Amazon Ad

Friday 31 January 2020

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3.

Step 1: Get your keys from
https://developers.google.com/recaptcha/intro

Step 2: Use the below example code:

.ASPX

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Captchav3._Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
        </div>
    </section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
        <h3>Login Form</h3>
        <asp:HiddenField ID="LoginId" runat="server" />
        Login:<asp:TextBox ID="txtLogin" runat="server"></asp:TextBox><br />
        Password:<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox><br />
        <asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
        <script src="https://www.google.com/recaptcha/api.js?render=6Lc7ctQUXXXXXzgKdup36qsMS-y_Hc6JCwAn_Bd"></script>
        <script>
            grecaptcha.ready(function () {
                grecaptcha.execute('6Lc7ctQUXXXXXzgKdup36qsMS-y_Hc6JCwAn_Bd', { action: 'umslogin' }).then(function (token) {
                    document.getElementById('<%= LoginId.ClientID%>').value = token;
            });
        });
        </script>
</asp:Content>



C#

 public partial class _Default : Page
    {
        private static string Token = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            Token = LoginId.Value;
        }
        private static ResponseToken response = new ResponseToken();
      
        private string CaptchaVerify()
        {
            if (response.score == 0)
            {
                var responseString = RecaptchaVerify(Token);
                response = JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);

            }
            return JsonConvert.SerializeObject(response);
            //return "";
        }
        private static string apiAddress = "https://www.google.com/recaptcha/api/siteverify";
        private static async Task<string> RecaptchaVerify(string recaptchaToken)
        {
            string url = apiAddress + "?secret=6Lc7ctQUXXXXXL--lngI_gIyRFyToplpKvZmMVlj&response=" + recaptchaToken;
            using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    string responseString = httpClient.GetStringAsync(url).Result;
                    return responseString;
                    //dynamic json = JsonConvert.DeserializeObject(responseString);
                    //return json.success;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            dynamic o = JsonConvert.DeserializeObject(CaptchaVerify());
            if (o.Success.Value)
            {
                if (o.score.Value > 0.3)
                {
                    Response.Write("<h1>Valid Request</h1>");
                    if (txtLogin.Text == "admin" && txtPassword.Text == "admin")
                    {
                        Response.Write("Logged In Successfully");
                    }
                }
                else
                {
                    Response.Write("<h1>Not a Valid Request</h1>");
                    Response.StatusCode = 403;
                }
            }
            else
            {
                Response.Write("<h1>Not a Valid Request</h1>");
                Response.StatusCode = 403;
            }

        }
    }
    public class ResponseToken
    {

        public DateTime challenge_ts { get; set; }
        public float score { get; set; }
        public List<string> ErrorCodes { get; set; }
        public bool Success { get; set; }
        public string hostname { get; set; }
    }

Wednesday 29 January 2020

How to restrict IP address for your .NET Application using web.config

Sometimes we face a situation when a certain request is deliberately accessing our resources with consent. In this situation we can block on ip or domain to access our resources in asp.net.



First of all you need to make sure that your OS allows IP restriction, for this, you should do the following:

Windows Server 2012 or Windows Server 2012 R2

On the taskbar, click Server Manager.
In Server Manager, click the Manage menu, and then click Add Roles and Features.
In the Add Roles and Features wizard, click Next. Select the installation type and click Next. Select the destination server and click Next.
On the Server Roles page, expand Web Server (IIS), expand Web Server, expand Security, and then select IP and Domain Restrictions.

Click Next.
On the Select features page, click Next.
On the Confirm installation selections page, click Install.
On the Results page, click Close.

Windows 8 or Windows 8.1

On the Start screen, move the pointer all the way to the lower left corner, right-click the Start button, and then click Control Panel.
In Control Panel, click Programs and Features, and then click Turn Windows features on or off.
Expand Internet Information Services, expand World Wide Web Services, expand Security, and then select IP Security.
Click OK.
Click Close.


Step 1

Change ApplicationHost.config file to allow ipsecurity

You will need to edit the project specific version of the ApplicationHost.config file

<section name="ipSecurity" overrideModeDefault="Allow" />

Step 2

