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();
        }