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.0 Hosting - HostForLIFE.eu :: How to Generate Unique Data in GridView?

clock June 29, 2016 22:02 by author Peter

This time, I will show you how to generate Unique Data in GridView. This code is useful to avoiding data duplicacy in GridView:

HTML of page : EliminateGridview.aspx
<div> 
<h1> 
        Grid with duplicate data 
    </h1> 
<asp:GridView ID="gvDuplicate" runat="server" HeaderStyle-BackColor="gray" 
            AutoGenerateColumns="False" AlternatingRowStyle-BackColor="Yellow " BackColor="white" 
            BorderColor="blue" BorderStyle="None"> 
    <Columns> 
        <asp:BoundField DataField="Name" HeaderText="Name"> 
            <ItemStyle HorizontalAlign="Left" Width="20%" /> 
        </asp:BoundField> 
        <asp:BoundField DataField="City" HeaderText="City"> 
            <HeaderStyle Wrap="true"></HeaderStyle> 
            <ItemStyle HorizontalAlign="Left" Width="20%" Wrap="true" /> 
        </asp:BoundField> 
    </Columns> 
</asp:GridView> 
</div> 
<div> 
<h1> 
        Grid with unique data 
    </h1> 
<asp:GridView ID="gvUnique" runat="server" HeaderStyle-BackColor="gray" AutoGenerateColumns="False" 
            AlternatingRowStyle-BackColor="Yellow " BackColor="white" BorderColor="blue" 
            BorderStyle="None"> 
    <Columns> 
        <asp:BoundField DataField="Name" HeaderText="Name"> 
            <ItemStyle HorizontalAlign="Left" Width="20%" /> 
        </asp:BoundField> 
        <asp:BoundField DataField="City" HeaderText="City"> 
            <HeaderStyle Wrap="true"></HeaderStyle> 
            <ItemStyle HorizontalAlign="Left" Width="20%" Wrap="true" /> 
        </asp:BoundField> 
    </Columns> 
</asp:GridView> 
</div> 

Code behind page: EliminateGridview.aspx.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Configuration; 

public partial class EliminateGridview: System.Web.UI.Page  

protected void Page_Load(object sender, EventArgs e)  

    if (!IsPostBack)  
    { 
        gvDuplicate.DataSource = gvUnique.DataSource = testData(); 
        gvDuplicate.DataBind(); 
        gvUnique.DataBind(); 
        RemoveDuplicateData(0); 
    } 


//generating datatable 
public DataTable testData()  

    DataTable dt = new DataTable(); 
    //Adding columns to datatable        
    dt.Columns.Add("Name"); 
    dt.Columns.Add("City"); 
    //Adding records to the datatable 
    dt.Rows.Add("Peter", "London"); 
    dt.Rows.Add("Peter", "Manchester"); 
    dt.Rows.Add("Peter", "Liverpool"); 
    dt.Rows.Add("Peter", "Bristol"); 
    dt.Rows.Add("Kevin", "Leeds"); 
    dt.Rows.Add("Kevin", "Glasgow"); 
    dt.Rows.Add("Kevin", "York"); 
    dt.Rows.Add("Anthony", "Cambridge"); 
    dt.Rows.Add("Anthony", "Bradford"); 
    dt.Rows.Add("Anthony", "Oxford"); 
    dt.Rows.Add("Steven", "Swansea"); 
    dt.Rows.Add("Richard", "Norwich"); 
    return dt; 

private void RemoveDuplicateData(int cellno)  

    string initialnamevalue = gvUnique.Rows[0].Cells[cellno].Text; 
    for (int i = 1; i < gvUnique.Rows.Count; i++) 
    { 

        if (gvUnique.Rows[i].Cells[cellno].Text == initialnamevalue)  
        { 
            gvUnique.Rows[i].Cells[cellno].Text = string.Empty; 
        }  
        else  
        { 
            initialnamevalue = gvUnique.Rows[i].Cells[cellno].Text; 
        } 
    } 


HostForLIFE.eu ASP.NET Core 1.0 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.0 Hosting - HostForLIFE.eu :: How to Send (Pass) multiple parameters to WebMethod in jQuery AJAX POST in ASP.NET?

clock June 23, 2016 22:05 by author Peter

Today let me show you how to send (Pass) multiple parameters to WebMethod in jQuery AJAX POST in ASP.NET. Generally people face issues with jQuery AJAX POST call to WebMethod when multiple parameters have to be passed, due to syntax errors the WebMethod does not get called. Hence I have come up in an innovative way where using JSON object and JSON2 Stringify method one can easily post any number and any type of parameters to WebMethod using jQuery AJAX.

 
HTML Markup
The HTML Markup consists of a sample form with TextBoxes for accepting Name and Age and a Button to post the values to server’s WebMethod using jQuery AJAX.
<table border="0" cellpadding="0" cellspacing="0">
<tr>
    <td>
        Name:
    </td>
    <td>
        <asp:TextBox ID="txtName" runat="server" Text = "Peter" />
    </td>