Add the following section in web.config

<system.webserver>
<security>
         <ipSecurity allowUnlisted="false">
            <add ipAddress="192.168.100.1" /><!-- block ip 192.168.100.1 -->
            <add ipAddress="169.254.0.0" subnetMask="255.255.0.0" /><!-- block ip 169.254.0.0 with subnet -->
         </ipSecurity>
      </security>
</system.webserver>

or

You can create an xml file for the blocked list

Create an xml file for instance RestrictedIP.xml as
<?xml version="1.0"?>
<ipSecurity allowUnlisted="false">
       <add ipAddress="xxx.xxx.xxx.xxx" /><!-- block ip xxx.xxx.xxx.xxx here xxx represents your ip number -->
       <add ipAddress="xxx.xxx.x.x" subnetMask="255.255.0.0" /><!-- block ip xxx.xxx.x.x with subnet -->
</ipSecurity>

In your web.config file you need to do the following

<system.webserver>
<security>
         <ipSecurity configSource="RestrictedIP.xml" />
</security>

Friday 3 January 2020

How to upload download files from google drive using API v3 in asp.net c#

Below is the code to upload and download files using Google drive API v3 in asp.net c#. Please check the official page for your reference,

the link is https://developers.google.com/drive/api/v3/quickstart/dotnet. Before you start you must enable Google drive api access for your account. The mentioned link has all the details regarding the same.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Services;
using System.Web.Script.Services;
using System.Security.Cryptography.X509Certificates;

namespace GoogleDriveAPIWorking
{
    public partial class _Default : Page
    {

        //Reference from https://developers.google.com/drive/api/v3/quickstart/dotnet

        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/drive-dotnet-quickstart.json
        //, DriveService.Scope.DriveFile
        static string[] Scopes = { DriveService.Scope.Drive,
                          DriveService.Scope.DriveAppdata,
                          DriveService.Scope.DriveFile,
                          DriveService.Scope.DriveMetadataReadonly,
                          DriveService.Scope.DriveReadonly,
                          DriveService.Scope.DriveScripts };
        static string ApplicationName = "Testing Google Drive API";
        static DriveService service;

        private void initGService()
        {
            try
            {
                UserCredential credential;
                using (var stream = new FileStream(Server.MapPath("~/credentials.json"), FileMode.Open, FileAccess.Read))
                {
                    // The file token.json stores the user's access and refresh tokens, and is created
                    // automatically when the authorization flow completes for the first time.
                    string credPath = Server.MapPath("token.json");

                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                         GoogleClientSecrets.Load(stream).Secrets,
                         Scopes,
                         "user",
                         CancellationToken.None,
                         new FileDataStore(credPath, true)).Result;

                    string s = "Credential file saved to: " + credPath;

                }

                // Create Drive API service.
                service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
            }
            catch (Exception ex)
            {

            }

        }

        protected void Page_Load(object sender, EventArgs e)
        {


            if (!Page.IsPostBack)
            {

                initGService();
            }
            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name, webContentLink)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            //Console.WriteLine("Files:");
            //fileList.InnerHtml = "Your Files:<br/>";
            if (files != null && files.Count > 0)
            {
                int i = 1;
                foreach (var file in files)
                {
                    //fileList.InnerHtml += "<div style='text-decoration:underline;font-color:blue' onclick='downloadfile(\"" + file.Id + "\");return

false;'>" + file.Name + "</a><br/>";
                    //Console.WriteLine("{0} ({1})", file.Name, file.Id);

                    LinkButton lb = new LinkButton();
                    lb.ID = "id" + i;
                    lb.Text = file.Name;
                    lb.CommandArgument = file.Id + "|" + file.WebContentLink;
                    lb.Command += new CommandEventHandler(DownloadFile);
                    Panel1.Controls.Add(lb);
                    Panel1.Controls.Add(new LiteralControl("<br />"));
                    i++;
                }
            }
            else
            {
                fileList.InnerHtml = "No files found.";
            }
            //Console.Read();
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {


            byte[] by = fu.FileBytes;
            string filename = fu.FileName;
            string contentType = fu.PostedFile.ContentType;

            var fileMetadata = new Google.Apis.Drive.v3.Data.File()
            {
                Name = filename
            };

            FilesResource.CreateMediaUpload request;
            //using (var stream = new System.IO.FileStream(Server.MapPath("files") + "/photo.jpg", System.IO.FileMode.Open))
            using (var stream = fu.FileContent)
            {
                request = service.Files.Create(fileMetadata, stream, contentType);
                request.Fields = "id";
                request.Upload();
            }
            var file = request.ResponseBody;
            fileList.InnerHtml = "<br/><br/>" + "File ID: " + file.Id;

            //UploadFileToDrive(Server.MapPath("files") + "/photo.jpg");
            //Console.WriteLine("File ID: " + file.Id)
        }


