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 :: Selecting or Deselect All Checkbox in Gridview using JQuery

clock February 27, 2015 06:16 by author Peter

In this post I will tell you about select or deselect all checkbox inside gridview using jquery in ASP.NET 5. First, create a new project and then write the following code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewSelectAll.aspx.cs"
    Inherits="GridViewSelectAll" %>
<!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>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#<%=gvProducts.ClientID%> input[id$='chkAll']:checkbox").click(function () {
                $("#<%=gvProducts.ClientID%> input[id*='chkSelected']:checkbox").attr('checked', $(this).is(':checked'));
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <input type="checkbox" id="chkAll" runat="server" value='<%#Eval("ProductID") %>' />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <input type="checkbox" id="chkSelected" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" />        

<asp:BoundField DataField="Description" HeaderText="Description" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class GridViewSelectAll : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
   {
        gvProducts.DataSource = ProductDAL.GetProducts();
        gvProducts.DataBind();
    }
}
public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
}
public class ProductDAL
{
    public static List<Product> GetProducts()
    {
        return new List<Product>()
                   {
                       new Product() {ProductID = 1, ProductName = "Product01", Description = "Example01"},
                       new Product() {ProductID = 2, ProductName = "Product02", Description = "Example02"},
                       new Product() {ProductID = 3, ProductName = "Product03", Description = "Example03"},
                       new Product() {ProductID = 4, ProductName = "Product04", Description = "Example04"},
                       new Product() {ProductID = 5, ProductName = "Product05", Description = "Example05"},
                   };
    }
}

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.



European ASP.NET Hosting - France :: How to Improve your ASP.NET Web API Performance

clock February 24, 2015 08:46 by author Scott

In this article, I will share about how to improve your ASP.NET Web API performance

1. Use fastest JSON serializer

JSON serialization  can affect overall performance of ASP.NET Web API significantly. A year and a half I have switched from JSON.NET serializer on one of my project to ServiceStack.Text .

2. Use other formats if possible (protocol buffer, message pack)

If you can use other formats like Protocol Buffers or MessagePack in your project instead of JSON do it.

You will get huge performance benefits not only because Protocol Buffers serializer is faster, but because format is smaller than JSON which will result in smaller and faster responses.

3. Implement compression

Use GZIP or Deflate compression on your ASP.NET Web API.

Compression is an easy and effective way to reduce the size of packages and increase the speed.

4. Use Caching

If it makes sense, use output caching on your Web API methods. For example, if a lot of users accessing same response that will change maybe once a day.

5. Implement async on methods of Web API

Using asynchronous Web API services can increase the number of concurrent HTTP requests Web API can handle.

Implementation is simple. The operation is simply marked with the async keyword and the return type is changed to Task.

[HttpGet] 
public async Task OperationAsync() 
{  
    await Task.Delay(2000); 
}

6. Use classic ADO.NET if possible

Hand coded ADO.NET is still the fastest way to get data from database. If the performance of Web API is really important for you, don’t use ORMs.

Please just see this table performance below

The Dapper and the hand-written fetch code are very fast, as expected, all ORMs are slower than those three.

LLBLGen with resultset caching is very fast, but it fetches the resultset once and then re-materializes the objects from memory.

Hope above tutorial help you.



European ASP.NET Signal R Hosting - Paris :: How to Integrate ASP.NET with SignalR Hubs

clock February 23, 2015 07:40 by author Scott

In modern applications the end users want to get their data. They want it now, they want it up-to date. In fact it does not matter whether these are pure web application, native desktop installations or mobile apps: everybody wants his data now!

For .NET-minded developers there are a numbers of options to implement near-real-time push style communication from the server/the services to the clients/consumers. You can choose plain HTTP or the super-new WebSockets features available in .NET 4.5 together with Windows 8 and Windows Server 2012. But the coolest and increasingly popular approach is to use a new framework: ASP.NET SignalR.

While it is not intended- and surely beyond the scope of this ebook - to give an introduction or even deep dive into SignalR, we need to have a look at some concepts and code in order to realize a smooth integration of SignalR and AngularJS.

The final goal of this chapter is to have an AngularJS-style integration of calling and listening to server-side SignalR push services.

A Simple SignalR Hub

Our server-side hub for demonstration in this chapter will be a server time emitting push service.

