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 Core 1.1 Hosting - HostForLIFE.eu :: How to Create Multi Step Form In ASP.NET?

clock January 11, 2017 07:18 by author Peter

In this post, I will tell you about how to create multi step form in ASP.NET. Multiview will be used to display the content on the tap of Tab. 

To show tab on the top, we will use Menu control. Thus, let's go and Add menu control from toolbox. I have given the Horizontal orientation, so that Tab will display horizontally. 
<asp:Menu 
           ID="menuTabs" 
           Orientation="Horizontal" 
           Width="100%" 
           runat="server"> 
           <Items> 
               <asp:MenuItem Text="Employee Info" Value="0" Selected="true"/> 
               <asp:MenuItem Text="Contact Info" Value="1" /> 
               <asp:MenuItem Text="Salary Info" Value="2" /> 
           </Items> 
</asp:Menu>
 

To display the content for each tab, we will use Multiview control. I have given a property Selected="true" for Employee Info, so that when a page is launched, it will display the content of Employee Info.
<asp:MultiView ID="multiviewEmployee" 
                      runat="server" ActiveViewIndex="0"> 

</asp:MultiView> 


Next step is to add view inside Multiview. As I have three menu items, I need to add three views inside Multiview.
<asp:MultiView ID="multiviewEmployee" 
                       runat="server" ActiveViewIndex="0"> 
              <asp:View runat="server"> 
                <div> 
                    <%--To do--%> 
                </div> 
              </asp:View> 
               <asp:View runat="server"> 
                <div> 
                    <%--To do--%> 
                </div> 
              </asp:View> 
               <asp:View runat="server"> 
                <div> 
                    <%--To do--%> 
                </div> 
              </asp:View> 
</asp:MultiView> 
 

ActiveViewIndex= "0" will display first view after page is launched. Now, we will open corresponding view, when it is clicked on menu items. For it, we need to handle OnMenuItemClick event of Menu control. Hence, add it in your code and it will look, as mentioned below.
<asp:Menu 
  ID="menuTabs" 
  Orientation="Horizontal" 
  Width="100%" 
  runat="server" 
  OnMenuItemClick="menuTabs_MenuItemClick"> 
  <Items> 
      <asp:MenuItem Text="Employee Info" Value="0" Selected="true"/> 
      <asp:MenuItem Text="Contact Info" Value="1" /> 
      <asp:MenuItem Text="Salary Info" Value="2" /> 
  </Items> 
</asp:Menu> 


In CS page, assign the value of menu item to multiview .
protected void menuTabs_MenuItemClick(object sender, MenuEventArgs e) 
    { 
        Menu menuTabs = sender as Menu; 
        MultiView multiTabs = this.FindControl("multiviewEmployee") as MultiView; 
        multiTabs.ActiveViewIndex = Int32.Parse(menuTabs.SelectedValue); 
         
    } 


Now, it's none. Your tab structure is ready. Full code for ASPX is mentioned below.
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title></title> 
<style> 
    .viewCSS { 
        border: solid 2px black; 
        padding: 20px; 
    } 


    #menuTabs a.static.selected { 
        border-bottom-color: red; 
        border-bottom-style: solid; 
        border-bottom-width: 3px; 
        color: red; 
    } 
</style> 
</head> 
<body> 
<form id="form1" runat="server" style="width: 100%"> 
    <div style="width: 100%; margin-left: 20px; margin-top: 50px; margin-right: 20px;"> 

        <asp:Menu 
            ID="menuTabs" 
            Orientation="Horizontal" 
            Width="100%" 
            runat="server" 
            OnMenuItemClick="menuTabs_MenuItemClick"> 
            <Items> 
                <asp:MenuItem Text="Employee Info" Value="0" Selected="true" /> 
                <asp:MenuItem Text="Contact Info" Value="1" /> 
                <asp:MenuItem Text="Salary Info" Value="2" /> 
            </Items> 
        </asp:Menu> 
        <asp:MultiView ID="multiviewEmployee" 
            runat="server" ActiveViewIndex="0"> 
            <asp:View runat="server"> 
                <div style="margin-top: 40px;"> 
                    <asp:Table runat="server" CssClass="viewCSS"> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">First Name</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Last Name</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                    </asp:Table> 
                </div> 
            </asp:View> 
            <asp:View runat="server"> 
                <div style="margin-top: 40px;"> 
                    <asp:Table runat="server" CssClass="viewCSS"> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Address</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Mobile</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                    </asp:Table> 
                </div> 
            </asp:View> 
            <asp:View runat="server"> 
                <div style="margin-top: 40px;"> 
                    <asp:Table runat="server" CssClass="viewCSS"> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Hire Date</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                        <asp:TableRow> 
                            <asp:TableCell> 
                                <asp:Label runat="server">Salary</asp:Label> 
                            </asp:TableCell> 
                            <asp:TableCell> 
                                <asp:TextBox runat="server"></asp:TextBox> 
                            </asp:TableCell> 
                        </asp:TableRow> 
                    </asp:Table> 
                </div> 
            </asp:View> 

        </asp:MultiView> 
    </div> 
</form> 
</body> 
</html> 


I Hope it works for you!

 

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How To Change app.config Data in ASP.NET?

