Add

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

Applying Custom Styles To Default GridView Pagination

Introduction


This article will demonstrate you how to add some customize styles to your asp.net GridView paging. In case you are using the default paging functionality in GridView/ListView/DataGrid then you may need this thing to make your website little cool and pretty.

 

Behind The Scene


Lets take the below grid view for our example. Here we are giving a CssClass to the default pager named "gridView"
 <asp:GridView ID="grd_MyExample" runat="server" CssClass="grid" AllowPaging="True" 
   OnPageIndexChanging="grd_MySalesClaims_PageIndexChanging" GridLines="None" >
    <PagerStyle CssClass="gridView"/>
    <Columns>
     <asp:BoundField DataField="UserID" />
     <asp:BoundField DataField="UserName" />
    </Columns>
 </asp:GridView>

OK, when this GridView gets loaded in the web page we can find the pagination indices are coming inside a "tr". So what we have to do in order to give some customize styles to it ????

Lets check the below CSS...
        .gridView {
            background-color: #fff;
            padding: 2px;
            margin: 2% auto;
        }

            .gridView a {
               cursor: hand;
               font-family: Verdana;
               font-size: 12px;
               padding: 2px 6px;
               border: solid 1px #ddd;
               text-decoration: none !important;
               color: Black;
            }

                .gridView a:hover {
                   background-color: #5D88AC;
                   color: #fff;
                   font-family: verdana;
                   cursor: pointer;
                }

            .gridView span {
                background-color: #5D88AC;
                color: #fff;
                font-family: verdana;
                font-size: 14px;
                padding: 2px 6px;
            }

        table.grid tr.gridView td {
            padding: 0px;
        }
Oh that's cool,Now if you look into the GridView in your webpage you can find a nice looking pagination is coming under it.

In the above CSS we have given some style to the elements like "td","tr","a" those present inside the element with class "gridView".

That's it we have just applied some customizes styles to the ASP.NET GridView.

Happy Coding...

Responsive Navigation Bar In Twitter Bootstrap 3

Introduction

Now-a-days Its very important to make your website compatible with the mobile devices. In order to make it possible you need to figure out somethings by learning how to make responsive websites.

Bootstrap 3 gives you a powerful platform to make your website responsive and here I am showing a live demo of making a responsive navigation bar in Twitter Bootstrap 3.

First download the below style-sheet and the js file.
 You can download the source code here too.
 

Behind The Scene

OK, before we start this thing you must be a bit familiar with the Bootstrap things like classes, components etc. if you are not aware of this thing just have a look into this link;

Download Bootstrap and Learn

Let's take a html page first and add the below references.
 <head>   
     <link href="css/bootstrap.min.css" rel="stylesheet">
     <script src="js/bootstrap.min.js"></script>
     <meta name="viewport" content="width=device-width, intial-scale=1.0">
 </head>
* This meta is required to enable the responsive design( this example will work if you remove this meta too)

Now we will see how to design the carousel slider.

Creating The Navigation Bar


Use the below code to make a responsive navigation bar.
    <div class="container">
        <div class="navbar navbar-default navbar-fixed-top">
            <div class="navbar-header">
               <button class="btn btn-scuuess navbar-toggle"
                        data-toggle="collapse"
                        data-target=".navbar-collapse">
                    <span class="glyphicon glyphicon-chevron-down"></span>
               </button>
            </div>
            <div id="logo">
                <a href="#"><h4>Tapan Kumar</h4> </a>
            </div>
        
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav navbar-right">
                <li class="nav active"><a href="#"> Home</a></li>
                <li class="nav"> <a href="#"> About</a></li>
                <li class="nav"><a href="#"> Blog</a></li>
                <li class="nav"><a href="#"> Article</a></li>
                <li class="nav"><a href="#"> Example</a></li>
                <li class="nav"><a href="#"> Contact</a></li>
            </ul>
        </div>
    </div>
  </div> 
In the above code we have given the div containing the navigation list a class named "navbar-collapse collapse", which tells the browser to hide the links (ul/li) in smaller screen resolutions.


And the button we have taken above the list inside the navbar-header div has two attributes named data-toggle which tells the browser that this is a toggle element and also has another attribute named data-target which tells the browser to show what and to hide what when user clicks on it.


The data-target is set to the class of the div, containing the navigation list.

Live demo




That's all, we have just designed a responsive navigation bar using Bootstrap 3.

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

