European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 5 Hosting - HostForLIFE.eu :: Getting an User Client IP address in ASP.NET using C#

clock February 6, 2015 07:00 by author Peter

In this post I am going to tell you how to get IP Address of the client machine in ASP.NET 5 with C#.Net or fetch/discover IP location of the client or server machine utilizing ASP.NET with C#.Net. You can likewise put this code in your site to get or retrieve users IP address also you count the unique visitor in your website. In numerous site use this kind of usefulness so he can see that which user is visited our website. So you can likewise utilize or set this code to your site for getting the listof IP location of the users machine that are gone by your site.


The following code is to get the client IP address in ASP.NET:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="RetriveUserIpAddressInAspNet.aspx.cs" Inherits="ProjectDemo_Asp.et.RetriveUserIpAddressInAspNet" %>
<!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>
    Client Id Address:
        <asp:Label ID="lblIPddress" runat="server" Text=""
            style="color: #FF0066; font-size: x-large"></asp:Label>  
    </div>
    </form>
</body>
</html>


C#.Net code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ProjectDemo_Asp.et
{
       public partial class RetriveUserIpAddressInAspNet : System.Web.UI.Page
       {
        public void Page_Load(Object sender, EventArgs e)
        {
            //code for print the time when the page loaded initially        
            lblIPddress.Text= GetLanIPAddress().Replace("::ffff:", "");
        }
        /*
         Method to get the IP Address of the User
         */
        public String GetLanIPAddress()
        {
            String ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            return ip;
        }
       }
}

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 5 Hosting Italy - HostForLIFE.eu :: Create Custom Configuration Sections in ASP.NET 5

clock February 2, 2015 07:10 by author Peter

In this article, I will explain you about creating a custom configuration sections in ASP.NET 5. We want to extend ASP.NET configuration settings using XML configuration elements of your own. To do this, we produce a custom configuration section handler. The handler should be a .NET Framework class that inherits from the System.Configuration.ConfigurationSection class. The section handler interprets and processes the settings that are outlined in XML configuration elements in a specific section of a web.config file. We willl browse and write these settings through the handler's properties. And here is the code that I used:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace CustomConfigSection
{
    public class LoginRedirectByRoleSection : ConfigurationSection
    {
        [ConfigurationProperty("roleRedirects")]
    public RoleRedirectCollection RoleRedirects
        {
    get
            {
    return (RoleRedirectCollection)this["roleRedirects"];
            }
    set
            {
    this["roleRedirects"] = value;
            }
        }
    }
    public class RoleRedirect : ConfigurationElement
    {
        [ConfigurationProperty("role", IsRequired = true)]
    public string Role
        {
    get
           {
    return (string)this["role"];
            }
    set
            {
    this["role"] = value;
            }
        }
        [ConfigurationProperty("url", IsRequired = true)]
    public string Url
        {
    get
            {
    return (string)this["url"];
            }
    set
            {
    this["url"] = value;
            }
        }
    }
    public class RoleRedirectCollection : ConfigurationElementCollection
    {
    public RoleRedirect this[int index]
        {
    get
            {
    return (RoleRedirect)BaseGet(index);
            }
        }
    public RoleRedirect this[object key]
        {
    get
            {
    return (RoleRedirect)BaseGet(key);
            }
        }
    protected override ConfigurationElement CreateNewElement()
        {
    return new RoleRedirect();
        }
    protected override object GetElementKey(ConfigurationElement element)
        {
    return ((RoleRedirect)element).Role;
        }
    }
}

<configSections>
    <section name="loginRedirectByRole" type="CustomConfigSection.LoginRedirectByRoleSection,CustomConfigSection" allowLocation="true" allowDefinition="Everywhere" />
    </configSections>
    <loginRedirectByRole>
    <roleRedirects>
    <add role="Administrator" url="~/Admin/Default.aspx" />
    <add role="User" url="~/User/Default.aspx" />
    </roleRedirects>
    </loginRedirectByRole>

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomConfigSection;
namespace CustomConfigSection
{
    public partial class WebForm1 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
        {
           LoginRedirectByRoleSection roleRedirectSection = (LoginRedirectByRoleSection)ConfigurationManager.GetSection("loginRedirectByRole");
    foreach (RoleRedirect roleRedirect in roleRedirectSection.RoleRedirects)
            {
    if (Roles.IsUserInRole("", roleRedirect.Role))
                {
                    Response.Redirect(roleRedirect.Url);
                }
            }
        }
    }
}

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 5 Hosting - Belgium :: Filter and Sorting in GridView using DataView in ASP.NET 5