clock January 4, 2017 08:20 by author Peter

In this post, I will tell you about How To Change app.config Data in ASP.NET. Please write the following code to change app.config data at runtime.
    private static void SetSetting(string key, string value) 
           { 
               Configuration configuration = 
                   ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
               configuration.AppSettings.Settings[key].Value = value; 
               configuration.Save(ConfigurationSaveMode.Full, true); 
               ConfigurationManager.RefreshSection("appSettings"); 
           } 


The code given below is used to fetch app.config data.
    private static string GetSetting(string key) 
            { 
                return ConfigurationManager.AppSettings[key]; 
            } 


App.config file

Key is lang and value is English.
 
Output

We get the "lang" value as English, this value is fetched from App.config file.

Modify App.config value at runtime.


Code
    public Form1() 
    { 
        InitializeComponent();  
        string objAppConfigValue = GetSetting("lang"); 
        SetSetting("lang", "Tamil"); 
        string objModifiedAppConfigValue = GetSetting("lang"); 
        
    } 

    private static string GetSetting(string key) 
    { 
        return ConfigurationManager.AppSettings[key]; 
    } 

    private static void SetSetting(string key, string value) 
    { 
        Configuration configuration = 
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
        configuration.AppSettings.Settings[key].Value = value; 
        configuration.Save(ConfigurationSaveMode.Full, true); 
        ConfigurationManager.RefreshSection("appSettings"); 
    } 



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How to Create Circular Progress Bar Dynamically In ASP.NET?

clock December 21, 2016 08:20 by author Peter

In this post, let me explain you about Create Circular Progress Bar Dynamically In ASP.NET. For it, we will take a div and apply style to make it circular.

<div id="circularProgess" class="circularprogress background" runat="server"> 
          <div id="ProgressText" class="overlay" runat="server"></div> 
</div> 


Add the style, mentioned below.
<style> 
    .background { 
        background-image: linear-gradient(<%= Val1 %>, <%= ColorCode %> 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0)), linear-gradient(<%= Val2 %>, #AC2D36 50%, #ffffff 50%, #ffffff); 
    } 
 
    /* -------------------------------------
     * Bar container
     * ------------------------------------- */ 
    .circularprogress { 
        float: left; 
        margin-left: 50px; 
        margin-top: 30px; 
        position: relative; 
        width: 180px; 
        height: 180px; 
        border-radius: 50%; 
    } 
 
        /* -------------------------------------
         * Optional centered circle w/text
         * ------------------------------------- */ 
        .circularprogress .overlay { 
            position: absolute; 
            width: 130px; 
            height: 110px; 
            color: white; 
            background-color: #CF5760; 
            border-radius: 50%; 
            margin-left: 25px; 
            margin-top: 23px; 
            text-align: center; 
            line-height: 90px; 
            font-size: 35px; 
            padding-top: 20px; 
        } 
</style> 

In the background style, I have added val1 and val2, where I will assign from .cs page, so we can make a dynamic circular progress bar. Add the properties and methods, mentioned below in .cs file.
private string val1 = "90deg"; 
 
       public string Val1 
       { 
           get { return val1; } 
           set { val1 = value; } 
       } 
 
       private string val2 = "90deg"; 
 
       public string Val2 
       { 
           get { return val2; } 
           set { val2 = value; } 
       } 
 
       private string colorCode = "#ffffff"; 
 
       public string ColorCode 
       { 
           get { return colorCode; } 
           set { colorCode = value; } 
       } 
 
       protected void Page_Load(object sender, EventArgs e) 
       { 
           ProgressText.InnerText = "0%"; 
           CalculateActiveUsersAngle(75); 
       } 
 
       private void CalculateActiveUsersAngle(int TotalUser) 
       { 
           //int TotalUser = 50; 
 
           if (TotalUser == 0) 
           { 
               Val2 = "90deg"; 
               Val1 = "90deg"; 
               ColorCode = "#ffffff"; 
           } 
           else if (TotalUser < 50 && TotalUser > 0) 
           { 
               double percentageOfWholeAngle = 360 * (Convert.ToDouble(TotalUser) / 100); 
               Val2 = (90 + percentageOfWholeAngle).ToString() + "deg"; 
               Val1 = "90deg"; 
               ColorCode = "#ffffff"; 
           } 
           else if (TotalUser > 50 && TotalUser < 100) 
           { 
               double percentage = 360 * (Convert.ToDouble(TotalUser) / 100); 
               Val1 = (percentage - 270).ToString() + "deg"; 
               Val2 = "270deg"; 
               ColorCode = "#AC2D36"; 
           } 
           else if (TotalUser == 50) 
           { 
               Val1 = "-90deg"; 
               Val2 = "270deg"; 
               ColorCode = "#AC2D36"; 
           } 
           else if (TotalUser >= 100) 
           { 
               Val1 = "90deg"; 
               Val2 = "270deg"; 
               ColorCode = "#AC2D36"; 
           } 
 
           ProgressText.InnerText = TotalUser + "%"; 
 
       } 


CalculateActiveUsersAngle() method will calculate and show the exact angle .You can assign the angle if you want to CalculateActiveUsersAngle() method. For this example, I have assigned 75, so circular progress will display 75% on the radial. And here is the output:

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How to Get IP Address In ASP.NET?