</tr>
<tr>
    <td>
        Age:
    </td>
    <td>
        <asp:TextBox ID="txtAge" runat="server" Text = "29"/>
    </td>
</tr>
<tr>
    <td>
        <asp:Button ID="btnSubmit" Text="Submit" runat="server" />
    </td>
</tr>
</table>
 
 
WebMethod accepting multiple parameters
The following WebMethod accepts multiple parameters from client side using the jQuery AJAX.
C#
[System.Web.Services.WebMethod]
public static string SendParameters(string name, int age)
{
    return string.Format("Name: {0}{2}Age: {1}", name, age, Environment.NewLine);
}

 
VB.Net
<System.Web.Services.WebMethod()> _
Public Shared Function SendParameters(name As String, age As Integer) As String
    Return String.Format("Name: {0}{2}Password: {1}", name, age, Environment.NewLine)
End Function

 
Passing multiple parameters to WebMethod in jQuery AJAX POST in ASP.Net
When the Button is clicked, the Name and Age is fetched from their respective TextBoxes and are assigned to a JSON object in which I have created two properties with the name same as that of the WebMethod parameters.

The JSON object is now serialized to a JSON string using JSON2 Stringify method and then passed as parameter to the WebMethod.
In this technique there are no syntax errors and also there’s no need to convert values of TextBoxes to integer or some other Data Type.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/json2/20130526/json2.min.js"></script>
<script type="text/javascript">
$(function () {
    $("[id*=btnSubmit]").click(function () {
        var obj = {};
        obj.name = $.trim($("[id*=txtName]").val());
        obj.age = $.trim($("[id*=txtAge]").val());
        $.ajax({
            type: "POST",
            url: "CS.aspx/SendParameters",
            data: JSON.stringify(obj),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                alert(r.d);
            }
        });
        return false;
    });
});
</script>

HostForLIFE.eu ASP.NET 4.6 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 5 Hosting - HostForLIFE.eu :: Waiting Message in ASP.NET

clock June 23, 2016 20:54 by author Anthony

When someone calls your company and all agents are busy assisting other customers, they will be sent to the waiting queue. When they enter the waiting queue, the "Waiting Message" plays. An example of a common Waiting Message is, "All of our agents are currently busy. Please hold and we will answer your call as soon as possible."

Sometimes we need please wait message button in our website to inform the visitor that their submission still in progress. Today, we will explain about creating please wait message in the button on ASP.NET website. You can copy below code to please wait message in the button.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PleaseWaitButton.aspx.cs"
   Inherits="PleaseWaitButton" %>

<!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>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <div>
               <asp:Button ID="Button1" runat="server" Text="Button" />
           </div>
       </div>
   </form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class PleaseWaitButton : System.Web.UI.Page
{
   protected void Button1_Click(object sender, System.EventArgs e)
   {
       System.Threading.Thread.Sleep(5000);
       ClientScript.RegisterClientScriptBlock(this.GetType(), "reset",
 "document.getElementById('" + Button1.ClientID + "').disabled=false;", true);
   }

   protected void Page_Load(object sender, System.EventArgs e)
   {
       System.Threading.Thread.Sleep(5000);
       Button1.Attributes.Add("onclick", ClientScript.GetPostBackEventReference(Button1, "") + ";
this.value='Please wait...';this.disabled = true;");
   }

}


Finish, happy coding.


HostForLIFE.eu ASP.NET 4.6 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 5 Hosting - HostForLIFE.eu :: Implementing Cookie Authentication in ASP.NET 5

clock June 9, 2016 20:03 by author Anthony

In this tutorial, I'm going to explain about cookie based authentication in ASP.NET 5. I am implementing a cookie authentication in ASP.NET MVC application. Similar to other middleware components in ASP.NET, Cookie Authentication is also a middleware component, which you need to plug into ASP.NET pipeline.

For implementing cookie authentication, you require reference of Cookie middleware, here is the project.json file.
{
    "dependencies": {
        "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
        "Microsoft.AspNet.Hosting": "1.0.0-beta1",
        "Microsoft.AspNet.Mvc": "6.0.0-beta1",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
        "Microsoft.AspNet.Security": "1.0.0-beta1",
        "Microsoft.AspNet.Security.Cookies": "1.0.0-beta1",
        "Microsoft.AspNet.StaticFiles": "1.0.0-beta1",
    },
    "commands": {
        "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"
    },
     "frameworks": {
        "aspnet50": {}
  }
}


All the components used in this project are available in ASP.NET Core Framework as well.

Now you need to plug the Cookie authentication module to use in ASP.NET pipeline, you can do this via Startup.cs file.

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseErrorPage();
 
        app.UseServices(services =>
        {
            services.AddMvc();
        });
     
        app.UseCookieAuthentication(options => {
            options.LoginPath = new PathString("/Home/Login");
        });
        app.UseMvc();                       
    }       
}


