Add

Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

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...

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...

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...

Search Functionality In ASP.NET GridView

Introduction


Data Grid(GridView), One of the most used data representation format in ASP.NET where data is represented in a tabular format. ASP.NET offers you some basic features to manipulate the GridView elements like Sorting/Paging/Edit/Delete/Update operations. But in some scenarios you might need a searching functionality to implement in the GridView when the loaded data amount is very large (say 500 records).

Lets consider the above case when your GridView has some 500 records and you are searching for a single record then it might be difficult for you to look into all the damn pages of the GridView or/else to look into each record one by one. Are you going to do this ????? No, I am not coz I have a little brain and that's still working.

Behind The Scene


Lets jump into the coding part now...
Its a common notion that while implementing the search functionality we all collect the search data and then call a stored procedure with those parameters and  bind the returned data to the gridview.

But we will not go for calling any stored procedure for this. We will save the data in a session variable while binding the grid for the first time and then will perform all the searching things on it by LINQ.
In this Example we will consider a GridView of  3 columns named 
  • ID
  • Name
  • Email
We need to search the grid according to the above 3 columns. So First design the interface for Search Options.

Lets take a drop down with the above column names and then a text box, where you need to give some input in order to search the grid. And finally a button that has a click event that triggers our code for searching.

These things are upto you. You need to do these things by yourself; Its not a big deal you know it ;)

OK, There may be two scenarios where your datasource is a DataTable or a List :)

When The Data Source Is A List



Hold the list in a session variable first, while binding the GridView for the very first time, that we are going to use later.
  // hold the list in session
  Session["ClaimList"] = listClaim;
Now in the Search button click Event get the list from session variable first.
  // Get the claim list stored in session.
  listClaim = (List<SalesClaim>)Session["ClaimList"];
 Ok that's cool, we have the list in our hand now. Its time to implement search using the LINQ.

Lets take a Switch Case for the above said search columns and use the LINQ for filtering.
  switch (ddlSearch.SelectedValue)
     {
         case "ID": // Filter By ID 
             listClaim = listClaim.Where(p => p.ID.Equals(txtSearch.Text.Trim())).ToList();
             break;
         case "Name": // By Name
             listClaim = listClaim.Where(p => p.Name.ToUpper().Contains(txtSearch.Text.Trim().ToUpper())).ToList();
             break;
         case "Email": // By Email
             listClaim = listClaim.Where(p => p.Email.ToUpper().Contains(txtSearch.Text.Trim().ToUpper())).ToList();
             break;
     }
* ddlSearch is the filtering dropdown we have discussed above with the item values such as ID, 
   Name and Email
* txtSearch is the text box where the search text has to be entered.
* Trim() function is used to remove unwanted white spaces from the search text.
* ToUpper() function is used to convert text to upper case.

Up to this we are all done for searching the list, now bind the gridview and set the session variable again for further use.
   // Bind the grid view
   grdUser.DataSource = listClaim;
   grdUser.DataBind();
   grdUser.EmptyDataText = "No data found";

   // Set the list in session.
   Session["ClaimList"] = listClaim; 
 That's all for the List data source. And lets see how to do this if data source is a DataTable


When The Data Source Is A DataTable



Everything will be same as above except the LINQ. Here store the data table in session while binding the GridView for the very first time.
  // hold the list in session
  Session["ClaimTable"] = dt;
 Now in the Search button click Event get the list from session variable first.
  // Get the claim list stored in session.
  dt= (DataTable)Session["ClaimTable"];
 Ok that's cool, we have the list in our hand now. Its time to implement search using the LINQ.

Lets take a Switch Case for the above said search columns and use the LINQ for filtering.
   // hold the dropdown value in a variable
   string searchColumn = ddlSearch.SelecetedValue;
   
   // hold the search text entered in a variable
   string searchText = txtSearch.Text.Trim();
  Now lets apply LINQ to the DataTable.
   var result = (from myRow in dt.AsEnumerable()
       where myRow.Field<string>(searchColumn ).Equals(searchText)
       select myRow).AsDataView();
 Up to this we are all done for searching the list, now bind the gridview and set the session variable again for further use.
   // Bind the grid view
   grdUser.DataSource = result;
   grdUser.DataBind();
   grdUser.EmptyDataText = "No data found";

   // Set the list in session.
   Session["ClaimList"] = listClaim; 
That's it we have done everything to implement searching functionality in the ASP.NET GridView.

Happy Coding...

How To Call A JavaScript Method From C#

Introduction

This is very silly thing but used very often. Calling a JavaScript Method to do something from code behind(C#) is not so difficult.

You may need this thing in order to show a custom alert using jQuery modal pop up, or for custom redirection when you are in an IFrame.

Behind The Scene


Recently I was stuck in some redirection problems. The senario is something like, I was in some iframe but after session out I need to go back to the login page. But the control in not in my hand as I am inside an iframe.
I tried a lot of things but what resulted me is reloading or rendering the page I was referring inside the iframe. But my purpose was to redirect the whole page to login page.
So I did this using JavaScript, and I need to call a JavaScript function form the C# code when session is out.
There are some way in which you can call a JavaScript function from code behind.

  // redirect user to home page.
  ScriptManager.RegisterStartupScript(this, GetType(), "load", "closeDocumentIFrame();", true);
 
*closeDocumentIFrame(); is the method written in the aspx page
  // redirect user to home page.
  ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>closeDocumentIFrame();</script>"));
 
*closeDocumentIFrame(); is the method written in the aspx page
  // redirect user to home page.
  ClientScript.RegisterStartupScript(GetType(), "Load", String.Format("<script type='text/javascript'>window.parent.location.href ='{0}' </script>", "http://www.google.com"));
 
You can too add the JavaScript code here instead of writing another method in page level.

Happy Coding...