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

European ASP.NET 4.5 Hosting - Amsterdam :: Writing asynchronous HTTP Module in ASP.NET 4.5

clock August 13, 2012 09:00 by author Scott

In this article, I will show you new features in ASP.NET 4.5, Asynchronous HTTP Module.

First Just to give a brief Idea, why Asynchronous HTTPModules are important ?


As we all know, web is stateless. A Web page is created from scratch every time whenever it is posted back to the server. In traditional web programming, all the information within the page and control gets wiped off on every postback. Every request in ASP.NET goes through a series of events.


Every request is served by am HTTP handler and it goes a series of HTTPModules (HTTPPipeline) which can be read, update the request. A lot of features of ASP.NET like Authentication, Authorization, Session etc are implemented as HTTP Module in ASP.NET. Let’s have a view on the Request Processing




Now as you can see the request is assigned to a thread T1 from the available threads is thread pool. And the request is passed through several HTTPModules and finally served my HTTPHandler and response is send back with the same thread (T1).


During the entire processing, same thread is engaged in serving the same request and cannot be used by any another request till request processing completes. During the request processing if any HTTPModules depends on some entities like I/O based operations, web services, Databases queries etc then it takes long to complete which makes the thread busy for long which makes asp.net thread will not do anything during that duration and will be useless. In this kind of scenarios the throughput goes down rapidly.


In the above scenario, synchronous HTTPModule can degrade the site performance a lot. So if we can make HTTPModules as asynchronous that can increase the through put a lot. In asynchronous mode, ASP.NET thread get released as soon as the control get passed to another component/module, it does not wait. And the thread becomes available in thread pool and can be used to serve another request. When the component completes its assigned task then it got assigned to new ASP.NET thread which completes the request. The flow can be graphically presented as




In the above picture, An asp.net thread T1 is assigned from threadpool to server the request. When the control got passed to File System to log message, asp.net thread got released and when essage logging got completed, control passed to asp.net and it is assigned to another thread say T2 from thread pool.

In .NET Framework 4.o, there was some major enhancement made for asynchronous programming model. Any asynchronous operation is represents a Task and it comes under the namespace System.Threading.Tasks.Task.

In .NET 4.5, there are some new operator and keyword introduced that makes the life easy for implement Asynchronous feature. One is async keyword and await operator.


These two enables us to write the asynchronous code is similar fashion as we write for synchronous mode.


And these features can be easily used while writing HTTPModules and HTTPHandlers. We’ll be using these enhancements in writing our custom asynchronous HTTPModule.


In my sample as depicted in image, I am creating a module that writes some log messages in a text file for every request made.


So to create a Custom
HTTPModule, Create a class library project. And create a class say named LogModule which implements IHttpModule. For this you need to add a reference of Assembly System.Web.

LogModule
would contains the methods discussed below.

We need to implement two methods Init and Dispose that are part of
IHTTPModule interface.

Here first , I have written an asynchronous method that actually reads the information from the request and writes in the log file asynchronously . For this I have used
WriteAsync of FileStream

private async Task WriteLogmessages(object sender, EventArgs e)
{
    HttpApplication app = (HttpApplication)sender;
        DateTime time = DateTime.Now;

        string line = String.Format(
        "{0,10:d}    {1,11:T}    {2, 32}   {3}\r\n",
        time, time,
        app.Request.UserHostAddress,
        app.Request.Url);
        using (_file = new FileStream(
            HttpContext.Current.Server.MapPath(
              "~/App_Data/RequestLog.txt"),
            FileMode.OpenOrCreate, FileAccess.Write,
            FileShare.Write, 1024, true))
        {
            line = line + "  ," + threaddetails;
            byte[] output = Encoding.ASCII.GetBytes(line);

            _file.Seek(_position, SeekOrigin.Begin);
            _position += output.Length;
            await _file.WriteAsync(output, 0, output.Length);
        }

}

Here you can see the await key word, what it means..


As per msdn “An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.“

await is used with some asynchronous method that returns task and is used suspend the execution of the method until the task completes and control is returned back to the caller to execute further. await should be used with the last expression of any code block.

And Init method would be like

public void Init(HttpApplication context)

{

        // It wraps the Task-based method
        EventHandlerTaskAsyncHelper asyncHelper =
           new EventHandlerTaskAsyncHelper(WriteLogmessages);

        //asyncHelper's BeginEventHandler and EndEventHandler eventhandler that is used
        //as Begin and End methods for Asynchronous HTTP modules
        context.AddOnPostAuthorizeRequestAsync(
        asyncHelper.BeginEventHandler, asyncHelper.EndEventHandler);

}