        public void DownloadFile(object sender, EventArgs e)
        {

            LinkButton btn = (LinkButton)(sender);
            string[] arr = btn.CommandArgument.Split('|');
            string fileId = arr[0];
            string DownloadUrl = arr[1];

            string status = "";
            try
            {
                //create a folder "Downloaded" in your project, before running this code
                string saveTo = HttpContext.Current.Server.MapPath("Downloaded");
                var stream = new System.IO.MemoryStream();
                var request = service.Files.Get(fileId);

                Google.Apis.Drive.v3.Data.File file = request.Execute();
                string fname = file.Name;
                string fext = file.FileExtension;


                // Add a handler which will be notified on progress changes.
                // It will notify on each chunk download and when the
                // download is completed or failed.
                request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) =>
                {
                    switch (progress.Status)
                    {
                        case Google.Apis.Download.DownloadStatus.Downloading:
                            {
                                downloadstatus.InnerHtml += "<br/>Downloaded : " + (progress.BytesDownloaded.ToString());
                                status = "Downloaded : " + (progress.BytesDownloaded.ToString());
                                break;
                            }
                        case Google.Apis.Download.DownloadStatus.Completed:
                            {
                                downloadstatus.InnerHtml += "<br/>Download complete.";
                                status = "Success";
                                SaveStream(stream, saveTo + "//" + fname);
                                downloadstatus.InnerHtml += "File Saved to location " + saveTo;
                                break;
                            }
                        case Google.Apis.Download.DownloadStatus.Failed:
                            {
                                downloadstatus.InnerHtml = "<br/>(Download failed.";
                                status = "Failed";
                                break;
                            }
                    }
                };
                request.Download(stream);

            }
            catch (Exception ex)
            {
                status = ex.ToString();
            }
        }

        //Save file from stream to local location
        private static void SaveStream(System.IO.MemoryStream stream, string saveTo)
        {
            using (System.IO.FileStream file = new System.IO.FileStream(saveTo, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                stream.WriteTo(file);
            }
        }
    }
}

Thursday 1 February 2018

How to read soap envelope in c#

Hi guys,