It has one method which can be called as the inbound API. And we will add a background worker in ASP.NET which will periodically push the server time every 5 seconds to all connected clients. For the sake of clarification that hubs do not really need to have both, an inbound and outbound API we will use two different hubs:

  • one for calling the server time from the client (kind of a Web API replacement, but based on the hubs protocol) - aka inbound API.
  • another one for using the hub context to call into connected clients - aka outbound API.

using Microsoft.AspNet.SignalR;
using System;

namespace Henriquatre.Integration.SignalR
{
    public class ServerTimeHub : Hub
    {
        public string GetServerTime()
        {
            return DateTime.UtcNow.ToString();
        }
    }

    public class ClientPushHub : Hub
    {
    }
}

How to Schedule Frequent Pushes on the Server

The official and recommended approach to run scheduled background work in ASP.NET is to implement an IRegisteredObject with the ASP.NET runtime and hook it up at application start.

In the end it can be a simple as this:

using Microsoft.AspNet.SignalR;
using System;
using System.Threading;
using System.Web.Hosting;

namespace Henriquatre.Integration.SignalR
{
    public class BackgroundServerTimeTimer : IRegisteredObject
    {
        private Timer taskTimer;
        private IHubContext hub;

        public BackgroundServerTimeTimer()
        {
            HostingEnvironment.RegisterObject(this);

            hub = GlobalHost.ConnectionManager.GetHubContext<ClientPushHub>();          

            taskTimer = new Timer(OnTimerElapsed, null,
                TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5));
        }

        private void OnTimerElapsed(object sender)
        {
            hub.Clients.All.serverTime(DateTime.UtcNow.ToString());
        }

        public void Stop(bool immediate)
        {
            taskTimer.Dispose();

            HostingEnvironment.UnregisterObject(this);
        }
    }
}

Inside of the constructor we get a reference to the hub context for our ClientsPushHub. This reference is then used in the timer's event to call all registered clients and actually call the serverTime 'method' on the client side.

In global.asax.cs we can simply create and set up the registered objects (we have another in place here for pushing performance data, see below in this chapter) and get our hubs pipeline working by adding the hub routes to the routes table. In this case we enable CORS as the SignalR services are located on a different server than the client-side HTML and JavaScript application.

using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.AspNet.SignalR;

namespace Henriquatre.Integration.SignalR
{
    public class MvcApplication : System.Web.HttpApplication
    {
        private BackgroundServerTimeTimer bstt;
        private BackgroundPerformanceDataTimer bpdt;