Now, you need to apply the Authorize filter to protect resources, I am applying it in the class level. When there is a unauthorized request to such resource, filter returns 401 and the cookie middleware redirects to /Home/Login.

Note: You need to set the LoginPath property explicitly, otherwise it may not redirect.

Authorize]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}


And here is the Login action method, this code is for illustration purpose only, I not validating against database, if username and password matches the hard coded credentials, identity is established with that username.

[AllowAnonymous]
public IActionResult Login()
{
    return View();
}
 
[HttpPost, AllowAnonymous]
public IActionResult Login(User user)
{
    if(user.UserName == "admin" && user.Password == "Password")
    {
        var claims = new[]
        {
            new Claim("name", user.UserName)
        };
        var identity = new ClaimsIdentity(claims,
            CookieAuthenticationDefaults.AuthenticationType);
        Context.Response.SignIn(identity);
 
        return Redirect("~/");
    }
    else
    {
        ModelState.AddModelError("LogOnError",
            "The user name or password provided is incorrect.");
    }
    return View(user);
}
 
public IActionResult Logout()
{
    Context.Response.SignOut
    (CookieAuthenticationDefaults.AuthenticationType);
    return View("Login");
}


And here is the Login view

@using(Html.BeginForm())
{
    @Html.LabelFor(model => model.UserName)
    @Html.EditorFor(model => model.UserName)
    @Html.LabelFor(model => model.Password)
    @Html.PasswordFor(model => model.Password)
    <input type="submit" value="Sign In" />
    <br/>
    @Html.ValidationMessage("LogOnError")
}


To verify the implementation, install the required packages using kpm restore command, once it finishes, execute k web command. If web server is started, browse http://localhost:5001/, which will redirect to /Home/Login page, where you can enter the credentials, you will redirect back to /Home/Index page.

HostForLIFE.eu ASP.NET 5 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.



HostForLIFE.eu Proudly Launches ASP.NET Core 1.0 RC2 Hosting

clock June 4, 2016 00:57 by author Peter

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 ASP.NET Core 1.0 RC2 hosting in their entire servers environment.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET Core 1.0 RC2 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

A key change that occurred between RC1 and RC2 is the introduction of the .NET command-line interface.  This tool replaces the dnvm, dnx, and dnu utilities with a single tool that handles the responsibilities of these tools. In RC1 an ASP.NET application was a class library that contained a Startup.cs class. When the DNX toolchain run your application ASP.NET hosting libraries would find and execute the Startup.cs, booting your web application. Whilst the spirit of this way of running an ASP.NET Core application still exists in RC2, it is somewhat different. As of RC2 an ASP.NET Core application is a .NET Core Console application that calls into ASP.NET specific libraries. What this means for ASP.NET Core apps is that the code that used to live in the ASP.NET Hosting libraries and automatically run your startup.cs now lives inside a Program.cs.

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 ASP.NET Core 1.0 RC2 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 ASP.NET Core 1.0 RC2 hosting installation to all their new and existing customers. The customers can simply deploy their ASP.NET Core 1.0 RC2 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 ASP.NET Core 1.0 RC2 Hosting can be viewed here http://hostforlife.eu



HostForLIFE.eu supports ASP.NET State Server Service for session :: Moving Session Out-of-Process with StateServer

clock June 2, 2016 20:47 by author Peter

Recently suddenly met a problem with the ASP.NET SessionState. It isn’t a fault of the SessionState itself, but likely a problem with my configuration or uses. Essentially the state was being reset too often. Although I had a timeout value of 1440 minutes, users were getting kicked out after 10-15 minutes. I eventually found out that (for some reason) the IIS worker process was being reset (although it wasn’t configured to self-reset), probably due to an unrecoverable  error in a number of our legacy-based code. And since our SessionState was set to InProc, all of the session data was stored in-the-process and was thus lost whenever it died.

I started researching the alternatives and discovered the proper way to configure the StateServer that comes with ASP.NET to move your sessions out-of-process. This way, you'll literally reset IIS (or if the StateServer is on another machine, reboot your IIS server machine) while not losing session. This seemed like a very appealing situation, and one that many people online endorse as best practice. Another benefit of moving the SessionState out-of-process is that you set yourself up nicely for eventually moving to multiple web servers, or even running simultaneous multiple instances of your application pools on the same machine to spice up performance.

