Friday, December 3, 2010

Weather Report

I Was feeling very cold from last two days and wanted to plan an outing so got to see weather forcast and from there got idea to develop this software which is a kind of Desktop Gadget.

image image

The Software uses AnimaOnline weather API that actually takes weather report from google.

The Project is developed using WPF technology for better look and flexibility.

Code for Getting Weather report is as follows.

Animaonline.Weather.WeatherData.GoogleWeatherData gd = Animaonline.Weather.GoogleWeatherAPI.GetWeather(Animaonline.Globals.LanguageCode.en_US, city);

Here ‘city’ is a string whose value can be set on choice of user and the weather report will be based on that only.

The Application can be download from

http://www.codeproject.com/KB/gadgets/Wreport.aspx

Monday, October 11, 2010

Using Binary file for storing data

Hi friends,

Hope you al are having great time and coding experience.

Today we’ll learn about using Binary file for storing data. From, some last days i was suffering with a problem. I used to subscribe for training and webinars but i rarely manage to attend them the reason is just that i used to forget about them so i decided to make a meeting reminder. i didn’t wanted to use any DATABASE for this hence i decided to use Binary file. here it' is.

image

Basically what here i’m going to discuss about is how to use binary file for storing data. here i used it for storing meeting information.

I have used the concept of serialization for writing an object into a binary file using binary formatter.

Serialization is the process by which a .NET object can be converted into a
stream, which can easily be transferred across a network or written to disk.
This stream can be converted into a copy of the original object through a
process called deserialization.

i made a class which define meetings and its detail and serialized it using [Serializable()]

here’s code

 [Serializable()]
        public class MeetingData
        {
            public string date;
            public string time;
            public string name;
            public string Description;
            public string Meeting_Id;
        }





This is class which object we are going to write into a binary file.


Following is the step we are going to follow.



  • Taking meeting infos
  • Adding that to MeetingData List
  • writing list to binary file

Taking info is simple, we can take it from UI on button click, here’s function for that


void addMeeting(MeetingData Md)
        {
            
            Md.date = CAl.SelectionRange.Start.Day.ToString() + "/" + CAl.SelectionRange.Start.Month.ToString();
            Md.time = txtTime.Text;
            Md.name = txtName.Text;
            Md.Description = txtDes.Text;
            Md.Meeting_Id = (Last_Meeting_Count + 1).ToString();
        }





CAl is callender control.


I have created a list of MeetingData class that would contain all meetings

 List<MeetingData> M_list = new List<MeetingData>();



Adding Meetings to list, here’s function for that


 void addtolist(MeetingData md)
        {
            M_list.Add(md);
        }



Writing to file usase Binary Formatter, here’s function for that


void WriteFile()
        {
            FileStream fs = File.OpenWrite("meeting.bin");
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, M_list);
                fs.Close();
            }
            catch (Exception x)
            {
                fs.Close();
            }
        }



Now on button click to add information to file here’s click event


private void button1_Click(object sender, EventArgs e)
        {
            MeetingData md = new MeetingData();
            addMeeting(md);
            addtolist(md);
            WriteFile();
            MainForm_Load(sender, e);
        }



Now while loading application we need to get data back from Binary file. Here we’ll do Deserialization


here’s MainForm_Load(sender, e) method


  private void MainForm_Load(object sender, EventArgs e)
        {            
            txtName.Focus();
            listView1.Items.Clear();
            FileStream fs = File.OpenRead("meeting.bin");
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                List<MeetingData> Md = bf.Deserialize(fs) as List<MeetingData>;
                foreach (MeetingData m in Md)
                {
                    listView1.Items.Add(new ListViewItem(new string[] {m.Meeting_Id, m.time + " " + m.date + @"\" + CAl.SelectionRange.Start.Month, m.name, m.Description }));
                }
                M_list = Md;
                fs.Close();
            }
            catch (Exception x)
            {
                fs.Close();
            }            
        }








Namespaces used are


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;



You can download complete setup and source code from here


http://meetingreminder.codeplex.com/

Thursday, September 30, 2010

Google Search for .NET application

image

Today we are going to talk about building a software that search throgh google right from your desktop. There can be many application of such software like:

  • for making search engine for searching books in your ebook reader
  • for pdf reader you can give a search engine for direct download and reading purposes
  • for image download
  • for searching and downloading videos

Now let’s come to the point “HOW TO CODE”

well for making such application is very simple

you’ll need an API(Application platform installer) for fetching results from Google. here’s the link to get API

http://code.google.com/p/google-api-for-dotnet/downloads/detail?name=GoogleSearchAPI_0.3.1.zip&can=2&q=

The application needs framework 3.5

Now for searching make click event of search button as

private void button1_Click(object sender, EventArgs e)
    {
        flowLayoutPanel1.Focus();
        flowLayoutPanel1.Controls.Clear();
        web = new GwebSearchClient(referrer);           
        w_result= web.Search(textBox1.Text, 20, "en-us");
        flowLayoutPanel1.Height = this.Height - panel1.Height - panel2.Height-5;
        for (int i = 0; i < w_result.Count; i++)
        {
            Label lblR = new Label();
            lblR.Text = w_result[i].Title;
            lblR.Width = flowLayoutPanel1.Width;
            Label lblCon = new Label();
            lblCon.Width = flowLayoutPanel1.Width;
            lblCon.Text = w_result[i].Content;
            lblCon.Top = lblR.Top + 10;
            LinkLabel lnkUrl = new LinkLabel();
            lnkUrl.Text = w_result[i].Url;
            lnkUrl.Top=lblCon.Top+10;
            lnkUrl.Width=flowLayoutPanel1.Width;               
            flowLayoutPanel1.Controls.Add(lblR);
            flowLayoutPanel1.Controls.Add(lblCon);
            flowLayoutPanel1.Controls.Add(lnkUrl);
        }
    }

I have taken flowlayout control for binding results

web is object of class “Google.API.Search.GwebSearchClient” provided with the API.

as you can see this is object of GwebSearchclient so it fetches the web results. in the same fashion you can extract image results by using GimageSearchClient, book results with GbookSearchClient etc

that’s all for today’s tips.

Happy coding :)

Thursday, September 9, 2010

Typed and Untyped Views

Hey Guys,
Howz  u doing ?
Now Lets Move Further...
In an ASP.NET MVC application, you pass data from a controller to a view by using view data and you have learnt about that in the last post of asp.net mvc..
you learned how to add items to the view data dictionary. There are two ways that you can use view data. First, you can use view data as an untyped dictionary. For example, the controller in Listing 1  returns a collection of products in its Index() action. And, the view in Listing 2 displays the collection by iterating through each item in the collection.
Listing 1 – Controllers\ProductController.cs

using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index()
{
// Create list of products
var products = new List<Product>();
products.Add(new Product("Laptop computer", 344.78m));
products.Add(new Product("Bubble gum", 2.00m));
products.Add(new Product("Toothpaste", 6.99m));
// Add products to view data
ViewData["products"] = products;
// Return view
return View();
}
}
}

