Creating a Graph in ASP.NET with AJAX, HttpHandler and Morris.js Plugin

Introduction


Graphical representation is something that can make you understand every statistics without a mathematical calculation. It keeps the ability to represent the facts and figures in such a manner that you need not to give any pressure to your brain for calculations.

Lets take a simple example.

Consider yourself as an owner of a laptop selling company which sells thousands of laptops daily. As you are the owner of the company, you must have to keep track of your business if your sales volume is increasing day by day or decreasing. 

In order to keep track of your sales volume in a certain time period what you have to do ????
Yes, you will collect the facts and figure for a comparison and definitely for this comparison you need to do some calculations blah blah blah blah......

Here comes the concepts of Graph by seeing it only you will get a clear cut idea whether your business is growing or not.

Graph is the concept which will save your time, save the utilization of your brain and keeps you away from headache while analyzing a bunch of data.

So, Being a software developer it becomes an important part of development to get all the reports like user accounts, page hits, sales volumes etc. in a graphical representation, so that it will be very easy to understand what is actually happening in the background, and how the business is getting affected day by day.

Here in this article I will show you how to generate a light weight, nice looking Graph using Jquery and AJAX. If you surf in the internet you will get hundreds of plugins for generating Graphs. 
I will be using  morris.js for generating a nice looking graph. For more details about the plugin please visit their website.


   Download Source Code Here
   

Behind The Scene


In this example we will be using AJAX, JQURY along with HttpHandler in ASP.NET. So some basic idea on these topics will be highly appreciated.
You can download the above demo project for a quick demo.

Lets do this.

Front End Stuffs:


Add a new webform  to your solution (in visual studio). And add the below scripts to the header section of your page.
 <link rel="stylesheet" href="http://cdn.oesmith.co.uk/morris-0.4.3.min.css">
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
 <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
 <script src="http://cdn.oesmith.co.uk/morris-0.4.3.min.js"></script>
Now add a div to the body of your page with an id. Here I have given it an id of  "area-example" and put it blank.
 <div id="area-example"></div>
Ok, now we need to bind that div with our data in order to produce a graph. So here you go.....

Add the below script to the header section and I will explain it line by line.
    <script type="text/javascript">
        $(document).ready(function () {

            Morris.Area({
                element: 'area-example',
                data: Graph(),
                xkey: 'label',
                ykeys: ['value'],
                labels: ['value']
            });

        });
    </script>
Here in the above script I am trying to bind the div with a graph by calling the Morris.Area function and passing it some parameters.

For more details about Morris Charts you can visit their web.

Let me explain these parameters here we are passing.
  • element (mandatory) : This is the ID of the container where the graph will be rendered.
  • data (mandatory) : Here you can provide the data to bind your graph. It accepts data in JSON format. like
    [
      { label: '2012-10-01', value: 802 },
      { label: '2012-10-02', value: 783 },
      { label: '2012-10-03', value: 820 },
      { label: '2012-10-04', value: 839 },
      { label: '2012-10-05', value: 792 },
      { label: '2012-10-06', value: 859 },
      { label: '2012-10-07', value: 790 },
    ] 

    Or you can call a function to get data from server side. Here I am using AJAX for getting data from server side through a HTTPHandler.
  • xkeys (mandatory) : A string containing the name of the attribute that contains date (X) values.The date format should be in "YYYY-MM-DD" format.
  • ykeys (mandatory) : A string containing the name of the attribute the value for (Y).
  • labels (mandatory) : A list of strings containing labels for the data series to be plotted (corresponding to the values in the ykeys option).
In our case the data attribute is calling a Javascript function named Graph(). And I am calling a HttpHandler through AJAX. Find the function below.
        function Graph() {
            var data = "";

            $.ajax({
                type: 'GET',
                url: "http://localhost:60539/GraphHandler.ashx",
                dataType: 'json',
                async: false,
                contentType: "application/json; charset=utf-8",
                data: { 'GraphName': 'line' },
                success: function (result) {
                    data = result;
                },
                error: function (xhr, status, error) {
                    alert(error);
                }
            });

            return data;
        }
I am passing the HttpHandler url in the url attribute, and I am sending some data to the server of json type. You can find the dataType : 'json' and data: {'GraphName': 'line'} which I will be using in my handler.

And as you can see I am making this AJAX call synchronous by setting async attribute to false because I need the AJAX call to wait till the data was retrieved from the back end otherwise the graph will not be loaded.

