14

Find IP Address In ASP.NET Behind Proxy

Find IP Address Behind Proxy Or Client Machine In ASP.NET, If you want to find the IP address of visitors to your aspx page or application or wanna retrieve IP for other users than u need to write this code

Using this code we can find IP address of visitor even if visitor is behind any proxy

public string IpAddress()
{
string strIpAddress;
strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (strIpAddress == null)
{
strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
}
return strIpAddress;
}

To find IP address of a machine behind LAN you can use this code
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses
(strHostName).GetValue(1).ToString();


10

OpenFileDialog In WinForms Windows Forms Application C# VB.NET

OpenFileDialog In WinForms Windows Forms Application Using C# And VB.NET

In this example i m creating a Open file dialog box to browse and select a file to open in .NET windows applications using C# and winforms




Start a new Windows Application project and drag a button, double click on the button to generate it's click event

Now create a new openFileDialog

OpenFileDialog fDialog = new OpenFileDialog();

To set the title of window
fDialog.Title = "Open Image Files";

To apply filter, which only allows the files with the name or extension specified to be selected. in this example i m only using jpeg and GIF files
fDialog.Filter = "JPEG Files|*.jpeg|GIF Files|*.gif";

To set the Initial Directory property ,means which directory to show when the open file dialog windows opens
fDialog.InitialDirectory = @"C:\";

if the user has clicked the OK button after choosing a file,To display a MessageBox with the path of the file:
if(fDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(fDialog.FileName.ToString());
}


If you want to select multiple files ,set the Multiselect property to true and to return the name of the files use fDialog.FileNames instead of fDialog.FileName. This will return a string array with the name of the files.
Other properties which we can use are :
If a user types the name of a file but doesn't specify the extension you can set the AddExtension property to true:
fDialog.AddExtension = true;

if a user types the name of a file or path that does not exist we can give him an warning:
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;


32

User Validation Authentication Using Session In ASP.NET

This post explains how to use User Validation Authentication Using Session In ASP.NET to validate users, Consider a scenario where you don't want to use membership class or Form Authentication techniques provided by .NET 2.0, in those situation this example might be helpful

In this example i m showing how to validate a user across different pages whether user is logged in or not using session variables in Global.asax through Session_Start event and Application_OnPostRequestHandlerExecute event which checks for the login validation which occurs when an asp.net event handler finish execution

For Forms Authentication, read this Forms Authentication with C# and managing folder lavel access with multiple web.config files in ASP.NET

Here is my login page, i've used hard coded values to login

<div style="text-align:left">
<table width="40%" style="text-align: center">
<tr><td style="width: 20%">
<asp:Label ID="lblUserName" runat="server" Text="Enter UserName:"/></td>
 
<td style="width: 20%">
<asp:TextBox ID="txtUserName" runat="server"/></td></tr>
 
<tr><td style="width: 20%">
<asp:Label ID="lblPassword" runat="server" Text="Enter Password:"/></td>
 
<td style="width: 20%" >
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"/></td>
</tr><tr>
 
<td colspan="2" align="right">
<asp:Button ID="btnLogin" runat="server" Text="Sign in" OnClick="btnLogin_Click"/>
</td></tr></table>
<asp:Label ID="Label1" runat="server" Text="Label"/><br />
</div>


After checking the username and password i m creating a new Session variable and setting the flag kindaa value in it , which is "Yes" in this example, this session value will be checked when ever user go to other pages and if it's null than user in not logged in

protected void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "amit" && txtPassword.Text == "amit")
{
Session["Authenticate"] = "Yes";
Response.Redirect("Default2.aspx");
}
else
Label1.Text = " login failed";
}

In Global.asax, in Session_Start event i m assigning null value to the session variable created at the time of Login and than calling the method to check the login, same is in Application_OnPostRequestHandlerExecute event as well

void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["Authenticate"] = "";
CheckLogin();

}
void Application_OnPostRequestHandlerExecute()
{
CheckLogin();
}

void CheckLogin()
{
string Url = Request.RawUrl;
int count = Url.Length - 10 ;
string TestUrl = Url.Substring(count);
string SessionData = Session["Authenticate"].ToString();
if (SessionData == "" && TestUrl != "Login.aspx")
{
Response.Redirect("~/Login.aspx");
}
}


13

ASP.NET Search Records In GridView Footer And Highlight Results