I was given a task to read soap envelope and do some operations on it. Here is how I achieved it      

        [HttpPost]
        [ActionName("CDDService")]
        [Route("api/test/CDDService")]
        public void CDDService()
        {
            var b = RequestBody(HttpContext.Current.Request.InputStream);

            XmlDocument soapEnvelop = new XmlDocument();
            soapEnvelop.LoadXml(b);

            XmlNamespaceManager nsmgr = new XmlNamespaceManager(soapEnvelop.NameTable);
            nsmgr.AddNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
            nsmgr.AddNamespace("sch", "http://ws.test.com/rti/cdd/schema");
            nsmgr.AddNamespace("wsse", "http://dtest.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            nsmgr.AddNamespace("wsu", "http://dtest.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            string Username = soapEnvelop.DocumentElement.SelectSingleNode("//wsse:Username",nsmgr).InnerText;
            string password = soapEnvelop.DocumentElement.SelectSingleNode("//wsse:Password",nsmgr).InnerText;

            var cddRequest = soapEnvelop.DocumentElement.SelectSingleNode("//sch:cddRequest",nsmgr);

            string clientCandidateID = cddRequest.Attributes["clientCandidateID"].Value;
            string clientID = cddRequest.Attributes["clientID"].Value;

            string firstname = cddRequest.SelectSingleNode("candidateName/firstName").InnerText;
            string lastname = cddRequest.SelectSingleNode("candidateName/lastName").InnerText;

            string email = cddRequest.SelectSingleNode("webAccountInfo/email").InnerText;

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/xml;charset=utf-8";
            HttpContext.Current.Response.Write(@"<pingResponse><status>Success</status></pingResponse>");
            HttpContext.Current.Response.End();
        }

        private static string RequestBody(Stream InputStream)
        {
            var bodyStream = new StreamReader(InputStream);
            bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
            var bodyText = bodyStream.ReadToEnd();
            return bodyText;
        }

Hope it helps!

Saturday 27 January 2018

How to solve net::ERR_CONTENT_DECODING_FAILED in ASP.NET

Guys,

It took me three days to solve one simple problem which was caused due to ajax post form posting data to .asmx service webmethod. This error usually happens when there is an implementation of dynamic/stati compression in the project for ex. gzip or deflate compression. The code which worked is given below:

$.ajax({
                    url: 'test.asmx',
                    dataType:"json",
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    data: formData,
                    success: function (data) {
                        console.log(data);
                        data = data.d;
                        console.log('inside success response Text is '+this.responseText);
                        console.log(data);
                        console.log('Success');
                        checkData(this.responseText);
                    },
                    error: function (a, b, c) { console.log('Error');checkData(a.responseText); console.log(a); console.log(b); console.log(c); }
                });

Wednesday 13 December 2017

Upload multiple files using progressbars in HTML5 Javscript with webservices


Hi Guys,

Today I will tell you how to upload multiple files using progressbars and  webserivces. Below is the code I have used.


<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Courses</title>
    <script src="js/jquery-1.11.3.js"></script>
    <link href="css/bootstrap.css" rel="stylesheet" />
    <style>
        .pt10 {
            padding-top: 10px;
        }

        .pb10 {
            padding-bottom: 10px;
        }

        .fileinput-button input {
            position: absolute;
            top: 0;
            right: 0;
            margin: 0;
            opacity: 0;
            -ms-filter: 'alpha(opacity=0)';
            direction: ltr;
            width: 150px;
            cursor: pointer;
        }

        .fileinput-button {
            position: relative;
        }

        progress::-moz-progress-bar {
            background: green;
        }

        progress::-webkit-progress-value {
            background: green;
        }

        progress {
            color: green;
        }
    </style>
    <script src="js/jquery-1.11.3.js"></script>
</head>
<body>
    <div class="container">
        <div>
            <h4>Course Code : <span id="coursecode"></span></h4>
            <h4>TotalMarks : <span id="totalmarks"></span></h4>
            <h4>Term : <span id="term"></span></h4>
            <hr />
        </div>
        <div class="col-md-12 col-sd-12 col-xs-12">
            <div id="testimg" class="col-md-6 col-sd-6 col-sm-12 col-xs-12">
            </div>
            <div id="submitform" class="col-md-6 col-sd-6 col-sm-12 col-xs-12">
                <div class="pt10">
                    <input type="hidden" id="assignmentid" />
                    <input type="hidden" id="assignmentnumber" />
                    <input type="hidden" id="regnumber" />
                    <input type="hidden" id="code" />
                    <!--<div class="btn btn-success fileinput-button">
                    <i class="glyphicon glyphicon-plus"></i>
                    <input type="file" name="images" id="images" multiple>
                    <span>Add files...</span>
                </div>-->
                    <div class="btn btn-success fileinput-button pt10">
                        <i class="glyphicon glyphicon-plus"></i>
                        <input type="file" name="images" id="images" accept=".jpg, .png, .jpeg, .gif, .bmp, .tif, .tiff|images/*" multiple />
                        <span>Select files...</span>
                    </div>
                    <div>
                        <h5>To select multiple files, hold down the CTRL or SHIFT key while selecting files.</h5>
                    </div>
                    <div class="files pt10">
                    </div>
                    <!--<button class="btn btn-info" onclick="submitform();">Submit</button>-->
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        var spath = 'http://localhost:121231/testwebservice.svc';
        var s1path = 'http://localhost:64383/api/upload';
        var regno = '12X2323232';

        $(document).ready(function () {
            var coursecode = getParameterByName("code");
            loadassignment(coursecode);
        });

        function loadassignment(coursecode) {
            $.get(spath + '/GetOnlineAssignment/' + coursecode, function (data) {

                $("#assignmentid").val(data[0].ID);
                $("#assignmentnumber").val(data[0].AssignmentNumber);
                $("#regnumber").val(regno);
                $("#code").val(data[0].CourseCode);
                $("#coursecode").text(data[0].CourseCode);
                $("#totalmarks").text(data[0].TotalMarks);
                $("#term").text(data[0].TermId);
                def(data[0].ID);
            });

        }

        //load assignment picture
        function def(id) {
            var html = "";
            var Obj = new Object();
            Obj.Id = id;

            $.ajax({
                type: "Get",
                contentType: "application/json; charset=utf-8",
                url: s1path + "/GetAssignmentQuestion",
                dataType: "json",
                data: Obj,
                success: function (data1) {
                    console.log(data1);
                    if (data1.d == undefined) {
                    }
                    else {
                        data1 = data1.d;
                    }
                    if (data1.length > 0) {
                        if (data1[0].Message == "No Record Found") {
                        }
                        else {
                            html += "<img class='img-responsive' src='" + data1[0].File + "'>"
                        }
                        $("#testimg").html(html);
                    }
                    else {
                    }
                },
                error: function (result) {

                }
            });
        }

        function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }

        $('#images').on('change', function () {
            var images = document.getElementById('images');
            var length = images.files.length;
            for (i = 0; i < length; i++) {
                //
                if (images.files[i].size < 2048000) {
                    send(i);
                } else {
                    //
                    alert('The file length exceeded 2MB size.');
                }
            }
        });

        var counter = 0, processed = false, pg = 0;
        function send(i) {

            var images = document.getElementById('images');
            var length = images.files.length;
            var image = images.files[i];

            var formData = new FormData();
            formData.append('QuestionId', '1');
            formData.append('AnswerNo', '1');
            formData.append('EntryBy', '2103242342');
            formData.append('coursecode', 'DEG101');
            formData.append('image', image);

            var h = '<div id="r' + (counter) + '"><progress id="progressBar' + (counter) + '" value="0" max="100" style="width: 300px"></progress><h5 id="status' + (counter) + '"></h5><p id="loaded_n_total' + (counter) + '"></p></div>';
            $(".files").append(h);
            counter++;

            var xhr = new window.XMLHttpRequest();
            xhr.open("POST", s1path + "/SaveAssignment");

            //Upload progress
            xhr.upload.addEventListener("progress", function (evt) {
                if (evt.lengthComputable) {

                    if (!processed) {
                        var prog = Math.ceil(evt.loaded / evt.total) * 100;
                        $("#loaded_n_total" + i).html("Uplodaed " + evt.loaded + " bytes of " + evt.total);
                        $("#progressBar" + i).val(Math.round(prog));
                        $("#status" + i).html(images.files[i].name + " <b>" + Math.round(prog) + "</b> % uploaded");

                        //Do something with upload progress
                        console.log(prog + ' % completed.');
                        console.log('loaded ' + evt.loaded + ' of ' + evt.total);

                    } else {
                        var prog = Math.ceil(evt.loaded / evt.total) * 100;
                        $("#loaded_n_total" + (pg)).html("Uplodaed " + evt.loaded + " bytes of " + evt.total);
                        $("#progressBar" + (pg)).val(Math.round(prog));
                        $("#status" + (pg)).html(images.files[i].name + " <b>" + Math.round(prog) + "</b> % uploaded");
                    }

                }
            }, false);

            //after complete make things ok
            xhr.upload.addEventListener("loadend", function () {
                $("#status" + pg).html("<strong class='text-success'>" + images.files[i].name + " <i class='glyphicon glyphicon-ok'></i></strong>");
                $("#loaded_n_total" + pg).html("Uplodaed Successfully");
                $("#progressBar" + (pg)).val(100);
                if ((i + 1) == length) {
                    processed = true;
                }
                pg++;
            }, false);
            xhr.send(formData);
            return xhr;
        }

    </script>