So apart from above these methods, we need to implement the dispose method.

Now compile your class library and use the reference in your ASP.NET website . Now as you must be knowing that we need to need to add the entry in the config file. So it’ll be as

<system.webServer>

<modules>
<add name="MyCustomHTTPModule" type="MyCustomHTTPModule.LogModule, MyCustomHTTPModule"/>
</modules>
</system.webServer>

Now when you run your application, you will see the logs are created in a text file in App_Data folder as mentioned path in the code.

Hope you all have liked this new feature.

 

 



European ASP.NET 4.5 Hosting - Amsterdam :: Custom Caching Provider in ASP.NET 4.0/4.5

clock August 6, 2012 06:54 by author Scott

In this article I am trying to explain Custom Caching Provider in ASP.NET 4.0 or 4.5. I have created a sample in Visual Studio 2011.

Purpose

Caching enables you to store data in memory for rapid access. When the data is accessed again, applications can get the data from the cache instead of retrieving it from the original source. This can improve performance and scalability. In addition, caching makes data available when the data source is temporarily unavailable.


Code:

Step 1
: Create two new projects; one is Web Application and the other is Class Library.

Step 2
: Now open the Class Library project and add a reference for System.Web assembly.

Step 3
: Now inherit your class from OutputCacheProvider Class.

Step 4
: Now override all Add, Get, Set and Remove Methods.

Here is sample Code.

public class FileCacheProvider : OutputCacheProvider

    {
        private string _filecachePath;

        public string FilecachePath
        {
            get
            {
                if (!string.IsNullOrEmpty(_filecachePath))
                    return _filecachePath;
                _filecachePath = System.Configuration.ConfigurationManager.AppSettings["OutputCachePath"];

                var context = HttpContext.Current;

                if (context != null)
                {
                    _filecachePath = context.Server.MapPath(_filecachePath);
                    if (!_filecachePath.EndsWith("\\"))
                        _filecachePath += "\\";
                }

                return _filecachePath;
            }
        }
        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            Debug.WriteLine("Cache.Add(" + key + ", " + entry + ", " + utcExpiry + ")");

            var path = GetPathFromKey(key);

            if (File.Exists(path))
                return entry;

            using (var file = File.OpenWrite(path))
            {
                var item = new CacheItem { Expires = utcExpiry, Item = entry };
                var formatter = new BinaryFormatter();
                formatter.Serialize(file, item);
            }

            return entry;
        }
        public override object Get(string key)
        {
            Debug.WriteLine("Cache.Get(" + key + ")");
 
            var path = GetPathFromKey(key);

            if (!File.Exists(path))
                return null;

            CacheItem item = null;

            using (var file = File.OpenRead(path))
            {
                var formatter = new BinaryFormatter();
                item = (CacheItem)formatter.Deserialize(file);
            }

            if (item == null || item.Expires <= DateTime.Now.ToUniversalTime())
            {
                Remove(key);
                return null;
            }

             return item.Item;
        }
        public override void Remove(string key)
        {
            Debug.WriteLine("Cache.Remove(" + key + ")");

            var path = GetPathFromKey(key);

            if (File.Exists(path))
                File.Delete(path);
        }

        public override void Set(string key, object entry, DateTime utcExpiry)
        {
            Debug.WriteLine("Cache.Set(" + key + ", " + entry + ", " + utcExpiry + ")");

            var item = new CacheItem { Expires = utcExpiry, Item = entry };
            var path = GetPathFromKey(key);

            using (var file = File.OpenWrite(path))
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(file, item);
            }
        }
        private string GetPathFromKey(string key)
        {
            return FilecachePath + MD5(key) + ".txt";
        }

        private string MD5(string s)
        {
            var provider = new MD5CryptoServiceProvider();
            var bytes = Encoding.UTF8.GetBytes(s);
            var builder = new StringBuilder();

            bytes = provider.ComputeHash(bytes);

            foreach (var b in bytes)
                builder.Append(b.ToString("x2").ToLower());

            return builder.ToString();
        }
    }

Step 5
: Now add the class library project reference to your web application and add the following attribute to your web.config file:

  <caching>
      <outputCache defaultProvider="FileCacheProvider">
        <providers>
         <add name="FileCacheProvider" type="CustomCacheProviderLib4_5.FileCacheProvider"/>
        </providers>
      </outputCache>
    </caching>