Let’s start from the top. The SessionState is a collection of data that is persisted across multiple web requests to ASP.NET. This can be authentication information, a shopping cart, a theme, or whatnot – essentially any information that you want the server to remember for the next time the user “does something” on your site. This can also be accomplished on the page level with ViewState, but that sends more data back and forth between the client and your server.

If you’re using the cookie method of “tagging” your SessionState (which you should, because cookieless is vulnerable to session hijacking), you’ll have a tiny little harmless cookie called ASP.NET_SessionId which contains a unique session ID that looks something like “okeiohntcofecw55svocxwiz”. This ID is sent to the web server to let the server know which session to retrieve.

If the SessionState is running InProc, all ASP.NET has to do is look at the memory it has of that session information and retrieve or set the values required. However, if that process gets reset (due to an IIS reset, power outage, reboot, failed process, etc) then it no longer has a record of that session information, so that SessionId is no longer valid and the user is “kicked off”.

Additionally, if you increase the number of worker processes per application pool, thinking you’ll be getting better performance on a multiprocessor server, you’ll find that the users continually get kicked off, because each process doesn’t know about the session state of the other so they continually reset the session on each other. This is the same problem you’ll encounter if you try to move to two load-balanced web servers.

The StateServer Solution
Included with .NET is a Windows service called the ASP.NET State Service. This is disabled by default, so if you’re reading this far you may not know about it. This service runs as an additional process so that if the IIS worker process gets reset, the state service is still running with all the session information.

You can even run this State Service on another Windows Server machine. This way, you can have one machine managing your session state, while you can have one or more web servers handling requests. An example situation might look something like this:

(I was trying to find a shape to use for the StateServer to differentiate it from the others… and I chose the “eCommerce Server” shape. As in cash = cache… get it?)

Even though that might be what a more advanced operation might look like, you will likely (such as in development or for a small-load web server) run the StateServer on the same machine as IIS.

Keep in mind that the SessionState is still being stored in memory with the StateServer solution… there’s no persisting of the state to disk. So if the StateServer process gets restarted or rebooted, so does your session information.

The SQL Server Solution
Another solution supported natively by ASP.NET is to use SQL Server to persist state information to disk. This way, even the server handling your state can be rebooted without losing session. This may be the preferred way of doing things for very high-end operations or situations where you need to maintain that information for security or contractual purposes. However, I will not be discussing that here, because I haven’t tried it myself. There’s many resources to learn about this on the web, such as this article from Microsoft.

Enabling StateServer
To enable the ASP.NET State Service, all you have to do is configure the service on both your development and production machines.
Click Start / Run or type Win + R.

  1.     Type in services.msc and press Enter or click OK.
  2.     Locate the ASP.NET State Service in the Services (local) list.
  3.     Right click on it and choose Properties.
  4.     Change the Startup Type to Automatic so that it starts on boot.
  5.     Click the Start button to get it started now.
  6.     Click OK to close the dialog.

Now, if you pull up Task Manager, you’ll notice a nice little aspnet_state.exe process running in addition to the IIS worker process (w3wp.exe). This process is the new StateServer that will maintain all your state data. But in order to use it, we must enable your ASP.NET web site to use the out-of-process StateServer.
Modifying your Web.Config

For the site that you’d like to have use the out-of-process StateServer, first open your web.config file for that site.

Locate (or add) a sessionState element in the system.web section of the config file, like this:

Note the cookieless=”UseCookies” and mode=”StateServer” attributes. These are required to use the StateServer in a cookie’d fashion.

The timeout attribute is the time, in minutes, that you want the session to remain valid.

Also note that this example above is for the StateServer running on the same machine as IIS. With no connection string specified, it looks for a StateServer running on the local machine. If you need to move the StateServer onto another machine, you must match up your MachineKeys and set a StateServer connection string for IIS to connect to. Google is your friend.

Now, your site should be using the StateServer for all of its session data. You may (or may not, but it might be a good idea) need to restart IIS for this to be optimally configured.

Non-Serializable Session Data
The only caveat in this post, and it’s a big one, is that you will receive an error if you try to store non-Serializable data into the session now that you have an out-of-process state (i.e. a System.Data.DataView). Serializable classes are those that have the Serializable attribute set and are optimized for serialization (i.e. a System.Data.DataTable).

You will need to review and test your code (or write new code accordingly) to make sure that you are not storing non-Serializable data to your session when using out-of-process state. If you are using custom classes to store session data, review them for serializable members and properties, and then mark them as serializable.