Search Records In GridView Footer And Highlight Results using ajax in asp.net, In this example i am populating Gridview by creating Sqlconnection and SqlCommand.

I've put a textbox in FooterTemplate of gridview for text to search, and the search results are highlighted using regular expression, i m using AJAX for partial postback and update progress template to show search progress

   1:  <style type="text/css">
   2:  .highlight {text-decoration:none; font-weight:bold;
   3:  color:black; background:yellow;}
   4:  </style>
   5:  </head>
   6:  <body>
   7:  <form id="form1" runat="server">
   8:  <asp:ScriptManager ID="ScriptManager1" runat="server"/>
   9:  <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  10:  <ContentTemplate>
  11:  <div>
  12:  <asp:GridView ID="grdSearch" runat="server" 
  13:                ShowFooter="True"
  14:                OnRowCommand="grdSearch_RowCommand" 
  15:                AutoGenerateColumns="False">
  16:   
  17:  <Columns>
  18:  <asp:TemplateField HeaderText="FirstName">
  19:  <ItemTemplate>
  20:  <asp:Label ID="lblFIrstName" runat="server"
  21:             Text='<%# Highlight(Eval("FirstName").ToString()) %>'/>
  22:  </ItemTemplate>
  23:   
  24:  <FooterTemplate>
  25:  <asp:TextBox ID="txtSearch" runat="server"/>
  26:  <asp:Button ID="btnSearch" CommandName="Search" 
  27:              runat="server" Text="Search"/>
  28:  </FooterTemplate>
  29:  </asp:TemplateField>
  30:   
  31:  <asp:BoundField DataField="LastName" HeaderText="LastName"/>
  32:  </Columns>
  33:  </asp:GridView>
  34:  </div>
  35:  </ContentTemplate>
  36:  </asp:UpdatePanel>
  37:   
  38:  <asp:UpdateProgress ID="UpdateProgress1" runat="server">
  39:  <ProgressTemplate>
  40:  <br />
  41:  <img src="Images/ajax.gif" alt="Searchig"/>
  42:  </ProgressTemplate>
  43:  </asp:UpdateProgress>
  44:  </form>
  45:  </body>

Populate GridView by making SqlConnection and SqlCommand to fetch data from database, then bind the data to Grid in Page_Load event.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private DataTable GetRecords()
    {
        SqlConnection conn = new SqlConnection(strConnection);
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Select * from Employees";
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        DataSet objDs = new DataSet();
        dAdapter.Fill(objDs);
        return objDs.Tables[0];

    }

    private void BindGrid()
    {
        DataTable dt = GetRecords();
        if (dt.Rows.Count > 0)
        {
            grdSearch.DataSource = dt;
            grdSearch.DataBind();
        }
    }

Now i've written a method to search GridView rows or records for the text entered in footer textbox by user

private void SearchText(string strSearchText)
    {
        DataTable dt = GetRecords();
        DataView dv = new DataView(dt);
        string SearchExpression = null;
        if (!String.IsNullOrEmpty(strSearchText))
        {
            SearchExpression =
            string.Format("{0} '%{1}%'",
            grdSearch.SortExpression, strSearchText);

        }
        dv.RowFilter = "FirstName like" + SearchExpression;
        grdSearch.DataSource = dv;
        grdSearch.DataBind();
    }

Next step is to check the command in RowCommand event of gridview,if it is what u've defined in while creating the button in footer of grid by assigning the commandname property, if yes than get the text entered by user in textbox placed in footer of gridview by using findcontrol method and pass this text to the search method written earlier by making a call to that method

protected void grdSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        System.Threading.Thread.Sleep(2000);
        if (e.CommandName == "Search")
        {
            TextBox txtGrid =
            (TextBox)grdSearch.FooterRow.FindControl("txtSearch");
            SearchText(txtGrid.Text);
        }
    }

To highlight search results use regular expression and replace the the words found with highlighted in yellow color

public string Highlight(string InputTxt)
    {
        GridViewRow gvr = grdSearch.FooterRow;
        if (gvr != null)
        {
            TextBox txtExample =
            (TextBox)grdSearch.FooterRow.FindControl("txtSearch");

            if (txtExample.Text != null)
            {
                string strSearch = txtExample.Text;
                Regex RegExp =
                new Regex(strSearch.Replace(" ", "|").Trim(),
                RegexOptions.IgnoreCase);
                return
                RegExp.Replace(InputTxt, new MatchEvaluator(ReplaceKeyWords));
                RegExp = null;
            }
            else
                return InputTxt;
        }
        else
        {
            return InputTxt;
        }
    }

    public string ReplaceKeyWords(Match m)
    {
        return "" + m.Value + "";
    }