clock January 30, 2015 05:50 by author Peter

In this article i will explain you how to Filter and Sorting in GridView using DataView in ASP.NET 5. First, you must create a new project and write the below code in ASP.NET:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Filter and Sorting in GridView using DataView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Enter ID:
               </td>
                <td>
                    <asp:TextBox ID="txtId" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Enter User Name:
                </td>
                <td>
                    <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnSearch" runat="server" Text="Search"
                        onclick="btnSearch_Click"></asp:Button>
                </td>
            </tr>
        </table>
        <asp:GridView ID="GridFilter" runat="server" BackColor="White" BorderColor="#CC9966"
            AllowPaging="True" PageSize="5" BorderStyle="Solid" AutoGenerateColumns="False"
            BorderWidth="1px" CellPadding="4" Font-Names="Georgia" DataKeyNames="User_ID"
            Font-Size="Small" OnSorting="GridFilter_Sorting" AllowSorting="true">
            <Columns>
                <asp:BoundField DataField="User_ID" HeaderText="User_ID" SortExpression="User_ID" />       <asp:BoundField DataField="UserName" HeaderText="User Name" SortExpression="UserName" />
                <asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender" />
                <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
            </Columns>
            <FooterStyle BackColor="Tan" />
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class GridRowFilter : System.Web.UI.Page
{
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {
       if (!IsPostBack)
        {
            GridFilter.DataSource = BindUsers();
            GridFilter.DataBind();
        }
    }
    private DataSet BindUsers()
    {
        ds = new DataSet();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select User_ID,UserName,Gender,Country from User_Details", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        return ds;
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            ds = BindUsers();
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            DataView dvData = dt.DefaultView;
            string strFilter = " 1=1 ";
            if (!string.IsNullOrEmpty(txtId.Text))
                strFilter = strFilter + " And User_ID = " + Convert.ToInt32(txtId.Text);
            if (!string.IsNullOrEmpty(txtUserName.Text))
                strFilter = strFilter + " And UserName Like '%" + txtUserName.Text + "%'";            dvData.RowFilter = strFilter;
            GridFilter.DataSource = dvData;
            GridFilter.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void GridFilter_Sorting(object sender,GridViewSortEventArgs e)
    {
        try
        {
            DataSet ds = BindUsers();
            DataTable dt = new DataTable();
            dt = ds.Tables[0];
            DataView dvData = dt.DefaultView;
            if (ViewState["SortDirection"] != null && ViewState["SortDirection"].ToString() != "")
                dvData.Sort = e.SortExpression + " " + ConvertSortDirection(ViewState["SortDirection"].ToString());
            else
                dvData.Sort = e.SortExpression + " " + ConvertSortDirection("ASC");
            GridFilter.DataSource = dvData;
            GridFilter.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;        }
    }
    private string ConvertSortDirection(string sortDireciton)
    {
        try
        {
            if (sortDireciton != null)
            {
                switch (sortDireciton)
                {
                    case "ASC":
                        ViewState["SortDirection"] = "DESC";
                        break;
                    case "DESC":
                        ViewState["SortDirection"] = "ASC";
                        break;
                }
            }
            return sortDireciton;
        }
        catch (Exception err)
        {
            throw err;
        }
    }
}

In VB.NET
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Partial Public Class GridRowFilter
    Inherits System.Web.UI.Page
    Private ds As DataSet
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            GridFilter.DataSource = BindUsers()
            GridFilter.DataBind()
        End If
    End Sub
    Private Function BindUsers() As DataSet
        ds = New DataSet()
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ConnectionString)        Dim cmd As New SqlCommand("Select User_ID,UserName,Gender,Country from User_Details", con)        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds)
        Return ds
    End Function
   Protected Sub btnSearch_Click(sender As Object, e As EventArgs)
        Try
            ds = BindUsers()
            Dim dt As New DataTable()
            dt = ds.Tables(0)
            Dim dvData As DataView = dt.DefaultView
            Dim strFilter As String = " 1=1 "
            If Not String.IsNullOrEmpty(txtId.Text) Then
                strFilter = strFilter & " And User_ID = " & Convert.ToInt32(txtId.Text)
            End If
            If Not String.IsNullOrEmpty(txtUserName.Text) Then
                strFilter = (strFilter & " And UserName Like '%") + txtUserName.Text & "%'"
            End If
            dvData.RowFilter = strFilter
            GridFilter.DataSource = dvData
            GridFilter.DataBind()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Protected Sub GridFilter_Sorting(sender As Object, e As GridViewSortEventArgs)
        Try
            Dim ds As DataSet = BindUsers()
            Dim dt As New DataTable()
            dt = ds.Tables(0)
            Dim dvData As DataView = dt.DefaultView
            If ViewState("SortDirection") IsNot Nothing AndAlso ViewState("SortDirection").ToString() <> "" Then
                dvData.Sort = e.SortExpression & " " & ConvertSortDirection(ViewState("SortDirection").ToString())
            Else
                dvData.Sort = e.SortExpression & " " & ConvertSortDirection("ASC")
            End If
            GridFilter.DataSource = dvData
            GridFilter.DataBind()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
   Private Function ConvertSortDirection(sortDireciton As String) As String
        Try
            If sortDireciton IsNot Nothing Then
                Select Case sortDireciton
                    Case "ASC"
                        ViewState("SortDirection") = "DESC"
                        Exit Select
                    Case "DESC"
                        ViewState("SortDirection") = "ASC"
                        Exit Select
                End Select
            End If
            Return sotDireciton
        Catch err As Exception
            Throw err
       End Try
    End Function