        protected void Application_Start()
        {
            bstt = new BackgroundServerTimeTimer();
            bpdt = new BackgroundPerformanceDataTimer();

            RouteTable.Routes.MapHubs(new HubConfiguration
                { EnableCrossDomain = true });

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

Speaking of the JavaScript clients, let's have a quick look at how to build a JS-based application with the Microsoft-provided JavaScript APIs.

SignalR JavaScript Client APIs

The current version (1.1 beta as of writing) provides two jQuery-based JavaScript APIs:

  • with JS proxy: the client uses a dynamically generated JS file as a proxy description for the hubs ('SignalR-WSDL', if you like).
  • without JS proxy: there is no static metadata involved at all and we wire up events and do method calls based on event and method names.

For a smooth integration between SignalR's JavaScript and AngularJS we are going to choose the no proxy route (no pun intended!).

An AngularJS Service for Integrating Hubs

With the above in mind we can write an AngularJS service that wraps and encapsulates the SignalR communication.

The following code shows the fully functional service. We are actually creating a kind of factory which the user of the service can then do different things with by working on the internally created runtime proxy object:

  • register local JavaScript methods which can be called by a server-side SignalR hub (local events, if you will) - this happens through the on method.
  • unregister a local JavaScript method from the runtime proxy by using off.
  • calling server-side hub methods by using the invoke function.

For convenience, we are also exposing the SignalR hub connection in order to get relevant data like e.g. the connection ID.

'use strict';

app.factory('signalRHubProxy', ['$rootScope', 'signalRServer',
    function ($rootScope, signalRServer) {
        function signalRHubProxyFactory(serverUrl, hubName, startOptions) {
            var connection = $.hubConnection(signalRServer);
            var proxy = connection.createHubProxy(hubName);
            connection.start(startOptions).done(function () { });           

            return {
                on: function (eventName, callback) {
                    proxy.on(eventName, function (result) {
                        $rootScope.$apply(function () {
                            if (callback) {
                                callback(result);
                            }
                        });
                    });
                },
                off: function (eventName, callback) {
                    proxy.off(eventName, function (result) {
                        $rootScope.$apply(function () {
                            if (callback) {
                                callback(result);
                            }
                        });
                    });
                },
                invoke: function (methodName, callback) {
                    proxy.invoke(methodName)
                        .done(function (result) {
                            $rootScope.$apply(function () {
                                if (callback) {
                                    callback(result);
                                }
                            });
                        });
                },
                connection: connection
            };
        };

        return signalRHubProxyFactory;   
}]);

The sample controller below illustrates how to use the SignalR AngularJS service. First, we get a reference to that 'factory' object by passing in the base URL of the SignalR hubs. This is essential when using the hubs in a cross-domain scenario. Optionally we can also pass the documented SignalR client configuration options.

From there on it is straight-forward to hook up client events and invoke/call methods on the server.

function ServerTimeController($scope, signalRHubProxy) {
    var clientPushHubProxy = signalRHubProxy(
        signalRHubProxy.defaultServer, 'clientPushHub',
            { logging: true });
    var serverTimeHubProxy = signalRHubProxy(
        signalRHubProxy.defaultServer, 'serverTimeHub');

    clientPushHubProxy.on('serverTime', function (data) {
        $scope.currentServerTime = data;
        var x = clientPushHubProxy.connection.id;
    });  

    $scope.getServerTime = function () {
        serverTimeHubProxy.invoke('getServerTime', function (data) {
            $scope.currentServerTimeManually = data;
        });
    };
};

How Does it Works?

AngularJS internally works with cycles when it comes to execute data binding and to determine when values of the model have changed. One of the cycles is the digesting cycle where Angular checks for model changes by processing and evaluating all registered watch expressions. But if model changes happen outside of the AngularJS world - in our case we get a callback executed externally, not happening in any controller or AngularJS artifact - then we need to instruct Angular that the model actually has changed.

This is what $apply is for: available on the scope, it triggers (or forces) the digesting cycle by calling$digest internally (API Reference: ng.$rootScope.Scope) and this is what we need to use in our SignalR-wrapping service.

on: function (eventName, callback) {
    proxy.on(eventName, function (result) {
       $rootScope.$apply(function () {
          if (callback) {
             callback(result);
          }
       });
    });
}

Conclusion

Last but not least we are showing you a running embedded example of the AngularJS-SignalR integration. This does not only use the already shown and discussed two hubs for the server time but a new one which frequently pushes current performance counter data (CPU values, in this case) to the connected clients.



European ASP.NET 5 Hosting - HostForLIFE.eu :: How to Create Form Validation in ASP.NET using AngularJs ?

clock February 16, 2015 06:48 by author Peter

In this article, I will tell you how to create form validation in AngularJs and ASP.NET 5. In most of Web Apps, we require user to register on the application. I need to do some action like Form validation , so that user can not submit a Invalid form. There are too many way to validate a form in Client side.

Here we are using AngularJs for the form validation. AngularJs Provide many form Validation Directives, We will use then to validate our form. Now, let’s create new project.  First, Add a Employee class and write the code below:
namespace FormValidationInAj.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }   
 }
}

Create an Empty Home Controller
using System.Web.Mvc;
namespace FormValidationInAj.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}