clock December 14, 2016 08:07 by author Peter

In this post, I will tell you how to Get IP Address In ASP.NET. An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication. An IP address serves two principal functions: host or network interface identification and location addressing. Its role has been characterized as follows: "A name indicates what we seek. An address indicates where it is. A route indicates how to get there.”

There are two versions of IP address, earlier Version of IP address is IPv4 contains IP address as 32 bit number, and then because of growth of internet new version of IP is developed named IPv6 which takes 128 bit to store the IP Address.

There are different ways to get IP Address of visitor of the websites.

First method of getting IP Address is using “HTTP_X_FORWARDED_FOR” and “REMOTE_ADDR”. Where, “X_FORWARDED_FOR” is HTTP header field for identifying originating IP Address of the client who connected to internet and “REMOTE_ADDR” Returns the IP address of the remote machine.

Code to get IP Address using Method 1:

Second method of getting IP address is using built in functionality of ASP.NET. Here we use Request property of Page Class which gets the object of HttpRequest class for the requested page. HttpRequest is sealed class which enables ASP.NET to read the HTTP values sent by client machine during the web request. We access the UserHostAddress property of HttpRequest class to get the IP Address of the visitor.

Code to get IP Address using Method 2:

Default.aspx

Call above both method in Page_Load event, as soon as page will load you will get output like this.

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: Using Highchart In ASP.NET

clock December 8, 2016 08:56 by author Peter

In this post, will tell you how to use Highchart in ASP.NET. Highchart in ASP.NET is purely a JavaScript and jQuery based API which can create interactive charts for representing the data. Highchart is a client-side API and it is flexible for use on different kinds of web browsers.

And here is the feature of highchart:

  • Compatible: Highchart works on all kinds of browsers.
  • Highchart is free for non-commercial purposes.
  • Different types of charts are available.
  • We can easily integrate it with .NET.

Types of Charts

Highcharts support different types of charts, such as:

  • Gauges
  • Basic Area chart
  • Bar chart
  • Column chart
  • Line chart
  • Pie chart
  • Polar chart
  • Range series

How it works

  • Download this dll and add to your project:
  • Download and add JavaScript to your project:
  • Chart Creation
  • Chart Output

Step 1

  • Download this dll to add to your project or install NET Highcharts.
  • You can follow the below steps.

Step 2
Download Highcharts and add reference of the JavaScript in your page or master page:
Add the below script
        <script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> 
        <script src="../../Scripts/highcharts.js" type="text/javascript"></script> 

Step 3

Chart Creation