Final Thoughts
I’ve seen developers proclaim online that all ASP.NET devs should design their applications around an out-of-process session model, and now that I’ve discovered it, I am inclined to agree. If you design from the beginning to be compatible with a StateServer or SQL database state server, you can easily make the jump from one web server to two. A few things to think about are the amount of memory available to the state service, latency and the connection between servers if the StateService is running on another machine, and how to minimize state since it’s now being transferred between processes.

HostForLIFE.eu ASP.NET State Server
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 4.5 Hosting - HostForLIFE.eu :: Secure Your Website No Copy Paste

clock June 2, 2016 20:43 by author Anthony

Have you ever worked really hard on graphics for your site only to find later that someone has stolen them as their own. You can help encrypt and protect your site with the following codes. No right click block is 100% effective, but they will help against novices.

In the real world, sometimes a developer needs to restrict a basic facility such as cut, copy and paste on an entire web page but not on a specific control. At that time you will need some easy way to stop these kinds of facilities on the page but not create code in every control to disable these facilities.
Suppose you have 20 "TextBox" controls in your page and you want to restrict the cut, copy and paste in all the textboxes, then you do not need to write the disable code in each TextBox. In this scenario, you need to just write the disable code only in the "body" tag.
To explain such implementation, I will use the following procedure.

Step 1

Create an ASP.Net Empty Website named "My Project".

Step 2

Add a new web form named "Default.aspx" into it.

Step 3

Add 2 "TextBox" controls to the page named "Default.aspx" .


Step 4

On Cut: By this, you can disable the "Cut " facility in both of the "TextBox" Controls.
Syntax: oncut= “return false”;

On Copy: By this, you can disable the "Copy " facility in both of the "TextBox" controls.
Syntax: oncopy= “return false”;

On Paste: By this, you can disable the "Cut" facility in both of the "TextBox" controls.
Syntax: onpaste= “return false”;

To disable the All (Cut, Copy and Paste) in the entire page:



HostForLIFE.eu ASP.NET 4.5 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 4.5 Hosting - HostForLIFE.eu :: Fixing ASP.NET 4.5 Register on Web Server

clock May 26, 2016 20:55 by author Anthony

 

NET 4.5 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.5. When making an ASP.NET website throughout IIS 7.5 in Visual Studio 2008/2010, you can find the following issue:

“ASP.NET 4.5 has not been registered on the Web server. You need to manually configure your Web server for ASP.NET 4.5 in order for your site to run correctly, Press F1 for more details”

This error usually occurs if you have installed IIS 7.x ‘after’ installing .NET. In order to resolve the error, do the following:

Step 1: Open Control Panel > Programs > Turn Windows Features on or off > Internet Information Services > World Wide Web Services > Application development Feature

Check the box 'ASP.NET' . Also in the Web Management Tools, remember to select IIS 6 Management Compatibility and IIS Metabase as shown below.

Note: Make sure that you are running Visual Studio 2010 as Administrator.

Now run the site from Visual Studio 2010 using Ctrl + F5.

Step 2: If you further get the error “Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list” or Managed handler is used; however, ASP.NET is not installed or is not installed completely then do a Visual Studio 2010 repair.

Start > Programs > Accessories > Run. Type this command depending on the version of VS 2010 installed.

Silent Repair for 32-bit

%windir%\Microsoft.NET\Framework\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart


Silent Repair for 64-bit

%windir%\Microsoft.NET\Framework64\v4.0.30319\SetupCache\Client\setup.exe /repair /x86 /x64 /ia64 /parameterfolder Client /q /norestart

That’s it. Restart IIS and the errors should be fixed.

Step 3: If the errors are not yet fixed, there could be an issue in the Application Pool. Follow these steps

1. Open IIS Manager (Run > Inetmgr) . Expand the server node and then click Application Pools

2. Now select the application pool that contains the application that you want to change. Go to Actions > View Applications.

3. Select the Application pool to change > In Action Pane, click on ‘Change Application Pool’

4. In the ‘Select Application Pool’ dialog box, select the application pool associated with .NET 4.0 from the Application pool list and then click OK.

 

 


HostForLIFE.eu ASP.NET 4.5 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.0 Hosting - HostForLIFE.eu :: How To Make DropDown List with ASP.NET Core WEB API and AngularJS 2 ?

clock May 22, 2016 05:48 by author Anthony

In this post, we take it to next level and implement it with ASP.NET Core Web API and AngularJS 2. But starting/configuring AngularJS 2 with ASP.NET Core is not straight forward and it requires some manual configurations to be done. If you are not sure how to do it, I recommend you to read this helpful post to find out post how to start with AngularJS 2 in ASP.NET Core with TypeScript using Visual Studio 2015.

Cascading DropDown List with ASP.NET Core WEB API and AngularJS 2

I believe now you have an idea about starting with AngularJS 2. I also followed same steps to configure this demo project as mentioned. So now let’s move to next part. Please note, I selected the “Web application template” while creating the project but removed all the unnecessary code.