Listing 2 – Views\Product\Index.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="MvcApplication1.Models" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% foreach (var item in (List<Product>)ViewData["products"])
{ %>
<li> <%= item.Name %> </li>
<% } %>
</asp:Content>

The view in Listing 2 is an untyped view. Notice that the products item from view data must be cast to a collection of product items before you can do anything with it.
Instead of using an untyped view, you can use a strongly-typed view. The controller in Listing 3 also returns a collection of products. However, in this case, the collection is assigned to the ViewData.Model property.
Listing 3 – Controllers\Product2Controller.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class Product2Controller : Controller
{
//
// GET: /Product2/
public ActionResult Index()
{
// Create list of products
var products = new List<Product>();
products.Add(new Product("Laptop computer", 344.78m));
products.Add(new Product("Bubble gum", 2.00m));
products.Add(new Product("Toothpaste", 6.99m));
// Add products to view data
ViewData.Model = products;
// Return view
return View();
}
}
}

Listing 4 – Views\Product2\Index.aspx


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% foreach (var item in Model)
{ %>
<li> <%= item.Name %> </li>
<% } %>
</asp:Content>

In Listing 3, the products are assigned to the ViewData.Model property. As an alternative to explicitly assigning data to the ViewData.Model property, you can pass the data to the View() method. In other words, the following two code blocks are equivalent :

// Assign products to Model
ViewData.Model = products;
return View();
// Assign products to Model
return View(products);

The view in Listing 4 is a typed view. In Listing 4, the Model property represents the collection of products as a collection of products. In other words, you don’t need to cast the view data to a collection of product items before you use the Model property.
The advantage of assigning a value to the ViewData. Model property is that you can cast the Model property automatically in a view. In a view, you can specify the type of object that the Model represents with the <%@ Page %> directive Inherits attribute.
This Inherits attribute casts the ViewData. Model property to an IEnumerable of Product.For this reason, in the body of the view, you do not need to cast the ViewData. Model property before looping through its items.

Creating Strongly Typed Views

Providing the proper value for the Inherits attribute for a typed view can be tricky.Because you don’t get any Intellisense for the Inherits attribute, you can easily make amistake, and your view generates an error.
Instead of creating a strongly typed view by hand, you can take advantage of the Visual Studio Add View dialog to create a strongly typed view automatically (see below Figure). You open this dialog by right-clicking a controller action and selecting the menu option Add View. Alternatively, you can right-click a folder located in the Views folder and select the menu option Add, View.
The Add View dialog includes a check box labeled Create a Strongly Typed View. If you check this check box, you can specify the view data class and the view content.
Note : The View Data Class drop-down list will be empty until you successfully build your application. It is a good idea to select the menu option Build, Build Solution before openingthe Add View dialog.
The View Data Class drop-down list enables you to pick a class from your project. The Inherits directive uses this class. For example, you can pick the Product class.
The View Content drop-down list enables you to pick the type of view that you want to create. Your options are Create, Details, Edit, Empty, and List. If you pick List, your viewdata model is cast to an IEnumerable of Products. Otherwise, if you pick any of the other options, your view data model is cast to a Product.
So We are done with the Typed and untyped Views....You Got the concept ?
If you have any Queries , Let us know...we would try our best to clarify it..
Hope this helps..
Enhanced by Zemanta

Wednesday, September 8, 2010

MDF TO XML Converter

In now a days for data processing one need to use XML instead of any other relational data source.Because the targeted customer may not have relational compatible software. And if they include needful files then the package becomes heavy so its better to use xml file.The presented software solves this problem.

here’s the look of the software that we are going to design

image

The working is very simple. Following are the steps for processing

  • Building Connectionstring of choosen database
  • Extracting table names of the database
  • Generating XML file of the tables data with the same schema

Connection String:

A typical connection string consist of following values

  • Server’s name
  • Database’s name
  • Username and Password (in case of SQL authentication)

All the values has been taken using UI then the user will be required to press a button to extract all the table names inside chosen Database.

The click event of that button is like this