3

Register Dlls Assembly Custom User Controls Ascx In ASP.NET

This post explains how to Register Assembly, Custom Controls, Dlls And User Control Ascx In Asp.Net 2.0,3.5,4.0. To register these we need to add reference in page directive of aspx html source

<%@ Register TagPrefix="MyControl" TagName="HeaderControl"
Src="Header.ascx" %>
<%@ Register TagPrefix="MyControl" TagName="footerControl"
Src="Footer.ascx" %>
<%@ Register TagPrefix="MyAssembly" Assembly="Myassembly" %>


Or like this

<%@ Register Assembly="AjaxControlToolkit"
             Namespace="AjaxControlToolkit"
             TagPrefix="ajaxToolkit" %>

But using this we need to register our ascx control or dll in every page we want to use , if we need to use control or dll in more than one page or in several pages than we can register controls and dlls in web.config file

<configuration>
    <system.web>
      <pages>
        <controls>
          <add tagPrefix="MyControl" src="~/Header.ascx" 
                                     tagName="HeaderControl"/>
 
          <add tagPrefix="ControlName" src="~/Footer.ascx" 
                                       tagName="FooterControl"/>
 
          <add tagPrefix="MyAssembly" assembly="MyAssembly"/>
 
          <add tagPrefix="asp" namespace="System.Web.UI" 
               assembly="System.Web.Extensions, 
               Version=3.5.0.0, Culture=neutral,
               PublicKeyToken=31BF3856AD364E35"/>
        </controls>
      </pages>
    </system.web>
</configuration>


8

ASP.NET TextBox Submit Form On Enter Key DefaultButton

TextBox Submit Form On Enter Key press Using DefaultButton In Asp.Net 2.0,3.5,4.0, We can set Defaultbutton property either in Form or in panel Whenever we want user to submit a form by pressing enter key after filing out some textboxes on the aspx page, though we provide the button to submit the form but user prefer to press enter and expect the form to be submitted

But in ASP.NET when user press enter key the page gets post back but the button event doesn't get fired hence whatever code u've written in the click event doesn't get executed and it just like refreshing the page , to handle this situation in ASP.NET 2.0 ,we need to set the Defaultbutton property which indicates which button events should get fired when user press enter key to submit the form.

<form id="form1" runat="server" defaultbutton="Button1">
<div>
<asp:TextBox ID="TextBox1" runat="server"/>
 
<asp:TextBox ID="txtTest" runat="server"/>
 
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit"/>
</div>
</form>
 
or if we use panel than
<asp:Panel ID="Panel1" runat="server" defaultbutton="Button1">


16

Search Records In GridView And Highlight Results Asp.Net Ajax

In this example i am Explaining how to Search Records In GridView And Highlight Results Using Ajax In Asp.Net 2.0,3.5,4.0 based on text entered in textbox.



Add following CSS style in head section of page.

HTML SOURCE
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
    
Enter first name to search:
 
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True"
             OnTextChanged="txtSearch_TextChanged"/>
 
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="grdSearch" runat="server"
              AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" 
           Text='<%# Highlight(Eval("FirstName").ToString()) %>'/>
</ItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#(Eval("LastName")) %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#(Eval("Location")) %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>

Write following code in code behind
C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    private DataTable GetRecords()
    {
        SqlConnection conn = new SqlConnection(strConnection);
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Select * from Employees";
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        DataSet objDs = new DataSet();
        dAdapter.Fill(objDs);
        return objDs.Tables[0];

    }
    private void BindGrid()
    {
        DataTable dt = GetRecords();
        if (dt.Rows.Count > 0)
        {
            grdSearch.DataSource = dt;
            grdSearch.DataBind();
        }
    }
    private void SearchText()
    {
        DataTable dt = GetRecords();
        DataView dv = new DataView(dt);
        string SearchExpression = null;
        if (!String.IsNullOrEmpty(txtSearch.Text))
        {
            SearchExpression = string.Format("{0} '%{1}%'",
            grdSearch.SortExpression, txtSearch.Text);

        }
        dv.RowFilter = "FirstName like" + SearchExpression;
        grdSearch.DataSource = dv;
        grdSearch.DataBind();

    }
    public string Highlight(string InputTxt)
    {
        string Search_Str = txtSearch.Text.ToString();
        // Setup the regular expression and add the Or operator.
        Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(),
        RegexOptions.IgnoreCase);

        // Highlight keywords by calling the 
        //delegate each time a keyword is found.
        return RegExp.Replace(InputTxt,
        new MatchEvaluator(ReplaceKeyWords));

        // Set the RegExp to null.
        RegExp = null;

    }

    public string ReplaceKeyWords(Match m)
    {

        return "" + m.Value + "";

    }

    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        SearchText();
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  BindGrid()
 End If