Carousel Image Slider In Twitter Bootstrap 3

Introduction


Bootstrap 3 is a very powerful CSS framework that has the power to make the life of a web designer very very easy.

Image slider is a very important thing when web design comes to our mind. You definitely need this in your website to add some life to the inactive text contents in order to catch the attention of the user. Before the revolution brought by Bootstrap, we used to use different jQuery plugins to create image sliders. But after Bootstrap creating an image sliders made so easy for you like a piece of cake.

Bootstrap offers a lot many CSS classes, jQuery plugins. Here we will see how to create a carousel image slider using this Bootstrap 3.

First of all download the Bootstrap 3 files from here Download, and extract the zip file. All you need is the below tow files.

 

Behind The Scene


Once you downloaded  and extracted it from the above link, add a HTML page to the root folder. And give reference to the above said two files located in the JS and CSS folders respectively.
  <head>   
     <link href="css/bootstrap.min.css" rel="stylesheet">
     <script src="js/bootstrap.min.js"></script>
  </head>
Now we will see how to design the carousel slider.

Creating The Carousel Slider


Use the below code to create an impressive image slider.
 <div class="carousel slide" id="theCarousel" data-interval="3000">
    <div class="carousel-inner">
        <div class="item active">
            <img src="http://www.ansupalake.in/gallery/tapan%20kumar%201.JPG" alt="1" class="img-responsive" />                     
        </div>
        <div class="item ">
            <img src="http://www.ansupalake.in/gallery/tapan%20kumar%202.JPG" alt="2" class="img-responsive" />                    
        </div>
        <div class="item ">
            <img src="http://www.ansupalake.in/gallery/tapan%20kumar.JPG" alt="3" class="img-responsive" />                      
        </div>
    </div> 
 </div> 
*data-interval : This is the time interval in which you want to slide the images(here it is 3 sec).

The class "carousel slide"  tells bootstrap that this control contains a carousel image slider inside it. Then the div with class "carousel-inner" holds all the images you need to slide in the slider.

Inside the div with class "carousel-inner" put your image tags in separate divs with class "item", give the class "active" to the item you want to show first.

That's it you are just a step away to create the beautiful image slider. Just call the "carousel" plugin from jQuery in document.ready.
 <script type="text/javascript">
  (function () {
      $("#theCarousel").carousel();
   })();
 </script>
* "#theCarousel" is the id of the carousel div.

Here take a look how the simple carousel image slider looks like in jsfiddle.


Giving Indicators To The Carousel


You can add custom slider indicators also in the carousel. Just add a ordered list with class "carousel-indicators"
 <ol class="carousel-indicators">
    <li data-target="#theCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#theCarousel" data-slide-to="1"></li>
    <li data-target="#theCarousel" data-slide-to="2"></li>
 </ol>
* "data-target" attribute holds the id of the carousel and "data-slide-to" attribute holds the slide number starting from 0
* add class "active" with respect to the active element of your slide.

Here take a look how the simple carousel image slider with indicators looks like in jsfiddle.


Giving Custom Navigation To The Carousel 


Now lets give a "Prev" and "Next" navigation to our carousel slider. You can do this by just adding two anchor tags, below the last item div.

You can give a span inside the anchor tag to show icons, the code is below.
 <a href="#theCarousel" class="carousel-control left" data-slide="prev">
     <span class="icon-prev"></span>
 </a>
 <a href="#theCarousel" class="carousel-control right" data-slide="next">
     <span class="icon-next"></span>
 </a>

* The anchor tag contains the ID of the carousel in the href attribute.
* The left and right navigation control have a class of "carousel-control left" and "carousel-control right" respectively.
* The "data-slide" attribute has a value of "prev" and "next" accordingly.

 Here take a look how the simple carousel image slider with navigation looks like in jsfiddle.


Giving Captions To The Carousel Slider


Here in this section we will give a custom captions to the individual slides. This is very simple to do. Just add  a div with class "carousel-caption" just below each image tag. And you are free to place whatever you want inside that div.

See the below code for this.
 <div class="carousel-caption">
     <h4 class="text-left">Resting In Style</h4>
     <p class="text-left">Hi Everybody what's going on.....</p>
 </div>
 Here take a look how the simple carousel image slider with captions looks like in jsfiddle.


Now you have seen how to make a beautiful carousel with indicators, navigations and captions in Bootstrap 3.

Happy Coding...