private void btnTables_Click(object sender, EventArgs e)
     {
         string con = "Data Source=";
         con = con + txtServerName.Text + ";";
         con = con + "Initial Catalog=" + txtDbName.Text + ";";

         if (!(string.IsNullOrEmpty(txtPwd.Text) || string.IsNullOrEmpty(txtUid.Text)))
         {
             con = con + "uid=" + txtUid.Text + ";" + "pwd=" + txtPwd.Text;
         }
         else
         {
             con = con + "Integrated Security=True;User Instance=True;";
         }
         SqlConnection connect = new SqlConnection(con);
         try
         {
             connect.Open();
             string cmd = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'ORDER BY TABLE_NAME";
             SqlDataReader dst = SqlHelper.ExecuteReader(connect, CommandType.Text, cmd);
             comboBox1.Text = "Select Table";
             while (dst.Read())
             {
                 comboBox1.Items.Add(dst["TABLE_NAME"].ToString());
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }

     }

con is our connection string.

in the try block we have given code for extracting tables name.

the querry for extracting all the table names is

“SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'ORDER BY TABLE_NAME”

SqlHelper is a class which is available on internet, it increases the speed of processing.

If you don’t want to do this then you can implement it using the very conventional way that’s by creating SQLConnction and SQlcommand. here’s the code for that

private void btnTables_Click(object sender, EventArgs e)
     {
         string con = "Data Source=";
         con = con + txtServerName.Text + ";";
         con = con + "Initial Catalog=" + txtDbName.Text + ";";

         if (!(string.IsNullOrEmpty(txtPwd.Text) || string.IsNullOrEmpty(txtUid.Text)))
         {
             con = con + "uid=" + txtUid.Text + ";" + "pwd=" + txtPwd.Text;
         }
         else
         {
             con = con + "Integrated Security=True;User Instance=True;";
         }
         SqlConnection connect = new SqlConnection(con);
         try
         {
             string cmd = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'ORDER BY TABLE_NAME";            

             SqlCommand Scmd = new SqlCommand(cmd, connect);

             connect.Open();

             SqlDataReader dst = Scmd.ExecuteReader();
             comboBox1.Text = "Select Table";
             while (dst.Read())
             {
                 comboBox1.Items.Add(dst["TABLE_NAME"].ToString());
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }

     }

 

So by now we are done with extracting Tables name.

now user will choose the table, and the path where he want XML file to be saved.

here’s click event of the button for generating XML file

private void btnConvert_Click(object sender, EventArgs e)
        {
            string con = "Data Source=";
            con = con + txtServerName.Text+";";
            con = con + "Initial Catalog=" + txtDbName.Text + ";";

            if (!(string.IsNullOrEmpty(txtPwd.Text) || string.IsNullOrEmpty(txtUid.Text)))
            {
                con = con + "uid=" + txtUid.Text + ";" + "pwd=" + txtPwd.Text;
            }
            else
            {
                con = con + "Integrated Security=True;User Instance=True;";
            }
            SqlConnection connect = new SqlConnection(con);
            try
            {
                string filename;
                connect.Open();           

                string strcmd = "Select * from " + comboBox1.Text;
                DataSet dst = SqlHelper.ExecuteDataset(connect, CommandType.Text, strcmd);
                if(string.IsNullOrEmpty(txtLocation.Text))
                {
                    filename= "Xml_"+comboBox1.Text+".xml";
                }
                else
                {
                    filename = txtLocation.Text + "Xml_" + comboBox1.Text + ".xml";
                }
                FileStream stream = new FileStream(filename,FileMode.Create);
                dst.WriteXml(stream);
                connect.Close();
                MessageBox.Show("File Created");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

Here we again built our Connection string and executed command for extracting all the data from chosen table.

we have taken that data as dataset.

We took a filestream to write xml file.

then we wrote the file using

dst.WriteXml(stream);

dst is object of our dataset after creating file close connection to databse and prompt for creation of file.

We have generated Xml file in the same way you can generate Binary File too. for that be with us and wait for next post.

Thank you.

Happy Coding.

P.S: Yu may download the project from here

Wednesday, August 25, 2010

Accessing Rss Feeds

RSS is a format for an XML document that describes a list of items, such as blog entries or news headlines. The document may just be a stream of XML created on the fly rather than a static file. In this post, we’ll tell you to put an RSS document (using Version 2.0) on a page by using the XmlDataSource and DataList controls.

Well what you need for this are as given below

  • URL to a valid rss file it could be .xml,.rss,.aspx.,.php etc
  • kind of schema of that rss file we call Xpath, to reach upto the content you are interested in.

A typical Rss file is like this.

A typical schema is like this

<rss>
<channel>
<item>
<title></title>
<description></description>
<link></link>
<pubDate></pubDate>
<!--...-->
</item>
</channel>
</rss>

XPath rss/channel/Item tell that this is Item from where you want to start fetching from.

Now i guess enough theoretical content has been described.

let’s start working.

Create a web site,

in default page or wherever you want to display the feeds put xmldatasource.

in navigationurl put the url of the rsss file. one example is (http://www.spaces.msn.com/members/mauliksoni/feed.rss). if you are choosing this Rss then put XPath=”rss/channel/item”.

take a data list and set its DataSourceID to the id of XmlDataSource you have taken.

in datalist set enableViewState to false.

Item template would be like this.

<ItemTemplate>
              Title:<%# XPath("title") %><br /><br />
              Description:<%# XPath("description")%>
              <hr />
           </ItemTemplate>

 

XPath(“Tiitle”) will print content of the Title tag and Xpath(“description”) will print content inside Description tag.

complete markup code is like this

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:XmlDataSource ID="XmlDataSource1" runat="server"
            DataFile="http://www.spaces.msn.com/members/mauliksoni/feed.rss"
            XPath="rss/channel/item"></asp:XmlDataSource>
        <asp:DataList ID="DataList1" runat="server" DataSourceID="XmlDataSource1" EnableViewState="False">
            <ItemTemplate>
               Title:<%# XPath("title") %><br /><br />
               Description:<%# XPath("description")%>
               <hr />
            </ItemTemplate>
        </asp:DataList>
    </div>
    </form>
</body>
</html>

Run the project and see the feeds from your favorite site. Enjoy.

Monday, August 16, 2010

Generating Views

Inno design

Hello Guys ,

How is Your ride with asp.net mvc going  ?? :-)

Let's Understand the Views...

The set of views in an ASP.NET MVC application is the public face of the application. ASP.NET MVC views are responsible for rendering the HTML pages that people see when they visit your website.

Creating a View

The easiest way to create a new view is to create the view from an existing controller action. You can right-click anycontroller action within the Visual Studio Code Editor window and select the menu option Add View to create a new view automatically.

When you select the Add View menu option, the Add View dialog opens like below. This dialog enables you to set various view options. For example, you can specify whether a view uses a view master page.

For example, if you open a controller named Person and right-click the Index() action to add a view, and you leave the default options selected in the Add View dialog, you’ll get the view in like below Listing :

The above Listing looks almost like a standard HTML document. This view contains two <asp: Content> tags. Any content that you place within the first <asp: Content> tag appears in the <title> tag of the resulting HTML document. Any content that you place within the second <asp: Content> tag appears in the <body> tag of the resulting HTML document.
For example, the modified Index view in the below Listing  has been modified to display the current time.

Above Listing contains familiar HTML tags such as the <h1 > and <p> tags. You can put anything that you would put in a normal HTML page within a view including images, iframes, Java applets, Flash, and Silverlight. The view also contains a script that displays the time. The expression DateTime. Now. ToString("T") returns the current time.
You embed a script in a view by using the <% %> script delimiters.The <%= %> script delimiters are shorthand for <% Response. Write %>. You can use the <%= %> script delimiters to write the value  of an expression to the browser. The following two scripts do exactly the same thing:
<%= DateTime. Now. ToString("T") %>
<% Response.Write(DateTime. Now.ToString("T") ); %>
We'll Understand view in detail in the upcoming posts....Till than Generate your simple views and enjoy Mvc'ing... :-)
Hope this helps...

Sunday, August 15, 2010

Understanding Controllers and Actions


Hello Guys,
It has been so long we wrote on Asp.Net MVC….Sorry for the dis-continuity…But here we are , lets understand the controllers and actions…
ASP.NET MVC controllers are responsible for controlling the flow of application execution. When you make a browser request against an ASP.NET MVC application, a controller is responsible for returning a response to that request.
Controllers expose one or more actions. A controller action can return different types of action results to a browser.
For example
–> a controller action might return a view,
–> a controller action might return a file, or
–> a controller action might redirect you to another controller action.
Creating a Controller
The easiest way to create a controller is to right-click the Controllers folder in the Visual Studio Solution Explorer window and select the menu option Add, Controller.
Selecting this menu option displays the Add Controller dialog :
PersonController
If you enter the name PersonController, you get the code in below listing :
Controllers\ProductController.cs
codecontroller
Note : A controller name must end with the suffix Controller. If you forget to include the Controller suffix, you can’t invoke the controller.
Notice that a controller is just a class (a Visual Basic or C# class) that inherits from the base System.Web.Mvc. Controller class. The controller class in above Listing exposes one action named Index(). The Index() action is
the default action that is invoked on a controller when no explicit action is specified.
Notice that the Index() action returns an ActionResult. A controller action always returns an ActionResult (even if it doesn’t appear to be returning an ActionResult). The ActionResult determines the response returned to the browser. The Index() controller returns a view as its ActionResult.
A controller typically exposes multiple actions. You add actions to a controller by adding new methods to the controller. For example, the modified Person controller in the below Listing exposes three actions named Index() , Help(), and Details() .
updatingcontroller
Here’s what you would type into a browser address bar to invoke the different actions:
  • /Person/Index — Invokes the PersonController Index( ) action
  • /Person — Invokes the PersonController Index() action
  • /Person/Help — Invokes the PersonController Help() action
  • /Person/Details/34 — Invokes the PersonController Details() action with the value 34 for the Id parameter
You invoke a controller action by following a particular pattern that looks like this:
{controller}/{action}/{id}
Notice that when you invoke a controller, you don’t include the Controller suffix in the URL. For example, you invoke the Person controller with the URL /Person/Index and not the URL /PersonController/Index.
The default controller action is the Index() action. Therefore, the URL /Person/Index and the URL /Person both invoke the Person controller Index( ) action.
When you invoke a controller, you can supply an optional Id parameter. For example, the Details() action accepts an Id parameter. The URL /Person/Details/2 invokes the Details() action and passes the value 2 for the Id parameter. The name of the parameter is important. You must name the parameter Id.
Note : The default pattern for invoking controller actions is defined by the default route in the Global.asax file. If you want to modify the URL pattern for invoking actions, you canmodify this default route. we will learn more about creating custom routes when we will discuss Routing.
Returning Action Results
A controller action always returns an ActionResult. The ASP.NET MVC framework includes the following types of ActionResults.
  • ViewResult — Represents an ASP.NET MVC view.
  • PartialViewResult — Represents a fragment of an ASP.NET MVC view.
  • RedirectResult — Represents a redirection to another controller action or URL.
  • ContentResult — Represents raw content sent to the browser.
  • JsonResult — Represents a JavaScript Object Notation result (This is useful in Ajax scenarios).
  • FileResult — Represents a file to be downloaded.
  • EmptyResult — Represents no result returned by an action.
  • HttpUnauthorizedResult — Represents an HTTP Unauthorized status code.
  • JavaScriptResult — Represents a JavaScript file.
  • RedirectToRouteResult — Represents a redirection to another controller action or URL using route values.
Typically, you don’t directly return an ActionResult from a controller action. Instead, you call a controller method that returns an ActionResult. For example, if you want to return a ViewResult, you call the controller View() method.
Here’s a list of controller methods that return ActionResults :
  • View( ) — Returns a ViewResult
  • PartialView() — Returns a PartialViewResult
  • RedirectToAction() — Returns a RedirectToRouteResult
  • Redirect() — Returns a RedirectResult
  • Content() — Returns a ContentResult
  • Json( ) — Returns a JsonResult
  • File( ) — Returns a FileResult
  • JavaScript() — Returns a JavaScriptResult
  • RedirectToRoute( ) — Returns a RedirectToRouteResult
we will use these all methods in our programming further….
The goal of this post was to provide depth explanation of how you can create controllers and controller actions. here you were provided with an overview of the different types of ActionResults that can be returned from a controller action.
Enjoyed ?? This was all about Controller and We have tried our best to explain……
Hope this helps….

Friday, July 30, 2010

Network Sniffer

I was looking for this project from a long time before thanks to MJSniffer project from where i got definitions for Packets. Let’s make it today.

A sample program can be downloaded from here.

Network sniffer is a kind of application that sniffs or captures the information in incoming and out going packets from your Machine. There are so many such applications. So i decided to make on my own. so i guess you to will think the same.

Here i have added definitions for following protocols

  • TCP
  • UDP
  • IP
  • DNS
  • others are named as unknown

The designing is very simple. Just put a list view and add four column namely

  • serial number
  • Version
  • Source Address
  • Destination Address A button and a text box, take some labels to show some message as shown in picture (along with the text box).
    The look will ne as
image

the process is coding is very simple.

We get the input as an IP address of the machines where sniffer has to be performed. We will create a socket and will bind that to that address and it’ll go in infinite loop capturing all packets.

the top level variables mean those which are out of any methods are as follows

        List<byte[]> bufs = new List<byte[]>();
        List<IpHeader> A_ipheader = new List<IpHeader>();
        Socket Scksnif;
        delegate void insertinto(object obj);
        bool is_Snifing = false;
        private byte[] byteData = new byte[4096];

Bool Is_Sniffing tells whether sniffer is working or not.

scksnif is our socket.

Delegate will be used for accessing the controls as we will be using threads.

The click event of button will be as this

private void toolStripButton1_Click(object sender, EventArgs e)
      {
          if (!is_Snifing && !string.IsNullOrEmpty(txtMachinesIP1.Text))
          {
              try
              {
                  is_Snifing=true;                  
                  Scksnif = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
                  Scksnif.Bind(new IPEndPoint(Dns.GetHostByAddress(IPAddress.Parse(txtMachinesIP1.Text)).AddressList[0],0));
                  Scksnif.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);
                  byte[] byTrue = new byte[4] { 1, 0, 0, 0 };
                  byte[] byOut = new byte[4] { 1, 0, 0, 0 };
                  Scksnif.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);
                  this.toolStripButton2.Image = global::MyNWproject.Properties.Resources._48px_Process_stop_svg;
                  Scksnif.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(Callback), null);
              }
              catch (Exception x) { MessageBox.Show(x.Message, "Error Reported", MessageBoxButtons.OK, MessageBoxIcon.Error); }
          }
          else
          {
              is_Snifing = false;
              this.toolStripButton2.Image = global::MyNWproject.Properties.Resources.btnStart;
              Scksnif.Close();
          }
      }

 

In above event we had checked for two condition whether sniffer is working or not and whether IP address textbox is empty.

when these conditions are true we’ll move inside a try block.

Initiate a socket instance. The constructor of socket class is overloaded.

It’ll take three arguments

Addressfamily is set to InterNetwork for supporting all IPv 4 type address what we are using.

SocketType has been set to Raw

ProtocolType has been set to IP we want our socket to support IP.

After this we binded the socket to the IPEndPoint (created by IP entered by user).

IPEndPoint is set to ‘0’ port number to take any available port.

Next to this socketOption is created.

SocketLevel set the option that to which protocol socket is to Apply. we have created this for IP

Two byte arrays are created for Input and out put.

Socket.Iocontrol set the operating mode of  socket using Codes.

next to this just changed the Image of tool strip button and next to that started receiving packets.

But how can it be so simple, Just an event must not be enough for capturing packets isn’t it. Now see carefully beginerecieve method takes some parameters among them one is Asynccallback, that takes a parameter which is a method. Bytedata will be out packet received.

Callback method is like this.

void Callback(IAsyncResult result)
        {
            try
            {
                int Nums = Scksnif.EndReceive(result);
                ParseData(byteData, Nums);
                if (is_Snifing)
                {
                    byteData = new byte[4096];
                    Scksnif.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(Callback), null);
                }
            }
            catch (Exception x) { }
        }

 