</body>
</html>

Thanks
Ritesh

Tuesday 28 November 2017

Regex to find all catch blocks in Visual Studio



Find all catch blocks

catch\s*\(\w*\s*(.*\w)*\)\s*\b*\n*\{

Replace with
$&\n\t\t\tlogerror($1);


Here logerror(); is the method which captures the logs. The method errorlog can be called.

Wednesday 15 November 2017

Create custom error logs in your ASP.NET application including try/catch errors

Dear All,


Guys I finally managed to catch all the errors coming in the try/catch or outside this block using global.asax file. Below is the code to be done


Create a class named UErrorLog

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace test
{
    public class UException
    {
        public string UserId { get; set; }
        public string ProjectName { get; set; }
        public string PageName { get; set; }
        public string LineNumber { get; set; }
        public string ErrorMessage { get; set; }
        public string ErrorDescription { get; set; }
        public string IpAddress { get; set; }
        public string LogDateTime { get; set; }
        public int? MenuId { get; set; }
    }
    public class ContextInfo
    {
        public Exception ex { get; set; }
        public List<string> Session { get; set; }

    }
   
    public class UErrorLog : Exception
    {
        public UErrorLog()
        {

        }

        public UErrorLog(Exception ex)
        {
            logerror(ex);
        }

        int line = 0;
        string filename = "";

        public void logerror(Exception ex)
        {
            //System.Exception ex = System.Web.HttpContext.Current.Server.GetLastError();
            if (ex != null)
            {
                //This is included in try/catch to handle the case when the database goes down.
                try
                {
                    var stack = new System.Diagnostics.StackTrace(true);
                    //Get the details
                    //System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(ex, true);
                    System.Diagnostics.StackFrame frame =new System.Diagnostics.StackFrame();

                    foreach (System.Diagnostics.StackFrame f in stack.GetFrames())
                    {
                        if (f.GetFileName() != null && f.GetFileLineNumber() > 0)
                        {
                            frame = f;
                        }
                    }

                    if (frame != null)
                    {
                        //if (line != frame.GetFileLineNumber() && filename != frame.GetFileName().Substring(frame.GetFileName().LastIndexOf("\\") + 1))
                        //{
                            line = frame.GetFileLineNumber();
                            filename = frame.GetFileName().Substring(frame.GetFileName().LastIndexOf("\\") + 1);

                            if (!filename.Contains("Global.asax"))
                            {

                                UException err = new UException();
                                //Log this error in your database
                                if (System.Web.HttpContext.Current.Session["LoginName"] != null)
                                {
                                    err.UserId = System.Web.HttpContext.Current.Session["LoginName"].ToString();
                                }
                                else
                                {
                                    err.UserId = "";//Session["LoginName"].ToString();
                                }
                                err.ProjectName = "YourProjectName";
                                //err.PageName = this.GetType().BaseType.Name;

                                //Get the page name and line number
                                err.PageName = filename;
                                err.LineNumber = line.ToString();

                                //Error Messages
                                err.ErrorMessage = ex.Message;
                                if (ex.InnerException != null)
                                    err.ErrorDescription = ex.InnerException.ToString() != "" ? ex.InnerException.ToString() : "";
                                else
                                    err.ErrorDescription = "";

                                //Get IP Address
                                string ip = "";
                                ip = GetIPAddress();
                                if (ip == "" || ip == "::1")
                                {
                                    ip = LocalIPAddress();
                                }
                                err.IpAddress = ip;

                                err.LogDateTime = DateTime.Now.ToString("dd MMM yyyy hh:mm tt");

                                string str = "pInsertErrorLog";
                                SqlConnection con = new SqlConnection("data source=.;user id=sa;password=123;database=test");
                                if (con.State == System.Data.ConnectionState.Closed)
                                    con.Open();

                                SqlCommand cmd = new SqlCommand(str, con);
                                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                                cmd.Parameters.AddWithValue("@UserId", err.UserId);
                                cmd.Parameters.AddWithValue("@ProjectName", err.ProjectName);
                                cmd.Parameters.AddWithValue("@PageName", err.PageName);
                                cmd.Parameters.AddWithValue("@LineNumber", err.LineNumber);
                                cmd.Parameters.AddWithValue("@ErrorMessage", err.ErrorMessage);
                                cmd.Parameters.AddWithValue("@ErrorDescription", err.ErrorDescription);
                                cmd.Parameters.AddWithValue("@IpAddress", err.IpAddress);
                                cmd.Parameters.AddWithValue("@LogDateTime", err.LogDateTime);
                                cmd.Parameters.AddWithValue("@MenuId", err.MenuId);
                                cmd.ExecuteNonQuery();
                            }

                        //}//if (line != frame.GetFileLineNumber() && filename != frame.GetFileName().Substring(frame.GetFileName().LastIndexOf("\\") + 1))

                    }//if (frame != null)

                }
                catch (Exception e)
                {

                }
            }
        }

        //For ISP (Internet Service Provider) IP Address
        public static string GetIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string sIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(sIPAddress))
            {
                return context.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                string[] ipArray = sIPAddress.Split(new Char[] { ',' });
                return ipArray[0];
            }
        }


        //For LAN (Local Area Network) IP Address
        public string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

    }
}