Below code 
        for Mvc 
        public ActionResult Index() { 
                DotNet.Highcharts.Highcharts chart = new DotNet.Highcharts.Highcharts("chart").SetXAxis(new XAxis { 
                        Categories = new [] { 
                            "Jan", 
                            "Feb", 
                            "Mar", 
                            "Apr", 
                            "May", 
                            "Jun", 
                            "Jul", 
                            "Aug", 
                            "Sep", 
                            "Oct", 
                            "Nov", 
                            Dec " }  
                        }).SetSeries(new Series { 
                        Data = new Data(new object[] { 
                            29.9, 
                            71.5, 
                            106.4, 
                            129.2, 
                            144.0, 
                            176.0, 
                            135.6, 
                            148.5, 
                            216.4, 
                            .1, 
                            95.6, 
                            54.4 
                        }) 
                    }); 
                    return View(chart); 
                } 
                Below Code 
                for Asp.net 
                protected void Page_Load(object sender, EventArgs e) { 
                    DotNet.Highcharts.Highcharts chart = new DotNet.Highcharts.Highcharts("chart").SetXAxis(new XAxis { 
                        Categories = new [] { 
                            "Jan", 
                            "Feb", 
                            "Mar", 
                            "Apr", 
                            "May", 
                            "Jun", 
                            "Jul", 
                            "Aug", 
                            "Sep", 
                            "Oct", 
                            "Nov", 
                            "Dec" 
                        } 
                    }).SetSeries(new Series { 
                        Data = new Data(new object[] { 
                            29.9, 
                            71.5, 
                            106.4, 
                            129.2, 
                            144.0, 
                            176.0, 
                            135.6, 
                            148.5, 
                            216.4, 
                            194.1, 
                            95.6, 
                            54.4 
                        }) 
                    }); 
                    ltrChart.Text = chart.ToHtmlString(); 
                } 
    HTML Code
        For Mvc 
        @model DotNet.Highcharts.Highcharts 
        @(Model) 
        For Asp.net < asp: Content ID = "BodyContent" 
        runat = "server" 
        ContentPlaceHolderID = "MainContent" > < asp: Literal ID = "ltrChart" 
        runat = "server" > < /asp:Literal>  < /asp:Content> 


Step 4

We get the output like the below image.

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET SignalR Hosting - HostForLIFE.eu :: Using ASP.NET SignalR for Chat Application

clock December 5, 2016 10:04 by author Scott

ASP.Net SignalR is one of the major revolutions in the development technology world these days for creating real applications. Consider an application having a page where you are required to update the user interface with the latest data, as soon as it is available. Such applications are said to be real-time applications, where the UI is updated as soon as the latest data is available for the user.

The best example is a stock market application that must maintain the user interface updated with the data as soon as the stock rates are changed. Another example is a chat application that updates the receiver with the latest message, from the sender. Some of the techniques could use timer-based requests to the server for getting the data and some could use polling to get the data. A good alternative to these is SignalR. 

As we know, our model of the web applications mainly consists of a server that hosts the application and the client, representing the end users of the applications. For creating SignalR based applications, we need to create a hub on the server that is responsible for updating the client or the end users with the latest data. This hub is nothing but a simple class inheriting from the Hub class. At the client end, we get an automatically generated JavaScript based proxy file (at run time) that can be used by the client for connecting with the hub. The client code also contains a JavaScript function that the hub uses to provide them the latest data.

To explain this process in detail, our hub directly calls the client JavaScript functions, to provide the latest data. On the other hand, by using the auto-generated JavaScript proxy file at the client end, client code can uses this proxy, to call the methods of the server hub, if required. The term if required is used here deliberately with the fact that the client may not be required to call the hub. For example, in an application where we have a user dashboard with some data from a database, we can use SqlDependency and SignalR to keep the user interface updated, whenever there is any change in the database records. In this case, the client is not required to make any calls to the server for getting the updates. On the other hand, if we have a chat application, the client code will call the server hub and forward the message. The Hub will than broadcast this message to the users of the application, by calling the JavaScript method of the clients.

One very important point from the preceding paragraph is that the client never calls the hub for getting the latest data. The client may only call the hub so that the hub can forward the message to the other connected clients. If the client code needs to make the calls for the latest data to the server, than the entire purpose of using the SignalR fails and we could have used the old concepts of a timer or page refresh for this.

Build Simple Group Chat Application in 15 minutes Using SignalR

Yes, that's correct. Once you are familiar with the basic concept/flow of SignalR, you can do it very easily. We will be now creating a group chat, without the use of a database. If we think about the flow of the application, this entire process requires a client to send a message to the server that will broadcast this message to all the connected client users. So the server needs to have a component that can broadcast the message to the clients. This role is played by the hub class.

Create a new project named SignalRChat. Add the references to the SignalR libraries using Nuget. It will automatically add the references to the OWIN hosting option libraries that allow addition of the SignalR application to the OWIN pipeline. Apart from the server libraries, it also adds the client libraries required for using SignalR. See the following references that are to be added:

Create OWIN host for the application

We will be using the OWIN based hosting, to host this application. Without going into depth about the OWIN hosting, let's add a class named Startup.cs. The name must be Startup as in the OWIN based hosting specifications and its namespace must be decorated with the assembly attribute, specifying that the Startup assembly is the starting point of the application. Next we define a method named Configuration and register the SignalR in the OWIN pipeline using app.MapSignalR().

Create the Hub on the Server

Our next step is to create the hub on the server that is nothing but a class file. We will name it SignalRChatHub and derive from the Hub class. It will contain a method named BroadCastMessage, with 2 parameters. the client code will use this method (using the proxy generated at its end) for communication with the hub and the parameters as the data to be sent to the hub. Inside this method, use the Clients property of the Hub class to call the client-side function. This function is a simple JavaScript function that will receive the data sent by the hub and update the chat window of the user. We will define a function with the name receiveMessage at the client end (later in the code). So for now, we will use this method name.

A point to be noted here is that we will not get any intelligence help for the client methods, of course. This method will be dynamically resolved. See the image below:

Setup the Client code

The server setup is done. We will now add an HTML page named ChatWindow.html that will be our chat window for the user. Also we add the references to the jquery-1.6.4.min.js and jquery.signalR-2.2.0 .min,js on this page that were added by the Nuget package manager. Earlier we discussed that SignalR automatically generates a proxy class at run time, for client code, to connect with the hub. So we also need to reference this file. Since this file is generated at run time, it does not exist physically for us. As in the SignalR tutorials on the official ASP.Net website, it states:

SignalR creates the JavaScript code for the proxy on the fly and serves it to the client in response to the "/signalr/hubs" URL.

So we need to add this reference also.

We also have the option to disable this auto-generated proxy file generation (that is out of scope for this discussion) and create the proxy ourselves. In that case, we need to reference that file accordingly. Next, let's add some HTML mark-up to generate the chat window and design it using CSS styling.

Now it's time for the client code to connect with the hub and send the message, so that hub can broadcast to all the users. For this, we first get the proxy instance in a variable named chatProxy. Note the camel case syntax of the client code below. This is the convention to be followed when creating the SignalR application. For detailed specifications, I recommend you check out the ASP.Net official SignalR website. Without going further into the details, let's move forward with the code. Here, signalRChatHub is the name of the hub on the server (that we created on the server earlier).

Next, we attach the button click event (the button to send the message to the users), when the connection to the hub is successfully started. This event will call the method of the hub, using the proxy instance that will receive the message and broadcast it to users. See the code below:

We also declare the function to which the hub will call, when it needs to update all the users with the message received. This is the function name we referred to, from the hub method, at the start of the discussion. So this function acts as a type of callback function here.

So all the client code is also set up and we can now run the application. So our complete client code will now look as in:

We can now run the application. Copy the URL and open another instance of the browser or any other browser and we can start chatting.

 



HostForLIFE.eu Proudly Launches Visual Studio 2017 Hosting

clock December 2, 2016 07:01 by author Peter

European leading web hosting provider, HostForLIFE.eu announces the launch of Visual Studio 2017 Hosting

HostForLIFE.eu was established to cater to an underserved market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu - a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the Visual Studio 2017 hosting in their entire servers environment.

The smallest install is just a few hundred megabytes, yet still contains basic code editing support for more than twenty languages along with source code control. Most users will want to install more, and so customer can add one or more 'workloads' that represent common frameworks, languages and platforms - covering everything from .NET desktop development to data science with R, Python and F#.

System administrators can now create an offline layout of Visual Studio that contains all of the content needed to install the product without requiring Internet access. To do so, run the bootstrapper executable associated with the product customer want to make available offline using the --layout [path] switch (e.g. vs_enterprise.exe --layout c:\mylayout). This will download the packages required to install offline. Optionally, customer can specify a locale code for the product languages customer want included (e.g. --lang en-us). If not specified, support for all localized languages will be downloaded.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt(DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customers can start hosting their Visual Studio 2017 site on their environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu offers the latest European Visual Studio 2017 hosting installation to all their new and existing customers. The customers can simply deploy their Visual Studio 2017 website via their world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features Visual Studio 2017 Hosting can be viewed here http://hostforlife.eu/European-Visual-Studio-2017-Hosting



ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: How to Built-In Logging In .NET Core?

clock November 30, 2016 08:19 by author Peter

In this post, I will show you how to Built-In Logging In .NET Core. For an application, logging is very important to keep track of that application and keep it error-free.

In .NET Core, we don't need any third party logging; instead, we can use built-in logging whenever we want. This is very efficient in terms of code and performance. Now, develope a new .NET Core application and name it.

Step 1: Go to Package mManager View-->Other Windows--> Package manager Console  -->

Install-Package Microsoft.Extensions.Logging

Add Logging
Once  the extension's installed, we can add logging by adding ILogger<T> (custom logging) or ILoggerFactory. If we want to use ILoggerFactory, then we must create it using CreateLogger, to use logging add logging services under ConfigureServices. Moreover, we can use built-in logging with the other loggings (like Nlog) with very minimal code.
services.AddLogging(); 

Startup.cs
public class Startup 
    { 
        public Startup(IHostingEnvironment env) 
        { 
            var builder = new ConfigurationBuilder() 
                .SetBasePath(env.ContentRootPath) 
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
                .AddEnvironmentVariables(); 
            Configuration = builder.Build(); 
        } 
 
        public IConfigurationRoot Configuration { get; } 
 
        // This method gets called by the runtime. Use this method to add services to the container. 
        public void ConfigureServices(IServiceCollection services) 
        { 
            // Add framework services. 
            services.AddMvc(); 
            services.AddLogging(); 
        } 
 
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
        { 
            loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
            loggerFactory.AddDebug(); 
 
            if (env.IsDevelopment()) 
            { 
                app.UseDeveloperExceptionPage(); 
                app.UseBrowserLink(); 
            } 
            else 
            { 
                app.UseExceptionHandler("/Home/Error"); 
            } 
 
            app.UseStaticFiles(); 
 
            app.UseMvc(routes => 
            { 
                routes.MapRoute( 
                    name: "default", 
                    template: "{controller=Home}/{action=Index}/{id?}"); 
            }); 
        } 
    } 

ILoggerFactory: We can use  ILoggerFactory. For this, we must use CreateLogger.

_logger = Mylogger.CreateLogger(typeof(HomeController)); 

HomeController.cs
public class HomeController : Controller 
    { 
        private ILogger _logger; 
 
        public HomeController(ILoggerFactory Mylogger) 
        { 
            _logger = Mylogger.CreateLogger(typeof(HomeController)); 
        } 
 
        public IActionResult Index() 
        { 
            return View(); 
        } 
 
        public IActionResult About() 
        { 
            try 
            { 
                ViewData["Message"] = "Your application description page."; 
                _logger.LogInformation("About Page has been Accessed"); 
                return View(); 
            } 
            catch (System.Exception ex) 
            { 
                _logger.LogError("About: " + ex.Message); 
                throw; 
            } 
        } 
 
        public IActionResult Contact() 
        { 
            try 
            { 
                ViewData["Message"] = "Your contact page."; 
                _logger.LogInformation("Contact Page has been Accessed"); 
                return View(); 
            } 
            catch (System.Exception ex) 
            { 
                _logger.LogError("Contact: " + ex.Message); 
                throw; 
            } 
        } 
 
        public IActionResult Error() 
        { 
            return View(); 
        } 
    } 


Run and Test

LogLevel: We can add logging level by adding the level we want in appsettings.json.Trace

  • Debug
  • Information
  • Warning
  • Error
  • Application failure or crashes         


ASP.NET Core 1.1 Hosting - HostForLIFE.eu :: Uploading File Without PostBack In ASP.NET

clock November 9, 2016 08:55 by author Peter

In this post, you will learn how to upload a file without PostBack in ASP.NET. My main focus to write this blog is that, if you work with file upload control, the page requires full PostBack and if your file upload control is inside the update panel, you must specify your submit button in trigger, as shown below.

 <Triggers> 
    <asp:PostBackTrigger ControlID=""/> 
 </Triggers> 


This also causes the full PostBack problem. To remove this problem, use "Handler" in ASP. NET C#.

UploadFile.ashx Code

 using System; 
 using System.Web; 
 using System.IO; 
 using System.Web.SessionState; 
 public class UploadFile: IHttpHandler, IRequiresSessionState { 
     public void ProcessRequest(HttpContext context) { 
         string filedata = string.Empty; 
         if (context.Request.Files.Count > 0) { 
             HttpFileCollection files = context.Request.Files; 
             for (int i = 0; i < files.Count; i++) { 
                 HttpPostedFile file = files[i]; 
                 if (Path.GetExtension(file.FileName).ToLower() != ".jpg" && 
                     Path.GetExtension(file.FileName).ToLower() != ".png" && 
                     Path.GetExtension(file.FileName).ToLower() != ".gif" && 
                     Path.GetExtension(file.FileName).ToLower() != ".jpeg" && 
                     Path.GetExtension(file.FileName).ToLower() != ".pdf" 
                 ) { 
                     context.Response.ContentType = "text/plain"; 
                     context.Response.Write("Only jpg, png , gif, .jpeg, .pdf are allowed.!"); 
                     return; 
                 } 
                 decimal size = Math.Round(((decimal) file.ContentLength / (decimal) 1024), 2); 
                 if (size > 2048) { 
                     context.Response.ContentType = "text/plain"; 
                     context.Response.Write("File size should not exceed 2 MB.!"); 
                     return; 
                 } 
                 string fname; 
                 if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") { 
                     string[] testfiles = file.FileName.Split(new char[] { 
                         '\\' 
                     }); 
                     fname = testfiles[testfiles.Length - 1]; 
                 } else { 
                     fname = file.FileName; 
                 } 
                 //here UploadFile is define my folder name , where files will be store. 
                 string uploaddir = System.Configuration.ConfigurationManager.AppSettings["UploadFile"]; 
                 filedata = Guid.NewGuid() + fname; 
                 fname = Path.Combine(context.Server.MapPath("~/" + uploaddir + "/"), filedata); 
                 file.SaveAs(fname); 
             } 
         } 
         context.Response.ContentType = "text/plain"; 
         context.Response.Write("File Uploaded Successfully:" + filedata + "!"); 
         //if you want to use file path in aspx.cs page , then assign it in to session 
         context.Session["PathImage"] = filedata; 
     } 
     public bool IsReusable { 
         get { 
             return false; 
         } 
     } 
 } 


web.config code

 <?xml version="1.0"?> 
 <!-- 
 For more information on how to configure your ASP.NET application, please visit 
 http://go.microsoft.com/fwlink/?LinkId=169433 
 --> 
 <configuration> 
     <system.web> 
         <compilation debug="true" targetFramework="4.0" /> 
     </system.web> 
     <appSettings> 
         <add key="Upload" value="UploadFile" /> 
     </appSettings> 
 </configuration> 


Default.aspx code

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
     <html xmlns="http://www.w3.org/1999/xhtml"> 
  
     <head runat="server"> 
         <title></title> 
         <%-- Should have internet connection for loading this file other wise inherit own js file for supporting js library--%> 
             <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
             <script type="text/javascript"> 
                 function onupload() { 
                     $(function() { 
                         var fileUpload = $('#<%=FileUpload.ClientID%>').get(0); 
                         var files = fileUpload.files; 
                         var test = new FormData(); 
                         for (var i = 0; i < files.length; i++) { 
                             test.append(files[i].name, files[i]); 
                         } 
                         $.ajax({ 
                             url: "UploadFile.ashx", 
                             type: "POST", 
                             contentType: false, 
                             processData: false, 
                             data: test, 
                             success: function(result) { 
                                 if (result.split(':')[0] = "File Uploaded Successfully") { 
                                     document.getElementById("<%=lbl_smsg.ClientID%>").innerText = result.split(':')[0]; 
                                 } else { 
                                     document.getElementById("<%=lbl_emsg.ClientID%>").innerText = result; 
                                 } 
                             }, 
                             error: function(err) { 
                                 alert(err.statusText); 
                             } 
                         }); 
                     }) 
                 } 
             </script> 
     </head> 
  
     <body> 
         <form id="form1" runat="server"> 
             <asp:ScriptManager ID="scmain" runat="server"></asp:ScriptManager> 
             <asp:UpdatePanel ID="upmain" runat="server"> 
                 <ContentTemplate> 
                     <fieldset> 
                         <legend>Upload File WithOut PostBack inside Update Panel</legend> 
                         <asp:FileUpload ID="FileUpload" runat="server" /> 
                         <input type="button" id="btnUpload" value="Upload Files" onclick="onupload();" /> 
                         <asp:Label ID="lbl_emsg" runat="server" ForeColor="Red"></asp:Label> 
                         <asp:Label ID="lbl_smsg" runat="server" ForeColor="Green"></asp:Label> 
                     </fieldset> 
                 </ContentTemplate> 
             </asp:UpdatePanel> 
         </form> 
     </body> 
  
     </html> 


Default.aspx code.cs code

 using System; 
 using System.Collections.Generic; 
 using System.Linq; 
 using System.Web; 
 using System.Web.UI; 
 using System.Web.UI.WebControls; 
 public partial class _Default: System.Web.UI.Page 
 { 
     protected void Page_Load(object sender, EventArgs e) {} 
 } 

HostForLIFE.eu ASP.NET Core 1.1 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



European ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Publish Your ASP.NET Core in IIS

clock November 3, 2016 09:27 by author Scott

When you build ASP.NET Core applications and you plan on running your applications on IIS you'll find that the way that Core applications work in IIS is radically different than in previous versions of ASP.NET.

In this post I'll explain how ASP.NET Core runs in the context of IIS and how you can deploy your ASP.NET Core application to IIS.

Setting Up Your IIS and ASP.NET Core

The most important thing to understand about hosting ASP.NET Core is that it runs as a standalone, out of process Console application. It's not hosted inside of IIS and it doesn't need IIS to run. ASP.NET Core applications have their own self-hosted Web server and process requests internally using this self-hosted server instance.

You can however run IIS as a front end proxy for ASP.NET Core applications, because Kestrel is a raw Web server that doesn't support all features a full server like IIS supports. This is actually a recommended practice on Windows in order to provide port 80/443 forwarding which kestrel doesn't support directly. For Windows IIS (or another reverse proxy) will continue to be an important part of the server even with ASP.NET Core applications.

Run Your ASP.NET Core Site

To run your ASP.NET Core site, it is quite different with your previous ASP.NET version. ASP.NET Core runs its own web server using Kestrel component. Kestrel is a .NET Web Server implementation that has been heavily optimized for throughput performance. It's fast and functional in getting network requests into your application, but it's 'just' a raw Web server. It does not include Web management services as a full featured server like IIS does.

If you run on Windows you will likely want to run Kestrel behind IIS to gain infrastructure features like port 80/443 forwarding via Host Headers, process lifetime management and certificate management to name a few.

ASP.NET Core applications are standalone Console applications invoked through the dotnet runtime command. They are not loaded into an IIS worker process, but rather loaded through a native IIS module called AspNetCoreModule that executes the external Console application.

Once you've installed the hosting bundle (or you install the .NET Core SDK on your Dev machine) the AspNetCoreModule is available in the IIS native module list:

The AspNetCoreModule is a native IIS module that hooks into the IIS pipeline very early in the request cycle and immediately redirects all traffic to the backend ASP.NET Core application. All requests - even those mapped to top level Handlers like ASPX bypass the IIS pipeline and are forwarded to the ASP.NET Core process. This means you can't easily mix ASP.NET Core and other frameworks in the same Site/Virtual directory, which feels a bit like a step back given that you could easily mix frameworks before in IIS.

While the IIS Site/Virtual still needs an IIS Application Pool to run in, the Application Pool should be set to use No Managed Code. Since the App Pool acts merely as a proxy to forward requests, there's no need to have it instantiate a .NET runtime.

The AspNetCoreModule's job is to ensure that your application gets loaded when the first request comes in and that the process stays loaded if for some reason the application crashes. You essentially get the same behavior as classic ASP.NET applications that are managed by WAS (Windows Activation Service).

Once running, incoming Http requests are handled by this module and then routed to your ASP.NET Core application.

So, requests come in from the Web and int the kernel mode http.sys driver which routes into IIS on the primary port (80) or SSL port (443). The request is then forwarded to your ASP.NET Core application on the HTTP port configured for your application which is not port 80/443. In essence, IIS acts a reverse proxy simply forwarding requests to your ASP.NET Core Web running the Kestrel Web server on a different port.

Kestrel picks up the request and pushes it into the ASP.NET Core middleware pipeline which then handles your request and passes it on to your application logic. The resulting HTTP output is then passed back to IIS which then pushes it back out over the Internet to the HTTP client that initiated the request - a browser, mobile client or application.

The AspNetCoreModule is configured via the web.config file found in the application's root, which points a the startup command (dotnet) and argument (your application's main dll) which are used to launch the .NET Core application. The configuration in the web.config file points the module at your application's root folder and the startup DLL that needs to be launched.