Callback method takes a parameter named result of Type IAsyncResult which is an Interface.

Now Scksnif.EndReceive(result); ends pending async reads.the int returned by this will return the number of bytes received.

Parsedata method will create an instance of IPheader and will call a method that will perform filling data into the list view.

Rest of code is for re-beginning receiving  of data and hence calling callback recursively.

The Parse data method is As given below

void ParseData(byte[] buffer, int nums)
        {
            IpHeader ipheader = new IpHeader(buffer, nums);
            insertsniffdata_IP(ipheader);
        }


IPheader constructor takes two arguments the byte received and the number of bye received.

IPHeader Class is as.

class IpHeader
    {
         //IP Header fields
        private byte      byVersionAndHeaderLength;   //Eight bits for version and header length
        private byte      byDifferentiatedServices;    //Eight bits for differentiated services (TOS)
        private ushort    usTotalLength;              //Sixteen bits for total length of the datagram (header + message)
        private ushort    usIdentification;           //Sixteen bits for identification
        private ushort    usFlagsAndOffset;           //Eight bits for flags and fragmentation offset
        private byte      byTTL;                      //Eight bits for TTL (Time To Live)
        private byte      byProtocol;                 //Eight bits for the underlying protocol
        private short     sChecksum;                  //Sixteen bits containing the checksum of the header
                                                      //(checksum can be negative so taken as short)
        private uint      uiSourceIPAddress;          //Thirty two bit source IP Address
        private uint      uiDestinationIPAddress;     //Thirty two bit destination IP Address
        //End IP Header fields
        private byte      byHeaderLength;             //Header length
        private byte[]    byIPData = new byte[4096];  //Data carried by the datagram

        public IpHeader(byte[] byBuffer, int nReceived)
        {
            try
            {
                //Create MemoryStream out of the received bytes
                MemoryStream memoryStream = new MemoryStream(byBuffer, 0, nReceived);
                //Next we create a BinaryReader out of the MemoryStream
                BinaryReader binaryReader = new BinaryReader(memoryStream);

                //The first eight bits of the IP header contain the version and
                //header length so we read them
                byVersionAndHeaderLength = binaryReader.ReadByte();

                //The next eight bits contain the Differentiated services
                byDifferentiatedServices = binaryReader.ReadByte();

                //Next eight bits hold the total length of the datagram
                usTotalLength = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                //Next sixteen have the identification bytes
                usIdentification = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                //Next sixteen bits contain the flags and fragmentation offset
                usFlagsAndOffset = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                //Next eight bits have the TTL value
                byTTL = binaryReader.ReadByte();

                //Next eight represnts the protocol encapsulated in the datagram
                byProtocol = binaryReader.ReadByte();

                //Next sixteen bits contain the checksum of the header
                sChecksum = IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

                //Next thirty two bits have the source IP address
                uiSourceIPAddress = (uint)(binaryReader.ReadInt32());

                //Next thirty two hold the destination IP address
                uiDestinationIPAddress = (uint)(binaryReader.ReadInt32());

                //Now we calculate the header length

                byHeaderLength = byVersionAndHeaderLength;
                //The last four bits of the version and header length field contain the
                //header length, we perform some simple binary airthmatic operations to
                //extract them
                byHeaderLength <<= 4;
                byHeaderLength >>= 4;
                //Multiply by four to get the exact header length
                byHeaderLength *= 4;

                //Copy the data carried by the data gram into another array so that
                //according to the protocol being carried in the IP datagram
                Array.Copy(byBuffer,
                           byHeaderLength,  //start copying from the end of the header
                           byIPData, 0,
                           usTotalLength - byHeaderLength);
            }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "MJsniffer", MessageBoxButtons.OK,
                MessageBoxIcon.Error);
        }
        }

        public string Version
        {
            get
            {
                //Calculate the IP version

                //The four bits of the IP header contain the IP version
                if ((byVersionAndHeaderLength >> 4) == 4)
                {
                    return "IP v4";
                }
                else if ((byVersionAndHeaderLength >> 4) == 6)
                {
                    return "IP v6";
                }
                else
                {
                    return "Unknown";
                }
            }
        }

        public string HeaderLength
        {
            get
            {
                return byHeaderLength.ToString();               
            }
        }

        public ushort MessageLength
        {
            get
            {
                //MessageLength = Total length of the datagram - Header length
                return (ushort)(usTotalLength - byHeaderLength);
            }
        }

        public string DifferentiatedServices
        {
            get
            {
                //Returns the differentiated services in hexadecimal format
                return string.Format ("0x{0:x2} ({1})", byDifferentiatedServices,
                    byDifferentiatedServices);
            }
        }

        public string Flags
        {
            get
            {
                //The first three bits of the flags and fragmentation field
                //represent the flags (which indicate whether the data is
                //fragmented or not)
                int nFlags = usFlagsAndOffset >> 13;
                if (nFlags == 2)
                {
                    return "Don't fragment";
                }
                else if (nFlags == 1)
                {
                    return "More fragments to come";
                }
                else
                {
                    return nFlags.ToString();
                }
            }
        }

        public string FragmentationOffset
        {
            get
            {
                //The last thirteen bits of the flags and fragmentation field
                //contain the fragmentation offset
                int nOffset = usFlagsAndOffset << 3;
                nOffset >>= 3;

                return nOffset.ToString();
            }
        }

        public string TTL
        {
            get
            {
                return byTTL.ToString();
            }
        }

        public Protocol ProtocolType
        {
            get
            {
                //The protocol field represents the protocol in the data portion
                //of the datagram
                if (byProtocol == 6)        //A value of six represents the TCP protocol
                {
                    return Protocol.TCP;
                }
                else if (byProtocol == 17)  //Seventeen for UDP
                {
                    return Protocol.UDP;
                }
                else
                {
                    return Protocol.Unknown;
                }
            }
        }

        public string Checksum
        {
            get
            {
                //Returns the checksum in hexadecimal format
                return string.Format ("0x{0:x2}", sChecksum);
            }
        }

        public IPAddress SourceAddress
        {
            get
            {
                return new IPAddress(uiSourceIPAddress);
            }
        }

        public IPAddress DestinationAddress
        {
            get
            {
                return new IPAddress(uiDestinationIPAddress);
            }
        }

        public string TotalLength
        {
            get
            {
                return usTotalLength.ToString();
            }
        }

        public string Identification
        {
            get
            {
                return usIdentification.ToString();
            }
        }

        public byte[] Data
        {
            get
            {
                return byIPData;
            }
        }

    }

