Wednesday, August 7, 2019

How to Integrate Google reCaptcha with asp.net

Step 1. Include following js at top of the .aspx page.
src="https://www.google.com/recaptcha/api.js?onload=renderRecaptcha&render=explicit" async defer

Step 2. Put following code into .aspx page.
Kindly put starting tag(<>) and ending tag(</>)
div class="form-group"
                                    div id="ReCaptchContainer" /div
                                   label id="lblMessage" runat="server" clientidmode="static" label
/div

Step 3. Put following javascript at the bottom of the .aspx page.


         var your_site_key = 'SITE_KEY';
        var renderRecaptcha = function () {
            grecaptcha.render('ReCaptchContainer', {
                'sitekey': your_site_key,
                'callback': reCaptchaCallback,
                theme: 'light', //light or dark   
                type: 'image',// image or audio   
                size: 'normal'//normal or compact   
            });
        };

        var reCaptchaCallback = function (response) {
            if (response !== '') {
                jQuery('#lblMessage').css('color', 'green').html('Success');
            }
        };

        jQuery('button[type="button"]').click(function (e) {
            var message = 'Please check the checkbox';
            if (typeof (grecaptcha) != 'undefined') {
                var response = grecaptcha.getResponse();
                (response.length === 0) ? (message = 'Captcha verification failed') : (message = 'Success!');
            }
            jQuery('#lblMessage').html(message);
            jQuery('#lblMessage').css('color', (message.toLowerCase() == 'success!') ? "green" : "red");
        });
   

Step 4. Put following function into .aspx.cs file

public bool IsReCaptchValid()
    {
        var result = false;
        var captchaResponse = Request.Form["g-recaptcha-response"];
        var secretKey = "SECRET_KEY";
        var apiUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}";
        var requestUri = string.Format(apiUrl, secretKey, captchaResponse);
        var request = (HttpWebRequest)WebRequest.Create(requestUri);

        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                JObject jResponse = JObject.Parse(stream.ReadToEnd());
                var isSuccess = jResponse.Value("success");
                result = (isSuccess) ? true : false;
            }
        }
        return result;
    }

Step 5. Validate IsReCaptchValid() function on Submit button click event

if (IsReCaptchValid())
        {
//Code for insert and send email to user/client
}
else
        {
            lblMessage.InnerHtml = (IsReCaptchValid())
         ? "span style='color:green'>Captcha verification success /span>"
         : "span style='color:red'>Captcha verification failed /span>";
        }

Thursday, July 11, 2019

How to Create and Download pdf using iTextSharp

 StringReader sr = new StringReader(strMailBody.ToString());//strMailBody is a html string generated using html template.
        Document pdfDoc = new Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        using (MemoryStream memoryStream = new MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
            pdfDoc.Open();

            htmlparser.Parse(sr);
            pdfDoc.Close();

            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();


            // Clears all content output from the buffer stream               
            Response.Clear();
            // Gets or sets the HTTP MIME type of the output stream.
            Response.ContentType = "application/pdf";
            // Adds an HTTP header to the output stream
            Response.AddHeader("Content-Disposition", "attachment; filename=SponsorshipForm.pdf");

            //Gets or sets a value indicating whether to buffer output and send it after
            // the complete response is finished processing.
            Response.Buffer = true;
            // Sets the Cache-Control header to one of the values of System.Web.HttpCacheability.
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            // Writes a string of binary characters to the HTTP output stream. it write the generated bytes .
            Response.BinaryWrite(bytes);
            // Sends all currently buffered output to the client, stops execution of the
            // page, and raises the System.Web.HttpApplication.EndRequest event.

            Response.End();
            // Closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach.
            Response.Close();
        }

Friday, September 28, 2018

How to Redirect Whole Classic ASP site from http to https (Force SSL for Specific Pages)

You have to open .asp file which is included each and every page of whole website like header.asp, leftmenu.asp, bottom.asp.

Write given below code at the top of this .asp file.

<%
   If Request.ServerVariables("SERVER_PORT")=80 Then
      Dim strSecureURL
      strSecureURL = "https://"
      strSecureURL = strSecureURL & Request.ServerVariables("SERVER_NAME")
      strSecureURL = strSecureURL & Request.ServerVariables("URL")
      Response.Redirect strSecureURL
   End If
%>

Monday, January 9, 2017

How to move label, textbox or any control like (marquee in html) in windows application

1. Take timer control into windows form.
2. Then create timer1_Tick event into .cs file.
3. Write following code within timer1_Tick event.

label.Location = new Point(label.Location.X + 5, label.Location.Y);

            if (label.Location.X > this.Width)
            {
                label.Location = new Point(0 - label.Width, label.Location.Y);
            }

Tuesday, September 8, 2015

Function for check table is exist or not in sql database

public int CheckTable(string TableName)
        {
            int i = 0;
            string cmdText = @"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES
                       WHERE TABLE_NAME='" + TableName + "') SELECT 1 ELSE SELECT 0";
            i = (int)ExecuteScalar(cmdText,CommandType.Text,null,null);
            return i;
        }

Tuesday, May 12, 2015

How to Find Column From All Tables of Database

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
ORDER BY schema_name, table_name;

How to find a string from whole database?

DECLARE @MyValue NVarChar(4000) = 'something';

SELECT S.name SchemaName, T.name TableName
INTO #T
FROM sys.schemas S INNER JOIN
     sys.tables T ON S.schema_id = T.schema_id;

WHILE (EXISTS (SELECT * FROM #T)) BEGIN
  DECLARE @SQL NVarChar(4000) = 'SELECT * FROM $$TableName WHERE (0 = 1) ';
  DECLARE @TableName NVarChar(1000) = (
    SELECT TOP 1 SchemaName + '.' + TableName FROM #T
  );
  SELECT @SQL = REPLACE(@SQL, '$$TableName', @TableName);

  DECLARE @Cols NVarChar(4000) = '';

  SELECT
    @Cols = COALESCE(@Cols + 'OR CONVERT(NVarChar(4000), ', '') + C.name + ') = CONVERT(NVarChar(4000), ''$$MyValue'') '
  FROM sys.columns C
  WHERE C.object_id = OBJECT_ID(@TableName);

  SELECT @Cols = REPLACE(@Cols, '$$MyValue', @MyValue);
  SELECT @SQL = @SQL + @Cols;

  EXECUTE(@SQL);

  DELETE FROM #T
  WHERE SchemaName + '.' + TableName = @TableName;
END;

DROP TABLE #T;

Friday, May 1, 2015

How to get the row count for all tables in a SQL SERVER database

CREATE TABLE #counts
(
    table_name varchar(255),
    row_count int
)

EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'
SELECT table_name, row_count FROM #counts ORDER BY table_name, row_count DESC

How to drop all the tables from any database ?

DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR

SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE [' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME

OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql

WHILE (@@FETCH_STATUS = 0)
BEGIN
Exec SP_EXECUTESQL @Sql
FETCH NEXT FROM @Cursor INTO @Sql
END

CLOSE @Cursor DEALLOCATE @Cursor
GO

EXEC sp_MSForEachTable 'DROP TABLE ?'
GO