Here's what the web.config looks like:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!--
    Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
  -->
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*"
        modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="dotnet"
                arguments=".\AlbumViewerNetCore.dll"
                stdoutLogEnabled="false"
                stdoutLogFile=".\logs\stdout"
                forwardWindowsAuthToken="false" />
  </system.webServer>
</configuration>

You can see that module references dotnetexe and the compiled entry point DLL that holds your Main method in your .NET Core application.

IIS is Recommended!

We've already discussed that when running ASP.NET Core on Windows, it's recommended you use IIS as a front end proxy. While it's possible to directly access Kestrel via an IP Address and available port, there are number of reasons why you don't want to expose your application directly this way in production environments.

First and foremost, if you want to have multiple applications running on a single server that all share port 80 and port 443 you can't run Kestrel directly. Kestrel doesn't support host header routing which is required to allow multiple port 80 bindings on a single IP address. Without IIS (or http.sys actually) you currently can't do this using Kestrel alone (and I think this is not planned either).

The AspNetCoreModule running through IIS also provides the necessary process management to ensure that your application gets loaded on the first access, ensures that it stays up and running and is restarted if it crashes. The AspNetCoreModule provides the required process management to ensure that your AspNetCore application is always available even after a crash.

It's also a good idea to run secure SSL requests through IIS proper by setting up certificates through the IIS certificate store and letting IIS handle the SSL authentication. The backplane HTTP request from IIS can then simply fire a non-secure HTTP request to your application. This means only a the front end IIS server needs a certificate even if you have multiple servers on the backplane serving the actual HTTP content.