This class is commented so i think no need to describe it.

Method insertsniffdata_IP is as given below

void insertsniffdata_IP(IpHeader ipheader)
      {
          if (listView1.InvokeRequired)
          {
              insertinto inst = new insertinto(insert);
              listView1.BeginInvoke(inst, ipheader);               
          }
      }

This method checks whether listview need the meain thread to be accessed and if then access it using Main thread only. insertinto was our delegate and insert is the method that feels the data into the listView.

Insert method is as given

void insert(object obj)
       {
           IpHeader ipheader = (IpHeader)obj;
           listView1.Items.Add(new ListViewItem(new string[] { global.ToString(), ipheader.Version, ipheader.SourceAddress.ToString(), ipheader.DestinationAddress.ToString() }));
           A_ipheader.Add(ipheader);
           global++;
       }

The various values inserted you can check from the the definition of IPheader class.

A_ipheader is a list of Ipheader we are adding current Ipheader to that. this way the index of values in row of listview and that of A_ipheader will be same.

Now Another feature of our sniffer. Its not actually a feature but it’ll become so messy if i would have put all the data over front listview so i decided to put detail information on another window.

Another window will contain a listview with two column

  • Property name
  • property valueWhenever user will click on any of row of listview of main window this window will appear.
    For this create a Double click event of ListView.
    The event will be as given below