Add Models classes in Models folder

First, add Country and State model classes in Models folder. Following is the code for Country.cs. This class has 2 properties and a method which returns a list of countries. For demo, I used static data but you can also get the same list from database.

public class Country
{
    public int id { get; set; }
    public string name { get; set; }

    public Country(int CountryID, string CountryName)
    {
        id = CountryID;
        name = CountryName;
    }

    public static List<Country> GetAllCountries()
    {
        List<Country> lstCountries = new List<Country>();
        lstCountries.Add(new Country(1, "USA"));
        lstCountries.Add(new Country(2, "India"));
        lstCountries.Add(new Country(3, "Australia"));
        lstCountries.Add(new Country(4, "Canada"));
        return lstCountries ;
    }
}

And following is the code for State.cs. This class has 3 properties and a method which returns a list of states. Nothing fancy, self-explanatory code.

public class State
{
    public int id { get; set; }
    public int countryid { get; set; }
    public string name { get; set; }

    public State(int StateID, int CountryID, string StateName)
    {
        id = StateID;
        countryid = CountryID;
        name = StateName;
    }
    public static List<State> GetAllStates()
    {
        List<State>  lstState = new List<State>();
        lstState.Add(new State(1, 1, "Arizona"));
        lstState.Add(new State(2, 1, "Alaska"));
        lstState.Add(new State(3, 1, "Florida"));
        lstState.Add(new State(4, 1, "Hawaii"));
        lstState.Add(new State(5, 2, "Gujarat"));
        lstState.Add(new State(6, 2, "Goa"));
        lstState.Add(new State(7, 2, "Punjab"));
        lstState.Add(new State(8, 3, "Queensland"));
        lstState.Add(new State(9, 3, "South Australia"));
        lstState.Add(new State(10, 3, "Tasmania"));
        lstState.Add(new State(11, 4, "Alberta"));
        lstState.Add(new State(12, 4, "Ontario"));
        lstState.Add(new State(13, 4, "Quebec"));
        lstState.Add(new State(14, 4, "Saskatchewan"));
        return lstState;
    }
}


Add action methods in controller
Next step is to make our WEB API ready. For your information, ASP.NET Core comes with Unified Programming Model for MVC and Web API. So open HomeController.cs and add following 2 action methods.

[HttpGet]
[Route("api/Home/GetCountries")]
public IEnumerable<Country> GetCountries()
{
    return Country.GetAllCountries();
}

[HttpGet]
[Route("api/Home/GetState/{countryid?}")]
public IEnumerable<State> GetState(int countryid = 1)
{
    List<State> lstState = State.GetAllStates();
    return lstState.Where(item => item.countryid == countryid);
}
GetCountries() method makes call to Country.GetAllCountries(); and returns the list. Where the second method GetState() accepts countryid as parameters and based on the its value, filters the state list and return the same.

Note countryid parameter is optional for GetState() action method. And also a default value is supplied to it. Why? Well, this actually allows you to pass countryid in querystring. And while calling REST APIs via AngularJS, the arguments/parameters are appended to URL as part of querystring. And that’s why we must allow our API to support querystring. So following URL,

http://localhost:53483/api/Home/GetState/1
is similar to
http://localhost:53483/api/Home/GetState?countryid=1

AngularJS 2 application structure
Create a folder named “app” in wwwroot folder. If you have already created while configuring AngularJS 2 then ignore this step. Now within this folder, following files needs to added.

I already explained about this application structure and about code here. But let me just summarize here again.

country.ts: This file has a simple class called Country with 2 properties id and name.
state.ts: This file has a simple class called States with 3 properties id, countryid and name.
countrylistcomponent.ts: This file contains code for defining a component and template used to render HTML. The Component adds the metadata to the class. And it also makes call to Angular 2 Service, which in turn calls WEB API.
CountryTemplate.html: This file has HTML code to render select dropdown list.
dataservice.ts: This is an Angular 2 service which makes WEB API calls to get list of countries and states.
main.ts: This file contains code to bootstrap angularjs 2 in our application.
country.cs

export class Country {
    constructor(public id: number, public name: string) { }
}
state.cs

export class State {
    constructor(public id: number,
                public countryid: number,
                public name: string) { }
}
dataservice.ts

import { Injectable } from 'angular2/core';
import {Http, URLSearchParams} from "angular2/http";
import 'rxjs/Rx';
import { Country } from './country';
import { State } from './state';


@Injectable()
export class DataService {
    constructor(public http: Http) {
        this.http = http;
    }
    getCountries() {
        return this.http.get("/api/Home/GetCountries")
            .map((responseData) => responseData.json());
    }