IIS can also provide static file serving, gzip compression of static content, static file caching, Url Rewriting and a host of other features that IIS provides natively. IIS is really good and efficient at processing non-application requests, so it's worthwhile to take advantage of that. You can let IIS handle the tasks that it's really good at, and leave the dynamic tasks to pass through to your ASP.NET Core application.

The bottom line for all of this is if you are hosting on Windows you'll want to use IIS and the AspNetCoreModule.

How to Publish ASP.NET Core in IIS

In order to run an application with IIS you have to first publish it. There are two ways to that you can do this today:

1. Use dotnet publish

Using dotnet publish builds your application and copies a runnable, self-contained version of the project to a new location on disk. You specify an output folder where all the files are published. This is not so different from classic ASP.NET which ran Web sites out of temp folders. With ASP.NET Core you explicitly publish an application into a location of your choice - the files are no longer hidden away and magically copied around.

A typical publish command may look like this:

dotnet publish
      --framework netcoreapp1.0
      --output "c:\temp\AlbumViewerWeb"
      --configuration Release

If you open this folder you'll find that it contains your original application structure plus all the nuget dependency assemblies dumped into the root folder:

Once you've published your application and you've moved it to your server (via FTP or other mechanism) we can then hook up IIS to the folder.

After that, please just make sure you setup .NET Runtime to No Managed Code as shown above.