Step 6: Now add an OutputCache Directive to your page (Default.aspx).

<%@ OutputCache VaryByParam="ID" Duration="300" %>

Step 7: Now run your web application and see that your page is loading from the Cache:



Step 8
: Here is the output window:



European ASP.NET 4.5 Hosting - Amsterdam :: Websockets with ASP.net 4.5 and Visual Studio 11

clock July 25, 2012 08:31 by author Scott

Web applications are becoming increasingly sophisticated and it is common to need to communicate with various services.

There are a number of options to accomplish this task with probably the most popular being to continually poll a server with XHR requests. Other alternatives exist that delay disconnections. These can be tricky to implement and don’t scale well (sometimes worse than polling as they keep a connection open) so aren’t used as much.


HTTP isn’t really an ideal protocol for performing frequent requests as:


- It’s not optimized for speed

- It utilizes a lot of bandwidth for every request with various headers etc sent with every request
- To keep an application up to date many requests must be sent
- Provides limited cross domain support (relying on workarounds such as JSONP http://remysharp.com/2007/10/08/what-is-jsonp/)
- Firewalls & proxys sometimes buffer streaming/long polling solutions increasing latency
- Long polling & streaming solutions are not very scalable

WebSockets are a new technology that attempts to resolve some of these limitations by:


- Sending the minimum amount of data necessary

- Making more efficient usage of bandwidth
- Providing cross domain support
- Still operating over HTTP so it can transverse firewalls and proxies
- Works with some load balancers (TCP l4)
- Provides support for binary data (note some JavaScript implementations don’t currently support this)

When would web sockets be a suitable protocol for your application?


You might want to consider using web sockets in the following scenarios:


- Games

- Real time data
- Chat applications
- News tickers

There is a nice set of demos at: http://www.html5rocks.com/en/tutorials/websockets/basics/ and an interesting article that compares a Web Sockets and polling solution in terms of latency & throughput at http://websocket.org/quantum.html.


Websockets pitfalls


Websockets is a relatively new protocol that has already undergone a number of versions as various issues are addressed. This is important as support across browsers varies.


At the time of writing Websockets (in some form) can be used by the following browsers (check caniuse.com for the most up to date info):


- IE10

- Chrome 13+
- Firefox 7
- Safari 5+
- Opera 11+

Earlier implementations of websockets had some security issues so your connections may work but are not secure (Firefox disabled support in Firefox 4 & 5 for this reason).


The other issue that you may encounter is that some older proxy servers don’t support the http upgrade system that websockets uses to connect so some clients may be unable to connect.


.net 4.5 Web Socket Support

.net 4.5 introduces a number of APIs for working with web sockets. If you find you need more control than the ASP.net API’s offers then look into WCF as that has also been updated.


Before we begin there are a couple of requirements for using ASP.net web sockets API:

-
Application must be hosted on IIS 8 (available only with some version of Windows 8 – please note currently IIS Express currently does not work)
-
Web Sockets protocol feature installed (IIS option)
-
.net 4.5
-
A compatible browser on the client (IE10 or Chrome will 18 work fine at time of writing)
-
It would help if your Chinese birth animal was the horse

Currently Microsoft have no plans to release Websockets support for earlier versions of IIS so if you plan to run it on Windows Server 2008 then you are going to have to look at other options such as http://superwebsocket.codeplex.com/.

You could also look at the SignalR library from Microsoft which is designed for developing async applications and provides WebSockets (and fallback) support: https://github.com/SignalR/SignalR/wiki/WebSockets.

Hello Web Sockets Example!

Ok I am going to assume that you are already working with some version of Windows 8 that has IIS & ASP.net 4.5 installed. The other thing we are going to need to do is make sure IIS has the Web Sockets Protocol feature installed (this is in the add/remove programs bit):

First create a new empty ASP.net project called WebSockets

Add the Nuget package Microsoft.Websockets

Pull down the latest jQuery library and put it in a scripts directory (I am using 1.7.2) – note jQuery isn’t necessary it just saves a bit of tedious event and manipulation code.

Now add a file called index.htm and enter the following code:

<!doctype html>

<head>

<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>

<script type="text/javascript">

$(document).ready(function () {

var name = prompt('what is your name?:');

var url = 'ws://' + window.location.hostname + window.location.pathname.replace('index.htm', 'ws.ashx') + '?name=' + name;

alert('Connecting to: ' + url);

ws = new WebSocket(url);

ws.onopen = function () {

$('#messages').prepend('Connected <br/>');

$('#cmdSend').click(function () {

ws.send($('#txtMessage').val());

$('#txtMessage').val('');

});

};

ws.onmessage = function (e) {

$('#chatMessages').prepend(e.data + '<br/>');

};

$('#cmdLeave').click(function () {

ws.close();

});

ws.onclose = function () {

$('#chatMessages').prepend('Closed <br/>');

};

ws.onerror = function (e) {

$('#chatMessages').prepend('Oops something went wront <br/>');

};

});

</script>

</head>

<body>

<input id="txtMessage" />

<input id="cmdSend" type="button" value="Send" />

<input id="cmdLeave" type="button" value="Leave" />

<br />

<div id="chatMessages" />

</body>

</html>

We need to create an http handler so add a new generic handler to the project called ws.ashx and enter the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using Microsoft.Web.WebSockets;

namespace WebSockets

{

public class WSHttpHandler : IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

if (context.IsWebSocketRequest)

context.AcceptWebSocketRequest(new TestWebSocketHandler());

}

public bool IsReusable

{

get

{

return false;

}

}

}

}