* It is not recommended usually to make the AJAX call synchronous.

Once the call is completed and it get some data then inside the success attribute I am setting a variable and then at the end of the method returning it.

You need to put this method in script block we have created just before sometime.


Back End Stuffs:



Once the call is transferred to the handler you get the flexibility to use your coding ability to fetch data from server or whatever you want to do.

Here I will be using two classes named GraphData.cs to and GraphDataList.cs. Find the two classes below.
    public class GraphData
    {
        public string label { get; set; }
        public string value { get; set; }
    }
 
    public class GraphDataList
    {
        public List<GraphData> ListOfGraphData { get; set; }
    }
Find the below function that is responsible for fetching the graph data from the server. Basically this is a DAL function.
        public GraphDataList GetGraphData(string graphName)
        {
            GraphData graphData = null;
            GraphDataList graphDataList = new GraphDataList();
            graphDataList.ListOfGraphData = new List<GraphData>();

            try
            {
                using (var con = new SqlConnection(connectionString))
                {
                    con.Open();

                    SqlCommand cmd = new SqlCommand();
                    SqlDataAdapter SqlDadp = new SqlDataAdapter();
                   
                    cmd.Parameters.Add("@ProgramID", SqlDbType.Int);
                    cmd.Parameters["@ProgramID"].Value = programID;

                    cmd.CommandType = CommandType.StoredProcedure;

                    using (IDataReader dataReader = cmd.ExecuteReader())
                    {
                        while (dataReader.Read())
                        {
                            graphData = new GraphData();

                            graphData.label = Convert.ToString(dataReader["Date"].ToString());
                            graphData.value = Convert.ToString(dataReader["AmountPaid"].ToString());

                            graphDataList.ListOfGraphData.Add(graphData);
                        }
                        dataReader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogError(ex);
            }

            return graphDataList;
        }
As you can see in the this method I am calling a stored procedure and binding the GraphDataList with the returned values. Finally it returns the graphDataList.

Now we need to call this method from ProcessRequest method of the HttpHandler.

Here is the code for ProcessRequest method.
        public void ProcessRequest(HttpContext context)
        {
            System.Collections.Specialized.NameValueCollection forms = context.Request.Form;
            
            string chartName = context.Request["GraphName"];
           
            DataAccessLayer Dal = new DataAccessLayer();

            int programID = 1;

            if (!string.IsNullOrEmpty(chartName))
            {
                GraphDataList graphList = new GraphDataList();

                switch (chartName)
                {
                    case "line":
                        graphList = Dal.GetGraphData(chartName);
                        break;
                    case "donut":
                        graphList = Dal.GetGraphData(chartName);
                        break;
                }

                //oper = null which means its first load.
                var jsonSerializer = new JavaScriptSerializer();
                string data = jsonSerializer.Serialize(graphList.ListOfGraphData);
                context.Response.Write(data);
            }
        }
As you can see I am retrieving the parameter I have passed from AJAX, from the context.Request. Then we are almost done.

Just call the GetGraphData(chartName) with the graph name and hold the returned data in a list, we just created before 2-3 minutes ago.

We are just 1 step away from generating a nice looking graph.

Finally serialize the list with JavaScriptSerializer and parse it back. now you will get a beutiful graphical representation of your data.

Here I have plotted a graph between the time frame and the sales volume of a organization. And the graph looks like below

Graph

Hopefully you got something from this article and demonstration. If you want a complete demo then feel free to download the source code from above link.

If you like the article, a +1 will be very much appreciated, that is present at the top of the Page.

Happy Coding...

Simple Example On SQL CASE Expression

Introduction


If you are working with SQL SERVER then you are definitely going to need this article. Let me explain a bit briefly. 
You have one table named [User] where, you are storing 3 type of user's data such as
  • Clients data
  • Employee data
  • Admin data
Consider the case if you are asked to write a stored procedure that needs to fetch the respective user data. What will you do ? I can say most of the people will go for a If-Else condition to fetch the data.
But the Case expression will solve your problem in just simple way. Find it below....
   

Behind The Scene


First see if you want to fetch the client data, employee data and admin data in If-Else condition.

-- AUTHOR: Tapan kumar
-- CREATE DATE: --                                                  
-- PROJECT:          
-- CREATED BY: Tapan kumar
-- MODIFIED BY:   
-- MODIFICATION DATE: 28DEC2013  
-- Last MODIFICATIONS :                                                
-- DESCRIPTION/PURPOSE: Gets all user data according to filter type. 
-- UNIT TESTING :  [Getuseranddetailstosendexpirynotification] 
-------------------------------------------------------
CREATE PROCEDURE [dbo].[Getuseranddetailstosendexpirynotification] --1
  @FilterType INT
AS
  BEGIN
      -- @FilterType = 1 (will select clients only)
      -- @FilterType = 2 (will select employees only)
      -- @FilterType = 3 (will select admins only)
      
      SET nocount ON;

      IF @FilterType = 1 -- For selecting client data
        BEGIN
            SELECT id,
                   firstname,
                   lastname,
                   salary
            FROM   [user]
            WHERE  isclient = 1
                   AND .isdeleted = 0
        END
      ELSE IF @FilterType = 2 -- For selecting employee data
        BEGIN
            SELECT id,
                   firstname,
                   lastname,
                   salary
            FROM   [user]
            WHERE  isemployee = 1
                   AND .isdeleted = 0
        END
      ELSE IF @FilterType = 3 -- For selecting admin data
        BEGIN
            SELECT id,
                   firstname,
                   lastname,
                   salary
            FROM   [user]
            WHERE  isadmin = 1
                   AND .isdeleted = 0
        END
  END 

This is how your stored procedure will look like. You need to write the select query 3 times.

But here comes the use of CASE expression to save your time. See the below stored procedure to do the same thing..

-- AUTHOR: Tapan kumar
-- CREATE DATE: --                                                  
-- PROJECT:          
-- CREATED BY: Tapan kumar
-- MODIFIED BY:   
-- MODIFICATION DATE: 28DEC2013  
-- Last MODIFICATIONS :                                                
-- DESCRIPTION/PURPOSE: Gets all user data according to filter type. 
-- UNIT TESTING :  [Getuseranddetailstosendexpirynotification] 
-----------------------------------------------
ALTER PROCEDURE [dbo].[Getuseranddetailstosendexpirynotification] --1
  @FilterType INT
AS
  BEGIN
      -- @FilterType = 1 (will select clients only)
      -- @FilterType = 2 (will select employees only)
      -- @FilterType = 3 (will select admins only)
      
      SET nocount ON;

      SELECT id,
             firstname,
             lastname,
             salary
      FROM   [user]
      WHERE  1 = CASE
                   WHEN @FilterType = 1
                        AND isclient = 1
                        AND .isdeleted = 0 THEN 1
                   WHEN @FilterType = 2
                        AND isemployee = 1
                        AND .isdeleted = 0 THEN 1
                   WHEN @FilterType = 3
                        AND isadmin = 1
                        AND .isdeleted = 0 THEN 1
                   ELSE 0
                 END
  END 

In the above procedure you can see how I have written a single select query that behave differently depending on the @filterType .

Here is how it behaves
  • @filterType = 1, it will select the client data. 
  • @filterType = 2, it will select the employee data. 
  • @filterType = 3, it will select the admin data.
Hope this will be helpful to you.

Happy Coding...

Renaming Multiple Files Present In A Folder In Windows Form Applicaion

Introduction


Today I got scenario where I have to rename 100+ files with their names starting with XYZ_ and my task is to replace that XYZ_ with  ABC_. But I don't have that luxury to spend around 1-2 hours on renaming the files. So I find a way to rename the files through codding.

I made an application that is capable of replacing some text with your desired text.

Find the patten in the below image which thing I want to replace.


Files wth a prifix of XYZ_

This is a folder present in "E:\Test\Files" directory of my computer. As you can see the files present there in the above image you can find that all the files have a prefix of XYZ_ that needs to be changed to ABC_.

So if I go to change this by selecting all for renaming then it does not work it renames all the files with what I typed.

I tried to find out a standard solutions from the web but did not find one suitable and efficient one. So I developed a windows application to do the job. And here it is.  


   Download Source Code Here

Behind The Scene


Find the below image how I want the output.

When "XYZ_" replaced with "ABC_"


In order to do this I choose Windows application where I took two Text Boxes, those take the input from the user for replacement work. Find the below image and then I will explain what control does what ?

The Form with all the controls


* Find Text will take the text which you want to replace.
* Replace Text will take the text which will be replaced.
* Select File Type will give you to the option to select the type of file you want to rename.
* Rename Files button will open a folder selection dialog to select the respective folder you want. 


When you click on the Rename Files button with appropriate inputs then a folder selection dialog will be opened like below where you need to select the folder.

Folder selection Dialog


OK, now we are done with the design part. lets move to the codding part. Once you click on the  Rename Files button it will invoke the btnRename_Click event.

private void btnRename_Click(object sender, EventArgs e)
  {
      {
          //
          // This event handler was created by double-clicking the window in the designer.
          // It runs on the program's startup routine.
          //
          DialogResult result = folderBrowserDialog1.ShowDialog();

          if (result == DialogResult.OK)
          {
              int count = 0;
              lblError.Text = string.Empty;

              // This will get the folder you have selected.
              DirectoryInfo d = new DirectoryInfo(folderBrowserDialog1.SelectedPath);

              // Check if the Dropdown has some value or not.
              if (cmbFileType.SelectedText != "Select")
              {
                  try
                  {
                      // get only those files with an extension of the selected one.
                      FileInfo[] infos = d.GetFiles("*" + cmbFileType.SelectedItem.ToString());

                      // Make a loop to replace and rename the files.
                      foreach (FileInfo f in infos)
                      {
                          // Do the renaming here
                          File.Move(f.FullName, Path.Combine(f.DirectoryName, 
                          txtReplaceText.Text.Trim() + f.Name.Replace(txtFindText.Text.Trim(),"")));
                          count++;
                      }

                      // Show alert if no file with the selected extension is present.
                      if (infos.Count() == 0)
                      {
                          lblError.Text = "Destination folder has no " + " ' " 
                          + cmbFileType.SelectedItem.ToString() + " ' files.";
                      }
                      //Show success alert.
                      else if (count == infos.Count())
                      {
                          lblError.Text = "All ' " 
                          + cmbFileType.SelectedItem.ToString() + " ' files in '" 
                          + d +
                              " ' folder whose name contains a text of ' " + txtFindText.Text.Trim() +  
                              " ' has been replaced with ' " + txtReplaceText.Text.Trim() + " '.";
                      }
                  }
                  catch (Exception ex)
                  {
                      lblError.Text = "Some error occured";
                  }
              }
              else
              {
                  lblError.Text = "Please select a file type first.";
              }
          }
      }
  }

What I am doing in the above code ???

  1. In the above method I am getting the folder name from the the folder selection dialog and creating a DirectoryInfo .
  2. Selecting all the files with the extension selected from the combo box.
  3. Making a loop to replace the intended text with the desired text.
  4. Then show appropriate alert message to the user.
If you want to download the demo project then you can download it from the above download link.

Happy Coding...

Get The Height And Width Of Window In JQuery For Resopnsive Web Design

Introduction


Now-a-days responsive web design becomes minimum requirement while developing or designing a website. In today's market everyone wants his website to get render nicely in any type of device by keeping the reason in mind of the usage of mobile/tablet devices in business process.

Mobile devices have become an unavoidable part of our life. We are using those for almost everything like browsing, internet surfing, online shopping and also for all other important works like applying for a job, filling up any application for admission, Tax payment, for mobile recharge etc. So by keeping this vast use of mobile devices in mind it has became a must for all the website depending companies or organizations to serve their clients with the best user experience irrespective of the device they are using.

So, in order to make a website responsive you need to calculate the height, width of the browser in every step a user resizes the window.

Here is a simple way to find the width and height of a window when it got resized.
 

Behind The Scene


There is a feature in JQuery through which you can get the width and height of the window or document.

     $(document).height();
     $(document).width();

     $(window).height();
     $(
window).width(); 

But the problem with that thing is when the page loads for the first time you can get those values but lets think if the user resizes his browser then what will happen this website should render accordingly.

For doing so you need to check the height and width in every attempt user resizes the browser.

JQuery provides a method $(window).resize(), which get called when the the user is trying to resize the window. So you can get the height and width in every resolution of the window automatically.

Below I have taken two div to show the size of the window initially and after it gets resized.

  
  <div id="divInitial"></div>
  <div id="divResize"></div>


Then I have written the below JQuery to fetch the width and height every time user resizes his window.

  
  $(document).ready(function () {
      $("#divInitial").text("Initial Window width: " + $(window).width() + ", height: " + $(window).height() + ".");

      //Event to handle resizing
      $(window).resize(function () {
          var width = $(window).width();
          var height = $(window).height();
          $("#divResize").text("Window width: " + width + ", height: " + height + ".");
      });
  });


This will write the height and width in the div when user tries to resize the window. So you can assign the CSS to the controls accordingly for making your website responsive.

Live demo


** Click on the Live Demo link above to see the example in jsfiddle and go on resizing the window and see what happens.

Happy Coding...

What is Impersonation and How to Use it in ASP.NET

Introduction


Impersonation is the process used by ASP.NET to execute code in the context of an authenticated and authorized user.

Basically when IIS gets a request it check for the authorization of the user if he/she is authorized or not, by default, all ASP.NET code is executed using a fixed machine-specific account. If you want to change it then you can do this by using Impersonation.
   

Behind The Scene


Lets go a bit dipper to understand the use of it. Each time a request goes to IIS server the ASP.NET runs a security check to find if the user is authorized or not. And mostly ASP.NET uses the machine specific user account.

Consider a senario where you are logged on to a web application through your credentials and there you are trying to access a page which has a web service, that is being called to another computer. In this case your identity will not be shown in the web service's server instead the network credential(IIS credential) will be used for authentication.

For this reason, you can use impersonation to use your credentials for authentication in the second computer instead the network credentials.

And in ASP.NET you can do this in two manners like below;
  • Use an anonymous internet user account/authenticated user account.
  • Use a specific user account.
This thing can be done by turning the impersonate attribute to "true" in the identity element of the web config file.

      
  <identity impersonate="true" />

In this case ASP.NET impersonates to the authenticated user or to an anonymous internet user account.

      
  <identity impersonate="true"  userName="domain\username" password=" password"/>

In this case ASP.NET impersonates to a specific user account.

Happy Coding...

Simple API Integration In C# To Get IP Address

Introduction


API: Application Programing Interface provides a medium of interaction between software components. Now-a-days API programing is one of the most important component of software development.

Know more about API

API is something like URL that provides some intended data to the user. Let me explain it with some real world example.

Consider you have an account in Facebook and you want to access your friend list, status, photos through codding. Here Facebook is a total different entity which has no relation with your code(application), neither you can access Facebook's code nor its database. So how can you access those data in your FB account via your application ?

Here comes the role of API, Facebook provides an interface (URL/Graph API) that gives you all the intended details of your account, those can be used in any application. So your work is just to call the API provides by the client (here Facebook) and to use the response in your application. That's it.

In this article I will show you a simple API call process in C# to get the IP address of the device, where your application is being opened.

Here is the sample project you can download it and check.


   Download Source Code Here
   

Behind The Scene


The main aim of an API is to return some desired information to the user so that those can be used across any application. There are many ways in which the API gives the response to the user.

Mostly an API gives response in two formats
  • XML format
  • JSON format
 (Here I will show you a sample API call to get IP address using smart-ip.net API)

A sample example of XML response.
 <?xml version="1.0" encoding="UTF-8"?>
    <geoip>
        <source>smart-ip.net</source>
        <host>193.178.146.17</host>
        <lang>en</lang>
        <countryName>Ukraine</countryName>
        <countryCode>UA</countryCode>
        <city>Kiev</city>
        <region>Kyyivs'ka Oblast'</region>
        <latitude>50.4333</latitude>
        <longitude>30.5167</longitude>
        <timezone>Europe/Kiev</timezone>
    </geoip>
A sample example of JSON response.
  {
        "source":"smart-ip.net"
        "host":"193.178.146.17",
        "lang":"en",
        "countryName":"Ukraine",
        "countryCode":"UA",
        "city":"Kiev",
        "region":"Kyyivs'ka Oblast'",
        "latitude":50.4333,
        "longitude":30.5167,
        "timezone":"Europe/Kiev"
  }
 In this example we will consider the JSON formatted response from the API. So lets start our implementation.

Our API to get the IP details is http://smart-ip.net/geoip-json?callback=?. You can find the response like below if you click on the above link.
  ?({
      "source": "smart-ip.net",
      "host": "111.93.167.67",
      "lang": "en",
      "countryName": "India",
      "countryCode": "IN",
      "city": "Calcutta",
      "region": "West Bengal",
      "latitude": "22.5697",
      "longitude": "88.3697",
      "timezone": "Asia\/Calcutta"
  });
You can find out your IP address in the above JSON response from the API along with your location, time zone etc.

Now lets do codding to implement this in c#.

First create a class with the data members those you are expecting from the API response.
  public class ApiClass
  {
     public string host { get; set; }
     public string countryName { get; set; }
     public string city { get; set; }
  }
Here is the method to get the json response and to deserialize it.
 protected void CallAPI()
 {
     // Createa request to call the dropbox api.
     WebRequest request = WebRequest.Create(new Uri("http://smart-ip.net/geoip-json?callback=?"));
     request.Method = "GET";
     request.ContentType = "application/json";

     // Get the response.
     WebResponse response = request.GetResponse();

     // Read the response.
     string apiResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
     apiResponse = apiResponse.Replace("?(", "").Replace(");", "");

     // Deserialize the json object.
     ApiClass apiObj = new JavaScriptSerializer().Deserialize<ApiClass>(apiResponse);

     // Set the label text.
     lblIP.Text = apiObj.host;
     lblCity.Text = apiObj.city;
     lblCountry.Text = apiObj.countryName;
 }
In the above method I am creating a WebRequest object with the above API and mentioning the method and contentType.

Then get the response from the web request by calling GetResponse() method. Finally hold the response in a string and deserialize it to get the desired data.

That's it you have just learned how to call an API in C#. Download the sample source code from the above download link to see a live demo.

Happy Coding...

Simple Error Logging Mecanism In .Net Using Log4Net

Introduction


Exception Handling is a very important concept in software development. It does not matter how efficiently and optimized code you are writing, there is one thing you can not ignore it and that is an Exception.

There are various ways for logging errors, here I will be showing you one of the simplest way to log error/exception using Log4Net. I will only explain how to code it in your code snippet and will not go through its concepts. If you want some more knowledge then here is a link you can go for it.
 Log4Net


Here is the sample project you can download it and check.


   Download Source Code Here
   

Behind The Scene


Lets consider a condition where an exception can be produce. OK, lets take the simple and common one Attempted to divide by zero.

Every time you try to divide a number by 0 it will give an exception Attempted to divide by zero.

Step 1


Just take a simple web form and add a reference to the log4net dll.(Download the demo project and you will find the dll inside the bin folder.)

I have taken a button and on clicking on it I m trying to generate the Attempted to divide by zero exception.


Step 2


Now take a new class file and give it a name of Logging and add it to the project. Put the below code in this class.

  internal static readonly ILog log = LogManager.GetLogger
           (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Log the Exceptions
        /// </summary>
        /// <param name="ex">Exception</param>
        public static void LogError(Exception ex)
        {
            try
            {
                log.Info("<br/><hr/>Log Entry<hr/> ");
                log.Error(string.Format("<br/><b>Error Message : </b>{0}", ex.Message));
                log.Error(string.Format("<br/><b>Error StackTrace : </b>{0}", ex.StackTrace));

                //Log inner exceptions.
                while (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                    log.Error("<hr/><b>Inner Exception : </b>");
                    log.Error(string.Format("<br/>Error Message : {0}", ex.Message));
                    log.Error(string.Format("<br/>Error StackTrace : {0}", ex.StackTrace));
                    log.Error("<hr/>");
                }

                log.Info("<br/><hr/>");

            }
            catch (Exception logex)
            {
                log.Error(logex);
            }
        }
** Here in the while loop I am trying to iterate the exception if there is any inner exceptions.

Step 3


Just add the below line of code in the AssemblyInfo.cs class present in the Properties folder.
[assembly: log4net.Config.XmlConfigurator(Watch = true)

Step 4


Now add the below things to the web config file
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
 
** Add this in the configSections

And then add the below code inside configuration.
 <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="Errors/error.html"/>
      <appendToFile value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date - %message%newline"/>
      </layout>
    </appender>
    <root>
      <level value="INFO"/>
      <appender-ref ref="ConsoleAppender"/>
      <appender-ref ref="FileAppender"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
  </log4net>
** this will create a folder named Errors in the root folder and then will add a html file named error.html for the first time to write the error. Next time it will append the error.html file with new exceptions.

Step 5


OK we are almost done just generate an exception in the web form and log it. Just add the below code and go to the browser and click the button. Here you will catch an exception which will be logged in the error.html file in Errors folder.
 protected void btnLogError_OnClick(object sender, EventArgs e)
    {
        try
        {
            int num1 = 10;
            int num2 = 0;
            int num3;

            num3 = num1 / num2;

        }
        catch (Exception ex)
        {
            Logging.LogError(ex);
            //Response.Redirect()
        }
    }
Now we ave successfully logged the error using log4net.
This is a working example of error logging mechanisim. you can download the source code from the above link.


Happy Coding...