private void listView1_DoubleClick(object sender, EventArgs e)
       {
           ListView l= (ListView) sender;
           DetailSnifer obj = new DetailSnifer();
           obj.ipheader1=(IpHeader) A_ipheader[l.SelectedItems[0].Index];
           obj.ShowDialog();
       }

Here we have created an instance of Detailsniffer class which will create our window that’ll show the detail values extracted by the sniffer.

Ipheader1 is an instance of IpHeader class created in DeatilSniffer class. we set that equal to current instance of Ipheader using selected row index (as index of listview and index of A_IpHeader corresponds to same instance of Ipheader, as told above).

The load event of DetailSniffer is as shown Below

private void DetailSnifer_Load(object sender, EventArgs e)
        {
            IpHeader ipheader=(IpHeader) ipheader1;
            insert_ip(ipheader);
            switch (ipheader.ProtocolType)
            {
                case Protocol.TCP:
                    TCPHeader tcp= new TCPHeader(ipheader.Data,ipheader.Data.Length);
                    if (tcp.DestinationPort == "53" || tcp.SourcePort == "53")
                    {
                        insert_DNS(tcp.Data, (int)tcp.MessageLength);
                    }
                    insert_Tcp(tcp);
                    break;
                case Protocol.UDP:
                    UDPHeader udpHeader = new UDPHeader(ipheader.Data, ipheader.Data.Length);
                    if (udpHeader.DestinationPort == "53" || udpHeader.SourcePort == "53")
                    {

                        insert_DNS(udpHeader.Data,Convert.ToInt32(udpHeader.Length) - 8);                      
                    }
                    insert_UDP(udpHeader);
                    break;
                case Protocol.Unknown:
                    break;
                default:
                    break;
            }
        }

 

Here we have checked for which protocol is the ipheader corresponds to and extracted values according to that.

Insert methods used are as given below

Insert_Ip