Add Index view corresponding to Index action with this code:
@model FormValidationInAj.Models.Employee
<div ng-controller="myCntrl" class="divForm">
    <form name="registerForm" novalidate ng-submit="Save(registerForm.$valid)">
        @Html.AntiForgeryToken()
         <fieldset>
            <legend>Employee</legend>
             <div class="editor-label">
                @Html.LabelFor(model => model.FirstName)
            </div>
            <div class="editor-field form-group">
                <input type="text" ng-model="firstName" name="firstName" ng-required="true" />
                <p ng-show="registerForm.firstName.$error.required && !registerForm.firstName.$pristine" class=" error">First Name Required</p>
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.LastName)
            </div>
            <div class="editor-field form-group">
                <input type="text" ng-model="lastName" name="lastName" />
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.Email)
            </div>
            <div class="editor-field form-group">
                <input type="email" ng-model="Email" name="Email" ng-required="true" />
                <p ng-show="registerForm.Email.$error.required && !registerForm.Email.$pristine" class="error">Email Required</p>
                <p ng-show="registerForm.Email.$error.email && !registerForm.Email.$pristine" class="error">Invalid Email</p>
            </div>
            <div class="editor-label">
                @Html.LabelFor(model => model.Age)
            </div>
            <div class="editor-field form-group">
                <input type="number" ng-model="Age" name="Age" ng-required="true" />
                <p ng-show="registerForm.Age.$error.required && !registerForm.Age.$pristine" class="error">Age Required</p>
                <p ng-show="registerForm.Age.$error.number && !registerForm.Age.$pristine" class="error">Invalid Age </p>
            </div>
            <p>
                <input type="submit" value="Create" class="btn btn-primary" />
           </p>
        </fieldset>
    </form>
</div>

Above I even have used AngularJs directives for form validation.

  1. Required :using ng-required="true", validated a input field that's required.
  2. Email : using Type="email" property of input field, validate Email address.
  3. Number : using Type="number" property of input field, validate number field.

There are several form validation directives in AngularJs.

  • To show the error message, I even have used Error Name of AngularJs.
  • To show error message only if used has been interacted with form, unless Error message are going to be hidden, I even have used $pristine. $pristine : it'll be true If user has not interacted with form yet.

Now, Add 2 new Js file.
module.js
var app = angular.module("myApp", []);

Controller.js
app.controller("myCntrl", function ($scope, $http) {
    $scope.Save = function (Valid) {
        if (!Valid) {
            alert("Invalid form");
            return;
        } else {
            alert("It's Great. Form Submitted");
        }
    }
});

Modilfy your _Layout.cshtml file. I have included required Js file for angularJs.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/Angular/Module.js"></script>
    <script src="~/Scripts/Angular/Controller.js"></script>
    <style>
        .divForm{
           margin: 15px 50px;
           padding: 0;
           width: 30%;
         }
    </style>
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>

Output:

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 :: Creating Custom Config Section in ASP.NET

clock February 13, 2015 05:55 by author Peter

In this tutorial, I will show you how to create custom config section in ASP.NET 5. You can extend ASP.NET configuration settings with XML configuration elements of your own. To do this, you create a custom configuration section handler.

The handler should be a ASP.NET Framework class that inherits from the System.Configuration.ConfigurationSection class. The section handler interprets and processes the settings that are defined in XML configuration elements in a specific section of a web.config file. You'll read and write these settings through the handler's properties.
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 Russia - HostForLIFE.eu :: Reading PDF Document Properties in ASP.NET

clock February 9, 2015 09:39 by author Peter

With this article, I will tell you about how to to read pdf document properties in  ASP.NET 5. We know that there is no- such  in-built class in .NET framework that read the pdf document. In this example,I will used third-party library iTextSharp. And here is the code that I used for this article:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PdfPropertiesReader.aspx.cs"    Inherits="PdfPropertiesReader" %>
<!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>
        <div id="pdfProperties" runat="server">
        </div>
    </div>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Read Pdf Properties" />    </form>
</body>
</html>


using System;
using System.Collections;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
public partial class PdfPropertiesReader : System.Web.UI.Page
{
    private const string FileNmae = @"C:\\temp\\asp.pdf";
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            StringBuilder stringBuilder = new StringBuilder();
            // create a reader (constructor overloaded for path to local file or URL)
            PdfReader reader = new PdfReader(FileNmae);
            // total number of pages
            int n = reader.NumberOfPages;
            // size of the first page
            Rectangle psize = reader.GetPageSize(1);
            float width = psize.Width;
            float height = psize.Height;
            Console.WriteLine("Size of page 1 of {0} => {1} × {2}", n, width, height);
            // file properties
            Hashtable infodict = reader.Info;
            foreach (DictionaryEntry kvp in infodict)
            {
                stringBuilder.Append(kvp.Key + "=>" + kvp.Value + "</br>");
            }
            pdfProperties.InnerHtml = stringBuilder.ToString();
        }
        catch (Exception exception)
        {
            Response.Write(exception.Message);
        }
    }
}

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



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in