Thursday, April 29, 2010

How to get client "IP Address" using Asp.net /C#

I have found that in various forum newbie are very frequently asked this type of question how to get client IP or get mac address or country. So that I would like to share this for that user. Though its very simple but helpful.

Tip:1
To get the client IP you can use the following function
    string sClientIp=Request.UserHostAddress();
or
    string strHostName = System.Net.Dns.GetHostName();
        string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
 
Tip:2:To avoid Proxy IP:

To get the IP address of the machine and not the proxy use the following code
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
 This will returns the client ip in string format.

Code:
C#
    string ip;
    
    ip=Request.ServerVariables("HTTP_X_FORWARDED_FOR");
    if(ip==string.Empty)
    {
      ip=Request.ServerVariables("REMOTE_ADDR");
    }

REMOTE_ADDR does not always provide the users IP but rather the ISPs' IP address so first test HTTP_X_FORWARDED_FOR as this one is the real user IP.

Another important note to this the HTTP_X_FORWARDED_FOR may contain an array of IP, this can happen if you connect through a proxy.What also happens when this happens is that the REMOTE_ADDR may contain the proxy IP. To avoid this problem you can parse the HTTP_X_FORWARDED_FOR for first entery IP.

Code:
C#
    string ip;
    ip=Request.ServerVariables("HTTP_X_FORWARDED_FOR") ;
       if (!string.IsNullOrEmpty(ip))
         {
          string[] ipRange = ip.Split(',');
          string trueIP = ipRange[0].Trim();
         }
       else
        {
         ip=Request.ServerVariables("REMOTE_ADDR");
        }

Hope that it may helpful for the newbie.Please inform me if anything wrong in this article.

Wednesday, April 28, 2010

Validation control not work in FireFox or other browser

When I use validation control on asp.net it works for IE fine but failed to work in Firefox. After goggling I will find the solution. I share this code here, hope it may help others.

The ASP.Net validations controls only work client side in IE.
You can make them work in other browsers, coding as below:

C#

Page.Validate();

if ( !Page.IsValid )
{
return;
}
//Continue Your code

VB.NET

Page.Validate()

If Not Page.IsValid Then
Return
End If
'Continue Your code


Have a nice day.

Tuesday, April 27, 2010

how to get MAC address using C#

How to get the MAC address of  system using Asp.net/C#

Now I want to share with you some simple but important for our rapid development.
Here I want to discuss how to get system MAC address using c# ,

First way:
You need to import the System.Net namespace for this to work.
This will support IPv4 and IPv6.


NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
    {
        IPInterfaceProperties properties = adapter.GetIPProperties();
        adapter.GetPhysicalAddress().ToString();
    }

Second way:
public string GetMACAddress()
{
  ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  ManagementObjectCollection moc = mc.GetInstances();
  string MACAddress = String.Empty;
 foreach (ManagementObject mo in moc)
 {
     if (MACAddress == String.Empty) // only return MAC Address from first card   
           {
              if ((bool)mo["IPEnabled"] == true) MACAddress = mo["MacAddress"].ToString();
           }
      mo.Dispose();
 }

  MACAddress = MACAddress.Replace(":", "");
 return MACAddress;
}


You might want to also add  "mo["Caption"].ToString()" to test before the mac address so that you know which devices you are looking at.
Also, don't forget to use try/catch blocks on these as a NullPointerReference will kill the app.



How to get Client MAC address(Web):

To get the client MAC address only way we can rely on JavaScript and Active X control of Microsoft.It is only work in IE if Active X enable for IE. As the ActiveXObject is not available with the Firefox, its not working with the firefox and is working fine in IE.


This script is for IE only:

<script language="javascript">
     function showMacAddress(){

    var obj = new ActiveXObject("WbemScripting.SWbemLocator");
    var s = obj.ConnectServer(".");
    var properties = s.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");
    var e = new Enumerator (properties);


    var output;
    output='<table border="0" cellPadding="5px" cellSpacing="1px" bgColor="#CCCCCC">';
    output=output + '<tr bgColor="#EAEAEA"><td>Caption</td><td>MACAddress</td></tr>';
    while(!e.atEnd())

    {
        e.moveNext();
        var p = e.item ();
        if(!p) continue;
        output=output + '<tr bgColor="#FFFFFF">';
        output=output + '<td>' + p.Caption; + '</td>';
        output=output + '<td>' + p.MACAddress + '</td>';
        output=output + '</tr>';
    }

    output=output + '</table>';
    document.getElementById("box").innerHTML=output;
}
</script>