void insert_ip(IpHeader ipheader)
       {
           listView1.Items.Add(new ListViewItem(new string[] { "Source", ipheader.SourceAddress.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "Destintion", ipheader.DestinationAddress.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "Version", ipheader.Version.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "Differentiated Srvice", ipheader.DifferentiatedServices.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "Total Length", ipheader.TotalLength.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "Identification", ipheader.Identification.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "Flags", ipheader.Flags.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "Fragmentation", ipheader.FragmentationOffset.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "TTL", ipheader.TTL.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "Data", Encoding.UTF8.GetString(ipheader.Data)}));
           listView1.Items.Add(new ListViewItem(new string[] { "Protocol", ipheader.ProtocolType.ToString() }));
           listView1.Items.Add(new ListViewItem(new string[] { "Checksum", ipheader.Checksum.ToString() }));
           textBox1.Text = Encoding.UTF8.GetString(ipheader.Data).GetHashCode().ToString();

       }

insert_Tcp

void insert_Tcp(TCPHeader tcp)
        {
            listView1.Items.Add(new ListViewItem(new string[] { "Source Port", tcp.SourcePort.ToString() }));
            listView1.Items.Add(new ListViewItem(new string[] { "Destination Port", tcp.DestinationPort.ToString() }));
            listView1.Items.Add(new ListViewItem(new string[] { "Sequence Number", tcp.SequenceNumber.ToString() }));
            listView1.Items.Add(new ListViewItem(new string[] { "Acknowledge Number", tcp.AcknowledgementNumber.ToString() }));
            listView1.Items.Add(new ListViewItem(new string[] { "Header Length", tcp.HeaderLength.ToString() }));
            listView1.Items.Add(new ListViewItem(new string[] { "Flags", tcp.Flags.ToString() }));
            listView1.Items.Add(new ListViewItem(new string[] { "Window Size", tcp.WindowSize.ToString() }));
            listView1.Items.Add(new ListViewItem(new string[] { "Check Sum", tcp.Checksum.ToString() }));
        }

 

insert_DNS

void insert_DNS(byte[] buffer, int nums)
        {
            DNSHeader dnsHeader = new DNSHeader(buffer, nums);                      
            listView1.Items.Add(new ListViewItem(new string[] {"Identification", dnsHeader.Identification}));
            listView1.Items.Add(new ListViewItem(new string[] {"Flags", dnsHeader.Flags}));
            listView1.Items.Add(new ListViewItem(new string[] {"Questions", dnsHeader.TotalQuestions}));
            listView1.Items.Add(new ListViewItem(new string[] {"Answer RRs", dnsHeader.TotalAnswerRRs}));
            listView1.Items.Add(new ListViewItem(new string[] {"Authority RRs", dnsHeader.TotalAuthorityRRs}));
            listView1.Items.Add(new ListViewItem(new string[] { "Additional RRs", dnsHeader.TotalAdditionalRRs }));
        }

insert_UDP

void insert_UDP(UDPHeader udpHeader)
        {
            listView1.Items.Add(new ListViewItem(new string[] {"Source Port", udpHeader.SourcePort}));
            listView1.Items.Add(new ListViewItem(new string[] {"Destination Port", udpHeader.DestinationPort}));
            listView1.Items.Add(new ListViewItem(new string[] {"Length", udpHeader.Length}));
            listView1.Items.Add(new ListViewItem(new string[] {"Checksum", udpHeader.Checksum}));
            listView1.Items.Add(new ListViewItem(new string[] { "Data", Encoding.ASCII.GetString(udpHeader.Data) }));
        }

Definitions of various Protocol header classes are as shown below.

UDPHeader:

class UDPHeader
  {
      private ushort usSourcePort;            //Sixteen bits for the source port number       
      private ushort usDestinationPort;       //Sixteen bits for the destination port number
      private ushort usLength;                //Length of the UDP header
      private short sChecksum;                //Sixteen bits for the checksum
      //(checksum can be negative so taken as short)             
      //End UDP header fields

      private byte[] byUDPData = new byte[4096];  //Data carried by the UDP packet

      public UDPHeader(byte[] byBuffer, int nReceived)
      {
          MemoryStream memoryStream = new MemoryStream(byBuffer, 0, nReceived);
          BinaryReader binaryReader = new BinaryReader(memoryStream);

          //The first sixteen bits contain the source port
          usSourcePort = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

          //The next sixteen bits contain the destination port
          usDestinationPort = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

          //The next sixteen bits contain the length of the UDP packet
          usLength = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

          //The next sixteen bits contain the checksum
          sChecksum = IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

          //Copy the data carried by the UDP packet into the data buffer
          Array.Copy(byBuffer,
                     8,               //The UDP header is of 8 bytes so we start copying after it
                     byUDPData,
                     0,
                     nReceived - 8);
      }

      public string SourcePort
      {
          get
          {
              return usSourcePort.ToString();
          }
      }

      public string DestinationPort
      {
          get
          {
              return usDestinationPort.ToString();
          }
      }

      public string Length
      {
          get
          {
              return usLength.ToString();
          }
      }

      public string Checksum
      {
          get
          {
              //Return the checksum in hexadecimal format
              return string.Format("0x{0:x2}", sChecksum);
          }
      }

      public byte[] Data
      {
          get
          {
              return byUDPData;
          }
      }
  }

TCPHeader