And that's really all that needs to happen. You should be able to now navigate to your site or Virtual and the application just runs.

You can now take this locally deployed Web site, copy it to a Web Server (via FTP or direct file copy or other publishing solution), set up a Site or Virtual and you are off to the races.

2. Publish Using Visual Studio

The dotnet publish step works to copy the entire project to a folder, but it doesn't actually publish your project to a Web site (currently - this is likely coming at a later point).

In order to get incremental publishing to work, which is really quite crucial for ASP.NET Core applications because there are so many dependencies, you need to use MsDeploy which is available as part of Visual Studio's Web Publishing features.

Currently the Visual Studio Tooling UI is very incomplete, but the underlying functionality is supported. I'll point out a few tweaks that you can use to get this to work today.

When you go into Visual Studio in the RC2 Web tooling and the Publish dialog, you'll find that you can't create a publish profile that points at IIS. There are options for file and Azure publishing but there's no way through the UI to create a new Web site publish.

However, you can cheat by creating your own .pubxml file and putting it into the \Properties\PublishProfilesfolder in your project.

To create a 'manual profile' in your ASP.NET Core Web project:

  • Create a folder \Properties\PublishProfiles
  • Create a file <MyProfile>.pubxml

You can copy an existing .pubxml from a non-ASP.NET Core project or create one. Here's an example of a profile that works with IIS:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <WebPublishMethod>MSDeploy</WebPublishMethod>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>Any CPU</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish>http://samples.west-wind.com/AlbumViewerCore/index.html</SiteUrlToLaunchAfterPublish>
    <LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
    <ExcludeApp_Data>False</ExcludeApp_Data>
    <PublishFramework>netcoreapp1.0</PublishFramework>
    <UsePowerShell>True</UsePowerShell>
    <EnableMSDeployAppOffline>True</EnableMSDeployAppOffline>
    <MSDeployServiceURL>https://publish.west-wind.com</MSDeployServiceURL>
    <DeployIisAppPath>samples site/albumviewercore</DeployIisAppPath>
    <RemoteSitePhysicalPath />
    <SkipExtraFilesOnServer>True</SkipExtraFilesOnServer>
    <MSDeployPublishMethod>RemoteAgent</MSDeployPublishMethod>
    <EnableMSDeployBackup>False</EnableMSDeployBackup>
    <UserName>username</UserName>
    <_SavePWD>True</_SavePWD>
    <ADUsesOwinOrOpenIdConnect>False</ADUsesOwinOrOpenIdConnect>
    <AuthType>NTLM</AuthType>
  </PropertyGroup>
</Project>

Once you've created a .pubxml file you can now open the publish dialog in Visual Studio with this Profile selected:

At this point you should be able to publish your site to IIS on a remote server and use incremental updates with your content.

#And it's a Wrap Currently IIS hosting and publishing is not particularly well documented and there are some rough edges around the publishing process. Microsoft knows of these issues and this will get fixed by RTM of ASP.NET Core.

In the meantime I hope this post has provided the information you need to understand how IIS hosting works and a few tweaks that let you use the publishing tools available to get your IIS applications running on your Windows Server.



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