Hope that it may help you.Please inform me if any one get any wrong with me.
Thanks

Monday, April 26, 2010

How to detect browser Information in Asp.net

Sometimes some fresher asked me how they get browser information when using asp.net. In online you can find lots of resources about. I have placed this code snippet form msdn which may help newbie.

Place this code under any button event or Page_Load event:
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
+ "Type = " + browser.Type + "\n"
+ "Name = " + browser.Browser + "\n"
+ "Version = " + browser.Version + "\n"
+ "Major Version = " + browser.MajorVersion + "\n"
+ "Minor Version = " + browser.MinorVersion + "\n"
+ "Platform = " + browser.Platform + "\n"
+ "Is Beta = " + browser.Beta + "\n"
+ "Is Crawler = " + browser.Crawler + "\n"
+ "Is AOL = " + browser.AOL + "\n"
+ "Is Win16 = " + browser.Win16 + "\n"
+ "Is Win32 = " + browser.Win32 + "\n"
+ "Supports Frames = " + browser.Frames + "\n"
+ "Supports Tables = " + browser.Tables + "\n"
+ "Supports Cookies = " + browser.Cookies + "\n"
+ "Supports VBScript = " + browser.VBScript + "\n"
+ "Supports JavaScript = " +
browser.EcmaScriptVersion.ToString() + "\n"
+ "Supports Java Applets = " + browser.JavaApplets + "\n"
+ "Supports ActiveX Controls = " + browser.ActiveXControls
+ "\n"
+ "Supports JavaScript Version = " +
browser["JavaScriptVersion"] + "\n";

For more info please visits:
http://msdn.microsoft.com/en-us/library/3yekbd5b%28v=VS.100%29.aspx

How to bind Data in Customized Gridview

In asp.net gridview control is widely used control. It has lots of properties and attributes which help the developers for rapid development. Generally we can use Gridvew to show data in tabular format.
But It has a lots of events and features which is make this control a most powerful control for asp.net.
There are various types of field in Gridview such as:
1.BoundField
2.ImageField
3.HyperLinkField
4.ButtonField
5.TemplateField
6.CommandField
7.CheckBoxField

These fields gives developer more flexibility to customize the gridview. Paging is efficiently handling by Gridview it is one of cool feature of it. There are various way to bind data into gridview.

Today I want to focus how to bind data to a customized gridview. I have used this following way to bind customized gridview very frequently. Obviously,there may be more easier way to bind in customize gridview.
Here I have used BoundField,Templatefield to customize the grid.


Here is the aspx code for Gridview:

<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="False" OnRowCommand="gvUser_RowCommand"  ShowHeader="true">

<Columns>
                        <asp:boundfield datafield="User_ID" headertext="User ID" visible="false">
                        <asp:boundfield datafield="User_NAME" headertext="User Name"></asp:boundfield>
                        <asp:boundfield datafield="User_ADDRESS" headertext="User Address"></asp:boundfield>                       
                        <asp:templatefield headertext="Edit Info">
                            <itemtemplate>
                                <asp:linkbutton commandname="EditRowData" d="lbtnEdit" runat="server"></asp:linkbutton>
                            </itemtemplate>
                        </asp:templatefield>
                        <asp:templatefield headertext="Delete Info">
                            <itemtemplate>
                                <asp:linkbutton commandname="DeleteRowData" id="lbtnDelete" runat="server"></asp:linkbutton>
                            </itemtemplate>
                        </asp:templatefield>
                        <asp:templatefield headertext="User Status">
                            <itemtemplate>
                                <asp:linkbutton commandname="ActiveRowData" id="lbtnActiveRow" runat="server"></asp:linkbutton>
                            </itemtemplate>
                        </asp:templatefield>
                        
                    </asp:boundfield>
               
Here is the aspx.cs code:
I have placed this code under Search button click event:
 