In the global.asax file add the following code

protected void Application_Start(object sender, EventArgs e)
        {
            bool _insideFirstChanceExceptionHandler = false;
            AppDomain.CurrentDomain.FirstChanceException += (object source, FirstChanceExceptionEventArgs e1) =>
            {
                if (_insideFirstChanceExceptionHandler)
                {
                    // Prevent recursion if an exception is thrown inside this method
                    return;
                }
                try
                {
                    _insideFirstChanceExceptionHandler = true;
                    new UErrorLog().logerror(e1.Exception);
                    //throw new UErrorLog(e1.Exception);
                }
                catch
                {
                    // You have to catch all exceptions inside this method
                    _insideFirstChanceExceptionHandler = true;
                }
                finally
                {
                    _insideFirstChanceExceptionHandler = false;
                }
                //new UErrorLog().logerror(e1.Exception);
            };

        }


Table is


CREATE TABLE [dbo].[ErrorLog](
    [LogId] [int] IDENTITY(1,1) NOT NULL,
    [UserId] [varchar](50) NULL,
    [ProjectName] [varchar](150) NULL,
    [PageName] [varchar](150) NULL,
    [ErrorMessage] [varchar](max) NULL,
    [ErrorDescription] [varchar](max) NULL,
    [IpAddress] [varchar](20) NULL,
    [LogDateTime] [datetime] NULL,
    [MenuId] [int] NULL,
 CONSTRAINT [PK_ErrorLog] PRIMARY KEY CLUSTERED
(
    [LogId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO


-- =============================================
-- Author:        <Ritesh Tandon>
-- Create date: <Create Date,,>
-- Description:    <Record Error Log>
-- =============================================
CREATE PROCEDURE [dbo].[pInsertErrorLog]
    -- Add the parameters for the stored procedure here
    @UserId varchar(50),
    @ProjectName varchar(100),
    @PageName varchar(100),
    @ErrorMessage varchar(max),
    @ErrorDescription varchar(max),
    @IpAddress varchar(20),
    @LogDateTime varchar(150),
    @MenuId int=null
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    INSERT INTO ErrorLog(UserId,ProjectName,PageName,ErrorMessage,ErrorDescription,IpAddress,LogDateTime,MenuId)
    VALUES(@UserId,@ProjectName,@PageName,@ErrorMessage,@ErrorDescription,@IpAddress,@LogDateTime,@MenuId)
END

GO

Another method is to find and replace all catch block with your method name. See the below regular expression which can be easily used in visual studio find and replace with regex option.

Find all catch blocks

catch\s*\(\w*\s*(.*\w)*\)\s*\b*\n*\{

Replace with
$&\n\t\t\tlogerror($1);


Here logerror(); is the method which captures the logs. The method errorlog can be called.

And friends that it, you will get your own logs.

Monday 6 November 2017

Validate that user has logged in once at a time

Dear All,

I was given a task to validate that the user has logged in once at a time, i.e the user once logged in cannot login from same or other place until logs out.

Below is the code for the events on my Login Page:

//create object of global.asax class
Global obj = new Global();
 protected void Login_Click(object sender, EventArgs e)
        {  
            bool result=obj.GenerateSession(TextBox1.Text,true);
            if(result){
                Label1.Text = "Logged in Sucessfully";
            }
            else
            {
                Label1.Text = "You are already logged in";
            }
        }

        protected void Logout_Click(object sender, EventArgs e)
        {
            bool result=obj.DeleteValue(TextBox1.Text);
            if (result)
            {
                Label1.Text = "Logged Out Sucessfully";
            }
            else
            {
                Label1.Text = "You are already logged Out";
            }
        }


Below is the code of Global.asax file:

Tuesday 24 October 2017

Calling a webservice from ESP900 using AT Commands

Hi Guys,
I was given a task to get data from a web API in Arduino, I struggled a lot as there is no specific documentation on it. Finally I achieved it, below is the code for the same.
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of SIM900
const byte txPin = 3; // Wire this to Rx Pin of SIM900

SoftwareSerial SIM900(rxPin, txPin);
float temp;
int tempPin = 0;
void setup()
{
 SIM900.begin(9600);  
 Serial.begin(115200);  
 delay(1000);

SIM900.println("AT+CIPSHUT");
 delay(1000);
 printSerialData();

 SIM900.println("AT+CIPMUX=0");
 delay(2000);
 printSerialData();
 SIM900.println("AT+CGATT=1");
 delay(1000);
 printSerialData();
 //here my sim is of Airtel hence i have mentioned airtelgprs.com
 SIM900.println("AT+CSTT=\"airtelgprs.com\",\"\",\"\"");//setting the APN,2nd parameter empty works for all networks 
 delay(5000);
 printSerialData();
 SIM900.println();
 SIM900.println("AT+CIICR");
 delay(6000);
 printSerialData();
 SIM900.println("AT+CIFSR"); //init the HTTP request
 delay(2000); 
 printSerialData();
 SIM900.println("AT+CIPSTART=\"TCP\",\"echo.jsontest.com\",\"80\"");
 //SIM900.println("AT+CIPSTART=\"TCP\",\"test.in\",\"80\"");
 delay(2000);
 printSerialData();
 //String cmd="GET /test.php HTTP/1.1\r\nHost: test.in\r\nUser-Agent: SIM900_HTTP_CLIENT\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\n\r\n";
 String cmd="GET /title/ipsum/content/blah HTTP/1.1\r\nHost: echo.jsontest.com\r\nUser-Agent: SIM900_HTTP_CLIENT\r\nCache-Control: no-cache\r\nConnection: keep-alive\r\n\r\n";
 delay(6000);
 SIM900.println("AT+CIPSEND="+String(cmd.length()));
 if(SIM900.find(">")){
  Serial.println("Sending Request..");
  SIM900.print(cmd);
  String c;
  while(SIM900.available()>0){
    c=SIM900.readString();
     Serial.println(c);
    };
    delay(10000);
   while(SIM900.available()>0){
     c=SIM900.readString();
     Serial.println(c);
   }
   delay(10000);
   while(SIM900.available()>0){
     c=SIM900.readString();
     Serial.println(c);
   }
   
  
 }

 delay(1000);
 SIM900.write(0x1A);
 delay(2000);
 printSerialData();
//sendtemp();
SIM900.println("AT+CIPCLOSE");
printSerialData();

SIM900.println("AT+CIPSHUT");
delay(1000);
printSerialData();
}

void loop()
{
}


void printSerialData()
{
 while(SIM900.available()!=0)
 Serial.write(SIM900.read());
}

void sendtemp()
{
  temp = analogRead(tempPin);
  temp = temp * 0.48828125;
  Serial.print("TEMPERATURE = ");
  Serial.print(temp);
  Serial.print("*C");
  Serial.println();
  delay(5000);
 SIM900.println(temp);
 delay(3000);
 printSerialData();
 delay(3000);
   printSerialData();
}
Thanks
Ritesh

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...