class TCPHeader
   {
       //TCP header fields
       private ushort usSourcePort;              //Sixteen bits for the source port number
       private ushort usDestinationPort;         //Sixteen bits for the destination port number
       private uint uiSequenceNumber = 555;          //Thirty two bits for the sequence number
       private uint uiAcknowledgementNumber = 555;   //Thirty two bits for the acknowledgement number
       private ushort usDataOffsetAndFlags = 555;      //Sixteen bits for flags and data offset
       private ushort usWindow = 555;                  //Sixteen bits for the window size
       private short sChecksum = 555;                 //Sixteen bits for the checksum
       //(checksum can be negative so taken as short)
       private ushort usUrgentPointer;           //Sixteen bits for the urgent pointer
       //End TCP header fields

       private byte byHeaderLength;            //Header length
       private ushort usMessageLength;           //Length of the data being carried
       private byte[] byTCPData = new byte[4096];//Data carried by the TCP packet

       public TCPHeader(byte[] byBuffer, int nReceived)
       {
           try
           {
               MemoryStream memoryStream = new MemoryStream(byBuffer, 0, nReceived);
               BinaryReader binaryReader = new BinaryReader(memoryStream);

               //The first sixteen bits contain the source port
               usSourcePort = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //The next sixteen contain the destiination port
               usDestinationPort = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //Next thirty two have the sequence number
               uiSequenceNumber = (uint)IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());

               //Next thirty two have the acknowledgement number
               uiAcknowledgementNumber = (uint)IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());

               //The next sixteen bits hold the flags and the data offset
               usDataOffsetAndFlags = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //The next sixteen contain the window size
               usWindow = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //In the next sixteen we have the checksum
               sChecksum = (short)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //The following sixteen contain the urgent pointer
               usUrgentPointer = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //The data offset indicates where the data begins, so using it we
               //calculate the header length
               byHeaderLength = (byte)(usDataOffsetAndFlags >> 12);
               byHeaderLength *= 4;

               //Message length = Total length of the TCP packet - Header length
               usMessageLength = (ushort)(nReceived - byHeaderLength);

               //Copy the TCP data into the data buffer
               Array.Copy(byBuffer, byHeaderLength, byTCPData, 0, nReceived - byHeaderLength);
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message, "MJsniff TCP" + (nReceived), MessageBoxButtons.OK, MessageBoxIcon.Error);
           }
       }

       public string SourcePort
       {
           get
           {
               return usSourcePort.ToString();
           }
       }

       public string DestinationPort
       {
           get
           {
               return usDestinationPort.ToString();
           }
       }

       public string SequenceNumber
       {
           get
           {
               return uiSequenceNumber.ToString();
           }
       }

       public string AcknowledgementNumber
       {
           get
           {
               //If the ACK flag is set then only we have a valid value in
               //the acknowlegement field, so check for it beore returning
               //anything
               if ((usDataOffsetAndFlags & 0x10) != 0)
               {
                   return uiAcknowledgementNumber.ToString();
               }
               else
                   return "";
           }
       }

       public string HeaderLength
       {
           get
           {
               return byHeaderLength.ToString();
           }
       }

       public string WindowSize
       {
           get
           {
               return usWindow.ToString();
           }
       }

       public string UrgentPointer
       {
           get
           {
               //If the URG flag is set then only we have a valid value in
               //the urgent pointer field, so check for it beore returning
               //anything
               if ((usDataOffsetAndFlags & 0x20) != 0)
               {
                   return usUrgentPointer.ToString();
               }
               else
                   return "";
           }
       }

       public string Flags
       {
           get
           {
               //The last six bits of the data offset and flags contain the
               //control bits

               //First we extract the flags
               int nFlags = usDataOffsetAndFlags & 0x3F;

               string strFlags = string.Format("0x{0:x2} (", nFlags);

               //Now we start looking whether individual bits are set or not
               if ((nFlags & 0x01) != 0)
               {
                   strFlags += "FIN, ";
               }
               if ((nFlags & 0x02) != 0)
               {
                   strFlags += "SYN, ";
               }
               if ((nFlags & 0x04) != 0)
               {
                   strFlags += "RST, ";
               }
               if ((nFlags & 0x08) != 0)
               {
                   strFlags += "PSH, ";
               }
               if ((nFlags & 0x10) != 0)
               {
                   strFlags += "ACK, ";
               }
               if ((nFlags & 0x20) != 0)
               {
                   strFlags += "URG";
               }
               strFlags += ")";

               if (strFlags.Contains("()"))
               {
                   strFlags = strFlags.Remove(strFlags.Length - 3);
               }
               else if (strFlags.Contains(", )"))
               {
                   strFlags = strFlags.Remove(strFlags.Length - 3, 2);
               }

               return strFlags;
           }
       }

       public string Checksum
       {
           get
           {
               //Return the checksum in hexadecimal format
               return string.Format("0x{0:x2}", sChecksum);
           }
       }

       public byte[] Data
       {
           get
           {
               return byTCPData;
           }
       }

       public ushort MessageLength
       {
           get
           {
               return usMessageLength;
           }
       }
   }

DNSHeader

class DNSHeader
   {
       //DNS header fields
       private ushort usIdentification;        //Sixteen bits for identification
       private ushort usFlags;                 //Sixteen bits for DNS flags
       private ushort usTotalQuestions;        //Sixteen bits indicating the number of entries
       //in the questions list
       private ushort usTotalAnswerRRs;        //Sixteen bits indicating the number of entries
       //entries in the answer resource record list
       private ushort usTotalAuthorityRRs;     //Sixteen bits indicating the number of entries
       //entries in the authority resource record list
       private ushort usTotalAdditionalRRs;    //Sixteen bits indicating the number of entries
       //entries in the additional resource record list
       //End DNS header fields

       public DNSHeader(byte[] byBuffer, int nReceived)
       {
           MemoryStream memoryStream = new MemoryStream(byBuffer, 0, nReceived);
           BinaryReader binaryReader = new BinaryReader(memoryStream);

           //First sixteen bits are for identification
           usIdentification = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Next sixteen contain the flags
           usFlags = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Read the total numbers of questions in the quesion list
           usTotalQuestions = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Read the total number of answers in the answer list
           usTotalAnswerRRs = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Read the total number of entries in the authority list
           usTotalAuthorityRRs = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Total number of entries in the additional resource record list
           usTotalAdditionalRRs = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());
       }

       public string Identification
       {
           get
           {
               return string.Format("0x{0:x2}", usIdentification);
           }
       }

       public string Flags
       {
           get
           {
               return string.Format("0x{0:x2}", usFlags);
           }
       }

       public string TotalQuestions
       {
           get
           {
               return usTotalQuestions.ToString();
           }
       }

       public string TotalAnswerRRs
       {
           get
           {
               return usTotalAnswerRRs.ToString();
           }
       }

       public string TotalAuthorityRRs
       {
           get
           {
               return usTotalAuthorityRRs.ToString();
           }
       }

       public string TotalAdditionalRRs
       {
           get
           {
               return usTotalAdditionalRRs.ToString();
           }
       }
   }

So finally we are done.

Happy Sniffing.

please leave your comments and question and suggestions :)