    getStates(countryid: string) {
        var params = new URLSearchParams();
        params.set('countryid', countryid);
        return this.http.get("/api/Home/GetState", { search: params })
            .map((responseData) => responseData.json());
    }
}

As you know AngularJS 2 is modular. And as here in this service, we need to make use of HTTP service. So we need to import it. Similarly URLSearchParams, which is used to pass arguments to WEB API method. Therefore,
import {Http, URLSearchParams} from "angular2/http";

And the other import statement import 'rxjs/Rx';, imports ReactiveX library. The Http service in Angular 1 returns a promise where Angular 2 returns an Observable object. And The Observable classes in Angular 2 are provided by the ReactiveX library.

Here, first we inject $http service in class constructor. And we use http.get() to run our HTTP request. And this returns an Observable object. Since it’s an observable object, we can use map() to convert the response into JSON response.

countrylistcomponent.ts

import { Component } from 'angular2/core';
import { DataService } from './dataservice';
import { Country } from './country';
import { State } from './state';

@Component({
    selector: 'my-country-list',
    templateUrl: 'app/CountryTemplate.html',
    providers: [DataService]
})
export class CountryListComponent {
    selectedCountry: Country = new Country(0, 'India');
    countries: Country[];
    states: State[];

    constructor(private _dataService: DataService) {
        this._dataService.getCountries().subscribe(data => { this.countries = data });
    }

    onSelect(countryid) {
        if (countryid == 0)
            this.states = null;
        else
            this._dataService.getStates(countryid).subscribe(data => { this.states = data });
    }
}
This file is modified to use the service to get countries and states list.

First, import the Service and then within @Component directive, set providers: [DataService].
And inject the service in CountryListComponent constructor. And in constructor, call getCountries() method to get list of countries from the service. Since the service returns Observable object, we can use .subscribe() method to get the output in variable.
Also defined onSelect method which will be called onChange event of country dropdown list. This method calls service to get the list of states based on selected countryid and then using subscribe get the list in states variable.
main.ts

import { bootstrap } from 'angular2/platform/browser';
import {HTTP_PROVIDERS} from "angular2/http";
import { CountryListComponent } from './countrylistcomponent';

bootstrap(CountryListComponent, [HTTP_PROVIDERS]);
This file has code to bootstrap AngularJS 2 in our application. Along with that, it also bootstrap application root/parent component. Angular’s http module exposes HTTP_PROVIDERS, which has all the providers that we need, to code http action in our service. Therefore add the http providers to the bootstrap, by importing the HTTP_PROVIDERS from angular2/http.

CountryTemplate.html

<div class="row">
    <div class="col-md-5" style="text-align:right;">
        <label>Country:</label>
    </div>
    <div class="col-md-7" style="text-align:left;">
        <select [(ngModel)]="selectedCountry.id" (change)="onSelect($event.target.value)" style="width:150px;">
            <option value="0">--Select--</option>
            <option *ngFor="let country of countries" value={{country.id}}>{{country.name}}</option>
        </select>
    </div>
</div>
<br />
<div class="row">
    <div class="col-md-5" style="text-align:right;">
        <label>State:</label>
    </div>
    <div class="col-md-7" style="text-align:left;">
        <select style="width:150px;">
            <option value="0">--Select--</option>
            <option *ngFor="let state of states " value={{state.id}}>{{state.name}}</option>
        </select>
    </div>
</div>
And finally the HTML template. This file name is used while specifying metadata for CountryListComponent class.
There are 2 dropdowns list one for country and other for state and also change event defined on country dropdown list. Angular 2 has different way of defining event. Take the HTML event and wrap it with parentheses. $event.target.value will give the selected country id.

I also want to bring in your attention a change made in AngularJS 2 version “2.0.0-beta.17” with respect to *ngFor. Previously we were using,

*ngFor="#state of states"
but in this version, it is changed a bit. Instead of “#”, use “let”

*ngFor="let state of states"
And finally since we are using Angular 2 Http service in our application, we need to include the script in the layout. So, open the _Layout.cshtml file located at Views/Shared/ and add the following code right after the script element that loads Angular 2 core.

<environment names="Development">
  <script src="~/lib/npmlibs/angular2/http.dev.js"></script>
</environment>
<environment names="Staging,Production">
  <script src="~/lib/npmlibs/angular2/http.min.js"></script>
</environment>
Wait!!! We still need to show what we have done till now on UI. So open Views/Home/Index.cshtml and add angular component tag <my-country-list></my-country-list> to HTML file. And we also need to load the application and all its modules. So place following script section to the end of the file.

@section Scripts {
    <script>
        System.config({
            packages: {
                'app': { defaultExtension: 'js' },
                'lib': { defaultExtension: 'js' },
            },
        });

        System.import('app/main')
            .then(null, console.error.bind(console));
    </script>
}

 

 