End Sub
Private Function GetRecords() As DataTable
 Dim conn As New SqlConnection(strConnection)
 conn.Open()
 Dim cmd As New SqlCommand()
 cmd.Connection = conn
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "Select * from Employees"
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 Dim objDs As New DataSet()
 dAdapter.Fill(objDs)
 Return objDs.Tables(0)

End Function
Private Sub BindGrid()
 Dim dt As DataTable = GetRecords()
 If dt.Rows.Count > 0 Then
  grdSearch.DataSource = dt
  grdSearch.DataBind()
 End If
End Sub
Private Sub SearchText()
 Dim dt As DataTable = GetRecords()
 Dim dv As New DataView(dt)
 Dim SearchExpression As String = Nothing
 If Not [String].IsNullOrEmpty(txtSearch.Text) Then

  SearchExpression = String.Format("{0} '%{1}%'", grdSearch.SortExpression, txtSearch.Text)
 End If
 dv.RowFilter = "FirstName like" & SearchExpression
 grdSearch.DataSource = dv
 grdSearch.DataBind()

End Sub
Public Function Highlight(InputTxt As String) As String
 Dim Search_Str As String = txtSearch.Text.ToString()
 ' Setup the regular expression and add the Or operator.
 Dim RegExp As New Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase)

 ' Highlight keywords by calling the 
 'delegate each time a keyword is found.
 Return RegExp.Replace(InputTxt, New MatchEvaluator(AddressOf ReplaceKeyWords))

 ' Set the RegExp to null.
 RegExp = Nothing

End Function

Public Function ReplaceKeyWords(m As Match) As String

 Return "" & Convert.ToString(m.Value) & ""

End Function

Protected Sub txtSearch_TextChanged(sender As Object, e As EventArgs)
 SearchText()
End Sub

12

Detect Browser Refresh Avoid Events Fire In ASP.NET

Detect Browser Refresh In Asp.Net 2.0,3.5,4.0 To Avoid Events Getting Fired Or Event Firing,If you are inserting some data in database in Click event of button, After click if user refresh the page than click event gets fired again resulting data insertion to database again.

To stop event fire on browser refresh we need to write bit of code.

In this example i've put a Label and a Button on the page, on click the label Text becomes Hello and when i refresh the page label's text again becomes Hello

HTML SOURCE
   1:  <asp:Label ID="Label1" runat="server" Text=""/>
   2:   
   3:  <asp:Button ID="Button1" runat="server" 
   4:              OnClick="Button1_Click" Text="Button"/>


In Page_Load event i m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event i am creating a Viewstate variable and assigning Session variable's value to it.

Than in button's click event i am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["CheckRefresh"] =
            Server.UrlDecode(System.DateTime.Now.ToString());
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
        {
            Label1.Text = "Hello";
            Session["CheckRefresh"] =
            Server.UrlDecode(System.DateTime.Now.ToString());
        }
        else
        {
            Label1.Text = "Page Refreshed";
        }
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["CheckRefresh"] = Session["CheckRefresh"];
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  Session("CheckRefresh") = Server.UrlDecode(System.DateTime.Now.ToString())
 End If
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs)
 If Session("CheckRefresh").ToString() = ViewState("CheckRefresh").ToString() Then
  Label1.Text = "Hello"
  Session("CheckRefresh") = Server.UrlDecode(System.DateTime.Now.ToString())
 Else
  Label1.Text = "Page Refreshed"
 End If
End Sub

Protected Sub Page_PreRender(sender As Object, e As EventArgs)
 ViewState("CheckRefresh") = Session("CheckRefresh")
End Sub


Find More Articles