protected void btnSearch_Click(object sender, EventArgs e)
    {  
      
        oUserDeatilList = GetList();//Get List Of data from database.
        //You can retrieve data as you like it may be in dataset or datatable no matter.
        //I have discussed after that scenario.


        DataTable oDataTable = new DataTable("Sample");
        oDataTable.Columns.Add(new DataColumn("User_ID", typeof(string))); ;
        oDataTable.Columns.Add(new DataColumn("User_NAME", typeof(string)));
        oDataTable.Columns.Add(new DataColumn("User_ADDRESS", typeof(string)));
   

        // list of User Info are loaded into dataTable
        if (oUserDeatilList != null)
        {
            if (oUserDeatilList.UserDetailList.Count > 0)
            {
                foreach (CUserDetail oUserDetail in oUserDeatilList.UserDetailList)
                {
                    DataRow row = oDataTable.NewRow();
                    row["User_ID"] = oUserDetail.UserID;
                    row["User_NAME"] = oUserDetail.PersonName;
                    row["User_ADDRESS"] = oUserDetail.UserAddress;
               
                    oDataTable.Rows.Add(row);
                }
            }
        }
        gvUser.Columns[0].Visible = true;
        gvUser.Columns[1].Visible = true;
        gvUser.Columns[2].Visible = true;
        gvUser.Columns[3].Visible = true;
        gvUser.Columns[4].Visible = true;
        //bind data to gridview
        gvUser.DataSource = oDataTable;
        gvUser.DataBind();
        gvUser.Columns[0].Visible = false;

        // to generat linkButton text
        for (int i = 0; i < gvUser.Rows.Count; i++)
        {
            LinkButton lblEdit = ((LinkButton)gvUser .Rows[i].FindControl("lbtnEdit"));
            lblEdit.Text = "Edit";//you can do whatever you like with this control's property

            LinkButton lblDelete = ((LinkButton)gvUser.Rows[i].FindControl("lbtnDelete"));
            lblDelete.Text ="Delete";//you can do whatever you like with this control's property

            LinkButton lblActive = ((LinkButton)gvUser.Rows[i].FindControl("lbtnActiveRow"));
            lblActive.Text = "Active";//you can do whatever you like with this control's property
        }
    }

  
   protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridViewRow gvRow = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
        string sButtonText = ((LinkButton)e.CommandSource).CommandName;
        string sUserID = gvRow.Cells[0].Text;
     

        if (sButtonText.Equals("EditRowData"))
        {
            if (sUserID.Length > 0)
            {
                LinkButton oLinkButton = (LinkButton)gvRow.Cells[5].FindControl("lbtnEdit");
                string sUrl = "AddEditUser.aspx?" + USERID + "=" + sUserID;
                Response.Redirect(sUrl, false);
                //do whatever you like
            }
        }
        else if (sButtonText.Equals("DeleteRowData"))
        {
            if (sUserID.Length > 0)
            {
                LinkButton oLinkButton = (LinkButton)gvRow.Cells[5].FindControl("lbtnDelete");
                //or do whatever you like
            }
        }
        else if (sButtonText.Equals("ActiveRowData"))
        {
            if (sUserID.Length > 0)
            {
                LinkButton oLinkButton = (LinkButton)gvRow.Cells[5].FindControl("lbtnActiveRow");
                if (oLinkButton.Text.Equals("ACTIVE")
                {
                    oLinkButton.Text = "INACTIVE";
                }
                else
                {
                     oLinkButton.Text = "ACTIVE";
                }
                //do whatever you like
             
            }
        }      
    }

Hope that it may help you.

Tuesday, April 20, 2010

Unable to start debugging on the web server. Could not start ASP.NET or ATL Server debugging.....

Yesterday I had started my work at new work station. Very recently I needed to test a web application on localhost. I found that IIS is not installed so that I installed it myself. Then I hosted it in localhost and try run but showed me an error. Today I want to share with you how to solve this problem.

Problem:
After developing an ASP.NET Web application by using localhost as the Web server, and config the Web site settings in Microsoft Internet Information Services (IIS) to use the localhost or specific IP address for Web Site Identification. Then, when I try to run the application, then receive the following error message:

Error while trying to run project: Unable to start debugging on the web server. Could not start ASP.NET or ATL Server debugging.
Verify that ASP.NET or ATL Server is correctly installed on the server.


Solution:
After search in google I have found lots of solution. But suddenly remembered that I have insatalled IIS after .net framework installed. I hope that this error occurs because Microsoft Internet Information Server (IIS) is not functioning properly. Then to resolve this issue IIS must be registered with .net framework. You can registered IIS with .net framework by executing this command from command prompt:

>C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\aspnet_regiis -i

Now its fixed my problem.
Have a nice day!!

Monday, April 19, 2010

Single Sign on (SSO) Using Cookie in asp.net

There are various ways to use Single Sign on(SSO) in asp.net web application. We can use cookies, session (state server), SAML and web services etc. Now we would like to give a brief overview of how to use cookie to implement Single Sign on(SSO) in asp.net web application.

Assume that we have two web application hosted on different virtual directory but under same domain. As for example, our root domain is: http://www.cookietest.com and
Other two virtual directory hosted under this domain are
http://www.cookietest.com/cookiesite1/Login.aspx
http://www.cookietest.com/cookiesite2/Default.aspx

If we login successfully in cookiesite1 then it writes the login information in cookie and now opens another tab or a new window in same browser (IE, FF whatever you like). Place this address http://www.cookietest.com/cookiesite2/Default.aspx in address bar logged in automatically in cookiesite2. When we try to access in cookiesite2 –> Default.aspx it checks the login information from cookie. If desired value found in cookie then you logged in automatically. Remember you need to enable cookie in your browser for all of these activities.

Configuration:
1. Web.Config
Before coding we need to some configure in our web.config file. Though cookiesite1 and cookiesite2 are in different virtual directory their web.config file must contains the same machine validationKey, decryptionKey and validation.

Like this,

<machineKey validationKey="282487E295028E59B8F411ACB689CCD6F39DDD21E6055A3EE480424315994760ADF21B580D8587DB675FA02F79167413044E25309CCCDB647174D5B3D0DD9141"
decryptionKey="8B6697227CBCA902B1A0925D40FAA00B353F2DF4359D2099"
validation="SHA1" />


2. IIS
In IIS->Directory security tab add the "ASPNET Machine Account" user and set the full rights.

Coding:
Write cookie after login complete:
Place this code in cookiesite1->Login.aspx.cs
If(login_Successful)
{
//Create a new cookie, passing the name into the constructor
HttpCookie cookie = new HttpCookie(“strCookieName”);

//Set the cookies value
cookie.Value =”set_cookie_value”;

//Set the cookie to expire in 5 minute
DateTime dtNow = DateTime.Now;
TimeSpan tsMinute = new TimeSpan(0, 0, 5, 0);
cookie.Expires = dtNow + tsMinute;

//Add the cookie
Response.Cookies.Add(cookie);

Response.Write("Cookie written. ");
}
Check cookie is exist or not on page_load
Place this code in cookiesite2->Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//Grab the cookie
HttpCookie cookie = Request.Cookies[“strCookieName”];

//Check to make sure the cookie exists
if (cookie != null)
{
ReadCookie();
}
Else
{
lblCookie.Text = "Cookie not found. ";
}

}

Read cookie when page load:
Add this method in cookiesite2->Default.aspx.cs

protected void ReadCookie()
{
//Get the cookie name the user entered

//Grab the cookie
HttpCookie cookie = Request.Cookies[“strCookieName”];

//Check to make sure the cookie exists
if (cookie == null)
{
lblCookie.Text = "Cookie not found. ";
}
else
{
//Write the cookie value
String strCookieValue = cookie.Value.ToString();
lblCookie.Text = "The cookie contains: " + strCookieValue + "";
}
}

Test the application in localhost.And for more information:
http://msdn.microsoft.com/en-us/library/aa289495%28VS.71%29.aspx#vbtchaspnetcookies101anchor10

http://www.aspnettutorials.com/tutorials/network/cookies-csharp.aspx

http://www.developer-corner.com/Resources/KnowledgeBase/tabid/118/articleType/ArticleView/articleId/23/PageID/10/Single-Sign-On-across-multiple-ASPNET-applications.aspx

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...