Finally we need to create something to handle the websocket connection (TestWebSocketHandler that is created in the AcceptWebSocketRequest method).

Create a new class called TestWebSocketHandler and enter the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading;

using System.Web;

using Microsoft.Web.WebSockets;

namespace WebSockets

{

public class TestWebSocketHandler : WebSocketHandler

{

private static WebSocketCollection clients = new WebSocketCollection();

private string name;

public override void OnOpen()

{

this.name = this.WebSocketContext.QueryString["name"];

clients.Add(this);

clients.Broadcast(name + " has connected.");

}

public override void OnMessage(string message)

{

clients.Broadcast(string.Format("{0} said: {1}", name, message));

}

public override void OnClose()

{

clients.Remove(this);

clients.Broadcast(string.Format("{0} has gone away.", name));

}

}

}


That’s all you need so now compile the project and run it in a compatible browser (IE10 or the latest Chrome will do fine) making sure you are hosting your project from IIS (project properties if you are not).


Once you have run it up you will be prompted to provide a name, then an alert box will indicate the end point of your application (ws://localhost/.. – note the secure https version is wss://).


Now open up a different browser and you should find you can via websockets!



European ASP.NET 4.5 Hosting - Amsterdam :: Request Validation with ASP.NET 4.5

clock July 16, 2012 07:16 by author Scott

Security is always the one of the greatest concerns of Applications and when it comes to web applications, they are more prone to security breach. All the web technologies provides many features that are used to write secured web applications.

Here In this post, I am going to discuss Request Validation feature, mainly focusing ASP.NET 4.5 version.


Request validation introduced since ASP.NET 1.1 is available. By default it is enabled and it prevents to accept un-encoded HTML/XML etc from Client to server. It validates all the data that is passed from client to server. It can be any form like


- Cookies

- Form Collection
- Querystring
- Server variables

This helps to avoid script injection attacks. So it is always recommended to validate all the data that is passed from client to server because it can be malicious code and can be harmful the application.


Although, if we are sure that this situation would not arise, it can be disabled at application level or page level so no request will get validated. But this is not the case every time. On some occasions, we may need to allow users to enter some html, xml etc.. data . In this case, we need to partially validate the request.


There are several scenarios where we need to turn off the request validation just because of some specific data we don’t need to get validated. It leads us to write less secure code because we are the whole request goes to unvalidated. There are scenarios like in blog sites where we normally allow the user to write html , xml etc as input


Till ASP.NET 4.0, we have option to disable the request validation in the entire application or can be done page by page. But till now we did not have option to partially validate the page. ASP.NET 4.5 enables us to validate some specific part of the request.


ASP.NET 4.5 provides us two features.


1. Selectively un-validate the request

2. Deferred or lazy validation

How to allow partially unvalidated request in asp.net 4.5

I have created a sample application and have two textboxes – txtValidate and txtunValidate, with a submit button.

Let’s have a use case that I want to validate txtValidate but not txtunValidate. You must remember that this was not possible with earlier version of ASP.NET.I’ll also discuss it in detail later. To use this feature , you must set requestValidationMode as 4.5 in web.config like

<httpruntime requestvalidationmode="4.5" />

Apart from this, ASP.NET 4.5 added one more property ValidateRequestMode with input controls. And it can have the following values


- Enabled: Request validation is enabled for the control. Bydefault it is enabled

- Disabled: Input values for this control would not be validated
- Inherit: Property value will be inherited from parent

So let’s proceed with sample, and as I don’t want to validate txtunValidate so I need to set ValidateRequestMode attribute as disabled like




Now Let’s run the code.



And as you can see I’ve put some script tag in txtunValidate and it worked fine. But let us remove the
requestValidationMode from web.config and try to submit the same input again.



and see it gave the
HttpRequestValidationException exception and got the above screen. Now lets again put the attribute requestValidationMode in web.config and try to put some script in txtValidate and submit. It’ll show you the same exception again as expected. So here you can see, ASP.NET 4.5 enables us to selectively validate the request.

Deferred or lazy validation

This is also introduced in asp.net 4.5 and I’ll say that above feature is just a corollary of this feature.


To provide these features, Microsoft has done some major changes in the way Request Validation feature got implemented in earlier version of ASP.NET. As we know, to process a request, ASP.NET creates an instance of HTTPContext which holds the instance of HTTPRequest and HTTPResponse with other required data. All the input data that is passed from client to server, it is posted in form collection, querystring etc.. ASP.NET validates every data that is passed from client to server.

Actually in ASP.NET 4.5, whenever the data is accessed from the request it gets validated. Like when we access the form collection to some input as Request.Form[uniqueId] the validation triggers. To provide selective validation, Microsoft has introduced a new collection property named as Unvalidated in the HTTPRequest class. This contains all the data that is passed from client to server like cookies, form collection, querystring etc as



Now the same data is available at two places. In
UnValidated collection and normal in HTTPRequest. When we set the ValidateRequestMode is disabled, the data is accessed from UnValidated collection else normal request. UnValidated collection don’t trigger any validation while other one triggers. I’ll show you a demo later.

In earlier version of ASP.NET 1.1/2.0/3.5, Request validation is done at earlier level of page processing. There were also some good amount of changes took place in ASP.NET 4.0, which provides us the feature to validate the non-ASP.NET resources as well which was not available earlier.


Under the hood


I have the same application and I have removed the
requestValidationMode attribute from web.config and putting some html tags as I did above example and pressed submit. So I got the HttpRequestValidationException as



Now let’s put the
requestValidationMode as 4.5 and try the same as above. I have removed the disable attribute. Again I got the same exception as below



But if we examine the circled part of the stacktrace, we can easily Identify that in 4.5, the validation exception got thrown from TextBox’s
LoadPostData method.

Please check study case below


Case Study 1

As we all know the ASP.NET Page LifeCycle as




As you can see, here
LoadPostData is a part of PageLife Cycle and comes after LoadViewState. All of the Input control’s data don’t get wiped off during postback even if viewstate is not enabled for that control.

So this is the
LoadPostData method that is responsible to get the data from Form collection and assign it to the control. As I said, Now asp.net 4.5, validates the input only when you access the data from form collection. That’s why if you look the stacktrace then it is visible that the exception is thrown from LoadPostData method only and page life cycle is the last stage of ASP.NET Request Processing.

Now lets try to have an clarification using a demo. As I mentioned, in ASP.NET 4.5, the validation triggers only when the data is accessed and the data is accessed at
LoadPostData for input controls. So lets create a custom textbox. For this I’ll override LoadPostData method and will do nothing in that. It means that the data would not be accessed for the customTextBox at LoadPostData. So even if the ValidationMode is enabled for the CustomtextBox, it wont be fired. Lets see this

I have created a
CustomtestBox and overridden the LoadPostData method as

public class CustomTextBox : System.Web.UI.WebControls.TextBox
 {
     protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
     {
          return false;
     }
 }


You can see, I have just returned false in the
LoadPostData method. Now I have used my CustomTextBox at my aspx page as



Now set the
requestValidationMode as 4.5 in web.config and enter some script tag and submit.

You would not get any error even
RequestValidation is enabled. This proves the validation fires only when data is accessed from the form collection.

Case Study 2

Here I’ll also try to prove the same as above. I have already shown above that How the new
UnValidated property of Context holds all the data including form collection, querystring, cookies etc. So whenever the data is accessed from the UnValidated collection, the validation is not fired. But when it is accessed from the normal form collection, validation gets fired.

So here I am going to use again the earlier sample. In that example I had two textboxes and a submit button. Here the change is that at server side, instead of accessing the data form txtValidate.Text, I’ll be accessing the data from FormCollection. So I’ll set the the ValidateRequestMode as disabled for both the textbox and will try to get the data one will be form normal Form Collection and another is from Unvalidated’s form collection as

protected void Button1_Click(object sender, EventArgs e)
 {
     string textValidated = this.Context.Request.Unvalidated.Form[txtValidate.UniqueID];
     string textUnValidated = this.Context.Request.Form[txtunValidate.UniqueID];
 }


Now lets enter some html tags in both the textboxes and submit the page using debugger as




Oh!! see even we have disabled the validation, even in that situation when data is accessed from normal Form collection the validation is fired.


This again proves the validation is fired only when the data is acessed and when the
ValidateRequestMode is set as disabled it is accessed from the UnValidated property



European ASP.NET 4.5 Hosting - Amsterdam :: HTML 5 Input Types in ASP.NET 4.5

clock June 22, 2012 08:26 by author Scott

Microsoft has released developer previews for Visual Studio 2011 and .Net framework 4.5. There are lots of new features available in the developer preview. One of the most interested things for web developers is the support introduced for new HTML 5 form controls.

The following are the list of new controls available in HTML 5


- email

- url
- number
- range
- Date pickers (date, month, week, time, datetime, datetime-local)
- search
- color

Describing the functionality for these controls is not in the scope of this article. If you want to know about these controls, refer the below URLs


http://msdn.microsoft.com/en-us/magazine/hh547102.aspx


http://www.w3schools.com/html5/html5_form_input_types.asp


ASP.Net 4.5 introduced more possible values to the Text Mode attribute to cater the above requirements. Let us evaluate these. I have created a project in Visual Studio 2011 developer preview, and created a page named “controls.aspx”. In the page I placed on Text box control from the toolbox




Now select the control and go to the properties pane, look at the TextMode attribute.



Now you can see more options are added here than prior versions of ASP.Net. I just selected Email as TextMode. I added one button to submit my page. The screen shot of the page in Visual Studio 2011 designer is as follows



See the corresponding markup


<form id="form1" runat="server">
    <div>
       Enter your email:
       <asp:TextBox ID="TextBox1" runat="server" TextMode="Email"></asp:TextBox
     </div>
     <asp:Button ID="Button1" runat="server" Text="Submit" />
</form>


Now let me run this page, IE 9 do not have the support for new form fields. I browsed the page using Firefox and the page appears as below.



From the source of the rendered page, I saw the below markup for my email textbox

<input name="TextBox1" type="email" id="TextBox1" />

Try to enter an invalid email and you will see the browser will ask you to enter a valid one by default.



When rendered in non-supported browsers, these fields are behaving just as normal text boxes. So make sure you are using validation controls with these fields.


See the browser support compatability matrix with these controls with various browser vendors.




ASP.Net 4.5 introduced the support for these new form controls. You can build interactive forms using the newly added controls, keeping in mind that you need to validate the data for non-supported browsers.

 

 



European ASP.NET 4.5 Hosting - Amsterdam :: Asynchronous HTTPHandlers with ASP.NET 4.5

clock June 8, 2012 08:06 by author Scott

The working of Asynchronous Handler can be shown as



As we know if we need to create a normal custom HTTPHandler. We need to implement
IHTTPHandler interface and if we want to create a custom Asynchronous HTTPHandler, we need to implement IHttpAsyncHandler.

In this post, I will be discussing, How we can write Asynchronous HTTPHandlers with the help of new features introduced in .NET 4.5 framework.


In the example, I’ll create an asynchronous HTTPHandler with the help of asp.net 4.5 that downloads rss feed.


To create Asynchronous HTTPHandler in asp.net 4.5, we need to implement the method
ProcessRequestAsync of new abstract class HttpTaskAsyncHandler that got newly introduced.

For that I created a class library named
AsyncHandlerLibrary , which has a Handler class CustomAsyncHandler which implements HttpTaskAsyncHandler.

So the class CustomAsyncHandler will be as


public class CustomAsyncHandler : HttpTaskAsyncHandler
 {

    public override async Task ProcessRequestAsync(HttpContext context)
    {
        string url = context.Request.QueryString["rssfeedURL"];
        if (string.IsNullOrWhiteSpace(url))
        {
           context.Response.Write("Rss feed URL is not provided");
        }
        WebClient webClient = new WebClient();

        //It starts downloading the rss asynchronously and the asp,net thread become free
        //and become available in threadpool
        //once the the it load the rssfeed loading completes it get assigned to another ASP.NET thread from the threadpool
        var rssfeed = await
            webClient.DownloadStringTaskAsync(url);

        // Writing the rss on the screen
        context.Response.Write(rssfeed);
    }

     public override bool IsReusable
     {
         get { return true; }
     }

     public override void ProcessRequest(HttpContext context)
     {
         throw new Exception("The ProcessRequest method has no implementation.");
     }

}

Now if you see the above code, I have implemented
ProcessRequestAsync , in which I read the rss url from query string. And asynchronously downloaded the rss feed and later wrote it in response.

Now you can see, with help of new keywords async keyword and await operator of .NET 4.5, it is extremely easy to write asynchronous code. It also got ensured that same can be used in asp.net with the introduction of new APIs.

Now build the project and add the reference in your web application. Also add this in your web.config file as

<system.webServer>
  <handlers>
     <add name="myHandler" verb="*" path="*.rss" type="AsyncHandlerLibrary.CustomAsyncHandler"/>
  </handlers>
</system.webServer>

Then run your application.
Now you can see it has never been so easy to write Asynchronous HTTPHandler. Now enjoy coding with ASP.NET 4.5.



European ASP.NET 4.5 Hosting - Amsterdam :: Creating Web Applications with HTML5 WebSockets

clock April 16, 2012 11:05 by author Scott

WebSockets enables the real-time web where the information is available to the user the moment it is published. WebSockets are standard based, Interoperable across browsers and very simple to use. We got the WebSockets support everywhere it is available on browsers, windows run time, WCF, ASP, IIS etc. This post gives you the basic idea about WebSockets and the technicalities behind this concept.

There is a deep desire for speed to get the information as quickly as possible.


Typical examples where user wants to see the information in real time


- Stock Market data

- Live Scores
- Airline Location
- Twitter Search Results
- Interactive games

The Problem

HTTP is a state less protocol where server can communicate with client only once per request received. Real time web needs asynchronous communication with client.




In the above example when you are 7 letters of text and sending to the server , it actually sending the 4kb of data to the server. We can do better and it clearly tells us the HTTP is not adequate for the real-time web.


Solution

WebSocket – is an enabler of the real-time web. Sockets are full-duplex bi-directional protocol. These Sockets are not directly available to the developers. So we need richness of Sockets and reach of Web. All together called WebSockets.


WebSockets Characteristics

- Full duplex bidirectional communication
- Supports unsecure(TCP) and secure(HTTPS) channels
- It can traverse proxies and firewalls
- It keeps the connection alive



Step1:
You start the communication with HTTP and tells the server you want to do the communication using sockets.

Step2:
The server checks and accepts the request then it starts the socket communication. At this stage both of them drop-down to start communication using sockets.

How the protocol operates?

The request from client looks like as below




It basically saying it supports websocket communication. The security key in the header is to both side to understand the sockets.


The Response from the server looks like below




WebSocket API
it is defined in W3C Primary methods and events are as below



You have the call-back method if connection is opened or if you connection is closed or message is received.


The request URI in this communication looks as below




notice it has a special scheme name
WS , ws indicates to the browser this is not something that not goes through the wire and says it is web sockets request is coming on and you need to do the HTTP hand shake down before actual communication start. ws never goes on the wire, it is HTTP that goes on the wire.

Creating a WebSocket is simple




Sending a Text message using this socket




Capturing the server response in onmessage event as below




WebSockets is an emerging standard which enables secure, real-time , bi-directional communication across the web. Microsoft supporting this in IE10, Windows 8 Apps, IIS, ASP.NET and WCF.



European ASP.NET 4.5 Hosting - Amsterdam :: WebSockets in ASP.NET 4.5

clock March 23, 2012 05:49 by author Scott

This post discuss about using WebSockets in ASP.NET 4.5. You can read this post to get an understanding about WebSockets. This post shows piece of code which uses WebSockets in ASP.NET 4.5 and the code is related to simple chat application.

The HTML of Web Form chat application looks as below




It contains a text box where you can type your text message and button where it sends a message to the server. You can notice there is <ul> element which shows the list of other messages which are arriving from the server.


Instantiate a W3C WebSocket JavaScript object and pointed to url to establish a connection to WebSockets Server.




The url starts with ws which runs on HTTP and pointing to .ashx handler which runs on ASP.NET server.


The Chat Handler code looks as below, The handler code checks whether sender is looking for WebSockets connection.






AcceptWebSocketRequest is a new method on Context object in ASP.NET 4.5.


ChatHandler is a wrapper API which implements lower level of WebSockets Handler.


The ChatHandler code looks as below




Override the OnOpen method in ChatHandler Class as below




We are modifying the OnOpen method code by adding the set WebSockets collection variable which contains the set of connection objects.






chatapp exposes a method BroadCast which accepts string or binary payload and send the message to all the objects in the collection. The payload in this piece of code is a JSON object.




Now To handle the messages that coming from the server, we are adding below piece of code in JavaScript by implementing a handler for OnMessage.


<image>


In above code we are actually parsing the JSON object that coming from server using JSON.parse method.


To send a message from client to server you can use the below code




Once this message comes to the server, you can check the type of message and can write the code as below




There is a OnClose method which you can override to close your WebSockets connection. For example when user closes the browser this method will fire and closes the connection.




When you run the application then output is as below


 

 



European ASP.NET 4.5 Hosting - Amsterdam :: WebSockets in ASP.NET 4.5

clock March 23, 2012 05:49 by author Scott

This post discuss about using WebSockets in ASP.NET 4.5. You can read this post to get an understanding about WebSockets. This post shows piece of code which uses WebSockets in ASP.NET 4.5 and the code is related to simple chat application.

The HTML of Web Form chat application looks as below




It contains a text box where you can type your text message and button where it sends a message to the server. You can notice there is <ul> element which shows the list of other messages which are arriving from the server.


Instantiate a W3C WebSocket JavaScript object and pointed to url to establish a connection to WebSockets Server.




The url starts with ws which runs on HTTP and pointing to .ashx handler which runs on ASP.NET server.


The Chat Handler code looks as below, The handler code checks whether sender is looking for WebSockets connection.






AcceptWebSocketRequest is a new method on Context object in ASP.NET 4.5.


ChatHandler is a wrapper API which implements lower level of WebSockets Handler.


The ChatHandler code looks as below




Override the OnOpen method in ChatHandler Class as below




We are modifying the OnOpen method code by adding the set WebSockets collection variable which contains the set of connection objects.






chatapp exposes a method BroadCast which accepts string or binary payload and send the message to all the objects in the collection. The payload in this piece of code is a JSON object.




Now To handle the messages that coming from the server, we are adding below piece of code in JavaScript by implementing a handler for OnMessage.


<image>


In above code we are actually parsing the JSON object that coming from server using JSON.parse method.


To send a message from client to server you can use the below code




Once this message comes to the server, you can check the type of message and can write the code as below




There is a OnClose method which you can override to close your WebSockets connection. For example when user closes the browser this method will fire and closes the connection.




When you run the application then output is as below


 

 



European ASP.NET 4.5 Hosting - Amsterdam :: What is WebSockets and Why Use WebSockets?

clock March 22, 2012 07:39 by author Scott

WebSockets are required to develop the rich and real time web applications. WebSockets can securely enable the real-time web. Before explaining the need of WebSockets we see what current Web is and it’s limitations.

What is Current Web?



We have rich web applications in current web which does the bi-directional communication. HTTP is a request-reply protocol and it is hard to PUSH on top of this protocol. Current programming model use different techniques to get connect with server, one of them is Periodic Polling.




example: Browser uses XmlHttpRequest to periodically query the server.




In Long Polling Server holds the HTTP request until there is a data to return. Client Sends the data as soon as previous request completes.


The limitations with current programming model

-
Periodic polling technique uses high-latency.
-
Long polling programming model is unintuitive.

Many scale out and Bandwidth issues with current programming model and limited cross domain support too.

What All WebSockets about is?

WebSockets is a new interoperable technology still undergoing standardization.

-
It is full duplex bidirectional socket.
-
You can program against using a browser and JavaScript API.
-
WebSockets runs over SSL
-
Designed for high performance – it is a light weight messaging protocol, it requires low bandwidth and latency.
-
Important thing is it is designed to broad reach.
-
WebSockets also has the built-in capability to make cross-domain calls.

What Applications can get benefit from WebSockets?

It supports

-
Rich web applications
-
Real-time applications and services(stock tickers and monitoring systems)
-
Beyond browser – Windows 8 and mobile
-
Online games

WebSockets are in

-
Windows 8
-
Internet Explorer 10
-
.NET 4.5

How it works?

The secret source for WebSockets protocol is HTTP handshake which enables the socket connection. When a client sends an HTTP request to WebSockets server, it contains the some information in header which tells the server to establish connection over WebSockets. If Server is happy to accepts the request and it then sends the HTTP response back to client and switches the protocol and starts the communication.

Once the handshake is complete client and server communicates over WebSockets using HTTP connection. The Message communication is in either binary or UTF8 format.

 



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