End Class

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



ASP.NET 5 Hosting Germany - HostForLIFE.eu :: Create Validation Control Error Messages with Alert Box in ASP.NET 5

clock January 26, 2015 06:23 by author Peter

At this short article, we will Create validation control's Error messages in Alert box in ASP.NET 5. First step, you need to know about how to show validation control's Error messages in Alert box in ASP.NET. Then, write the following code:

 

ASP.NET
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>How to show validation control's Error messages in Alert box in ASP.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td>
                <asp:Label ID="lblName" runat="server" Text="Name"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtName" runat="server" ValidationGroup="Validation"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtName"
                    Display="None" ErrorMessage="Name is Required" ValidationGroup="Validation"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblGender" runat="server" Text="Gender"></asp:Label>
            </td>
            <td>
                <asp:DropDownList ID="ddlGender" runat="server" ValidationGroup="Validation">
                    <asp:ListItem Selected="True" Value="0">--Select--</asp:ListItem>
                    <asp:ListItem Value="1">Male</asp:ListItem>
                    <asp:ListItem Value="2">Female</asp:ListItem>
                </asp:DropDownList>
                <asp:CompareValidator ID="CVGender" runat="server" ControlToValidate="ddlGender"
                    Display="None" ErrorMessage="Gender is Required" Operator="NotEqual" ValidationGroup="Validation"
                    ValueToCompare="0"></asp:CompareValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblEmail" runat="server" Text="Email Address"></asp:Label>
            </td>
            <td>
                <asp:TextBox ID="txtEmail" runat="server" ValidationGroup="Validation"></asp:TextBox>
                <asp:RegularExpressionValidator ID="regEmail" runat="server" ControlToValidate="txtEmail"
                    Display="None" ValidationGroup="Validation" ErrorMessage="Enter Valid Email address "
                    ValidationExpression="^([a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]){1,70}$">
                </asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblValidation" runat="server" Text="* Marked fields are mandatory"
                    ForeColor="Red"></asp:Label>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnShowAlert" runat="server" Text="Show Alert" ValidationGroup="Validation" />
                <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True"
                    ShowSummary="False" ValidationGroup="Validation" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

And here is the result:

HostForLIFE.eu ASP.NET 5 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in