HostForLIFE.eu ASP.NET Core 1.0 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.0 Hosting - HostForLIFE.eu :: How To Inject Codes in HTTP Pipeline?

clock May 12, 2016 21:49 by author Anthony

In this tutorial, I will explain about how to inject little codes in HTTP Pipeline in ASP.NET Core. “Middleware is defined in the OWIN specification as pass through components that form a pipeline between a server and application to inspect, route, or modify request and response messages for a specific purpose. Middleware consists of application components are incorporated into the ASP.NET HTTP pipeline.” The text is in the ASP.NET Core documentation, and as can be seen, with middleware we can insert a component that is incorporated in ASP.NET HTTP pipeline, that is, we can develop a code with a purpose to manipulate the requests and responses.

A characteristic of middleware is that normally there will a chain of middleware whereby order of configuration, one is called after the end of other and the current middleware can on any moment cancel invoking the next middleware, thus all chains of middleware will be canceled.

middlwares

Do you have doubts about what is middlewares? We can compare middleware with the old http modules that today don’t exist in the new ASP.NET. I have already seen somebody comparing middlewares with a hamburger, because the middle is middleware and the ends are the application and the server. How much more middleware, bigger is the hamburger.

To get more clarity about the subject, I am going to show some middlewares that already are utilized by default in application templates to ASP.NET Core, and after I am going to create a custom middleware.

Below I show the startup class, note that there are some comments that indicate where there is a middleware.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink(); //Middleware
                app.UseDeveloperExceptionPage(); //Middleware
                app.UseDatabaseErrorPage(); //Middleware
            }
            else
            {
                app.UseExceptionHandler("/Home/Error"); //Middleware

                try
                {
                    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                        .CreateScope())
                    {
                        serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
                             .Database.Migrate();
                    }
                }
                catch { }
            }

            app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear()); //Middleware

            app.UseApplicationInsightsExceptionTelemetry(); //Middleware

            app.UseStaticFiles(); //Middleware

            app.UseIdentity(); //Middleware

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            }); //Middleware
        }

Did you see the middlewares utilized in code? Here, each middleware has a responsibility and the gain that we have is we can choose only the ones needed for our project, different from old version of ASP.NET that by default many features were added even when they were not necessary. A very good phrase says: “Pay only by what you use”, in other words, how many fewer middleware you use, the less heavy will be the HTPP pipeline.

Other thing to observe that in code above, all the middlewares start with a “Use”, this is a pattern done by team ASP.NET.

Now I am going to create a own middleware and my goal will be creating one that shows the total time of application to take care of a request. Below following the code.

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace MiddlewareArticle.Middleware
{
    public class ResponseTime
    {
        RequestDelegate _next;

        public ResponseTime(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var sw = new Stopwatch();
            sw.Start();

            await _next(context);

            var isHtml = context.Response.ContentType?.ToLower().Contains("text/html");

            if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault())
            {
                var body = context.Response.Body;
               
                using (var streamWriter = new StreamWriter(body))
                {
                    var textHtml = string.Format(
                        "<footer><div id='process'>Response Time {0} milliseconds.</div>",
                        sw.ElapsedMilliseconds);
                    streamWriter.Write(textHtml);
                }
            }
        }
    }
}


As can be seen, making a middleware is not difficult, it needs a constructor to receive the next middleware and an “Invoke” method that receives the context of HTTP. The goal of showing the total time of application gets in method Invoke. Before calling the next middleware, it is started the time and after of calling the next middleware, when all the middlewares already were executed, I execute the code to show in the HTML the total time.

Remember, I know that all middleware were executed because our middleware must be configured before of all others, thus the code will wait all executions and after the instruction “await _next(context);” we can write our code.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseMiddleware<ResponseTime>(); //Our Middleware
           
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
           
            //...
            //Continue with others codes

The code above is only to show the set up of our middleware in the Configure method of the Startup class. To that this works, it is needed using the instruction “app.UseMiddleware();”, where the UseMiddleware method is used to call custom middlewares.

Conclusion


The ASP.NET Core has changed, not the code that we know, but your core and by this, the way of manipulating a request and a response was changed to middleware. Now it’s lighter and easier to stay between an application and a server. However, take care, it is not because it got better that you must now only use that to develop.

 

 

HostForLIFE.eu ASP.NET Core 1.0 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.

 



About HostForLIFE.eu

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

We have offered the latest Windows 2012 Hosting, ASP.NET 4.5 Hosting, ASP.NET MVC 4 Hosting, ASP.NET MVC 5 Hosting and SQL 2014 Hosting.


Tag cloud

Sign in