.Net Framework 4.5 Features
.Net Framework 4.5 came up with lots of great features. Writing about all of them will not be possible but I would like to add light on some features especially with regards to Asp.Net.
Now I am just wondering from where should I start and how should I start?
I think I should start talking about target audience. Let me be clear that this article is not intended for those who want to learn Asp.Net Web Forms or Asp.Net MVC. In order to understand this article you should have basic knowledge of web development and some features introduced in prior versions of .Net framework, especially Asp.Net features. |
What we will learn then?
We will not cover each and every Asp.Net feature introduced with 4.5. Rather we will talk about some features which I personally felt good and thought I should share. If you think that there is something else which has to be covered, you have comment box and I will try to get it to you.
Agenda
- Understand Asynchronous HTTP Modules and Handlers.
- WebSocket protocol support in Asp.Net 4.5
- New Request Validation features
- What’s next and conclusion?
Enough talking, let’s get back to work.
Understand Asynchronous HTTP Modules and Handlers.
HTTP modules and HTTP handlers are two words we commonly hear from every Asp.Net developer. Many times we want to implement pre-processing logic before any web resource like image, text or aspx is requested. For example – We want to add a security check before actual page/resource processing starts.
HTTP modules emits lots of events in the Asp.Net request pipeline where we can write our own logic so it is termed as event based methodology. Each and every request passes through HTTP modules.
HTTP handlers on the other hand won’t get executed for every request, it depends on the extension of resource we are requesting so it is termed as extension based methodology. Let’s say end user make a request to image with .jpg extension but we internally retrieves the image from database and send it as a response. HTTP handler fits here best.
If you are more curious about these two concepts and want to learn in-depth click here.
Request Processing is Asp.Net
Now IIS web server maintains a pool of threads and whenever a new requests comes in it just takes one thread from that pool and allocates it for request processing. As long as threads are available in the thread pool, Asp.Net will be able to serve all requests. But once all threads got busy processing the request and no free threads remain in thread pool, new request has to wait for thread to become free. Obviously there is a waiting time and after that server will throw “HTTP 503 server busy” or “Server Unavailable” error.
Increasing the thread pool size doesn't really solve the problem.
Lack of threads is not the real problem, real problem is existing threads are not getting used efficiently.
Many times our request processing thread will be waiting for our I/O to complete instead of executing code, which I call as inefficient use of thread. We should release the thread as soon as I/O operation starts and obtain a new thread as soon as it completes.
Synchronous HTTP modules
Let’s talk about a scenario where we want to write a complex long running task in HTTP module.
Task may include
|
For demo purpose let’s say we want to log details of all requests into database.
Now if we execute modules in a synchronous manner it will degrade site performance a lot because it will keep request processing thread (which was allocated in the beginning) busy throughout database processing.
Asynchronous HTTP modules
Now Asp.Net has a support for creating asynchronous HTTP modules. In this case we will release the thread as soon as I/O or any other operation starts which won’t require CPU.
In order to do that we will use asynchronous methods in HTTP modules instead of synchronous methods. In example we are using AddOnPostAuthorizeRequestAsync method which is asynchronous version of synchronous event PostAcquireRequestState.
Then what is new in Asp.Net 4.5?
Although previous versions of Asp.Net allowed the creation of asynchronous HTTP modules, with the introduction of Task in 4.0 and async/await keywords in 4.5, it has become much simpler.
In Asp.Net 4.5 we have a class called EventHandlerTaskAsyncHelper and a delegate type called TaskEventHandler using which we can integrate Task-based asynchronous methods with the older asynchronous programming model exposed by the Asp.Net HTTP Pipeline. Let’s have a quick look at the refactored version of above code snippet.
Synchronous HTTP handlers
Let’s discuss about the image processing scenario we discussed above (while explaining HTTP handlers). Now if we create a synchronous HTTP handler for the same, it will just block the request processing thread for a long time. We should release the thread to thread pool as soon as we start retrieving image from database(so that it can serve some other request) and should allocate a new thread when retrieving completes.
Asynchronous HTTP handlers
Ultimate solution will be Asynchronous HTTP handlers.
Normally in order to create HTTP handler we use IHttpHandler but in order to create Asynchronous HTTP handler we will use IHttpAsyncHandler.
Hide Copy Code
public class MyAsyncHandelerOldWay: IHttpAsyncHandler { public MyAsyncHandelerOldWay() { } public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallbackcb, object extraData) { //...... } public void EndProcessRequest(IAsyncResult result) { //...... } public bool IsReusable { //...... } public void ProcessRequest(HttpContext context) { //...... } }
Then what is new in Asp.Net 4.5?
Same problem. It’s too complex to implement. But .Net 4.5 made it easy to implement with async/await keyword and a class called HttptaskAsyncHandler.
Hide Copy Code
publicclassMyAsyncHandeler:HttpTaskAsyncHandler { public MyAsyncHandeler() { } public override async Task ProcessRequestAsync(HttpContext context) { SqlCommand cmd = newSqlCommand(); Object Image= await cmd.ExecuteScalarAsync(); context.Response.BinaryWrite((byte[])Image); context.Response.End(); } }
WebSocket support in Asp.Net 4.5
HTML 5 WebSocket is a known features to everyone by now. It brings sockets to the web.
Clients connect to a server and sends an HTTP request (prefixed by “ws://” or “wss://”) with special headers, then web server response back HTTP 101 with special response headers. This is how handshaking works in case of WebSockets. This will establish a secure, real time communication between client and server over HTTP.
Now it’s not required to use techniques like long pooling or periodic pooling to simulate the socket behavior in web, now it’s possible without much effort because of WebSockets.
What’s new in Asp.Net 4.5?
Now in order to work with WebSockets we need
1. Client side JavaScript APIs which we can use,
- For initiating connection
- For sending messages to server
- For receiving messages from Server.
2. Server side .Net APIs for creating and hosting WebSocket server.
Client Side APIs
Now for client side scripting we have APIs provided by HTML 5.
Code 1 – Initiating connection:
Hide Copy Code
window.onload = function () { //Url of WebSocket Server var url = "ws://localhost:9495/ChatServer.ashx?Name=Sukesh"; var ws = new WebSocket (url); }
Code 2- Sending Messages
Hide Copy Code
$('#BtnSend').click ( function () { ws.send($('#TxtMessage').val()); $('#TxtMessage').val(''); } );
Code 3 – Receiving Messages
Hide Copy Code
ws.onmessage = function (e) { $('#ResponseDiv').append("<br>" + e.data.toString()); }
Note: $ in above code is from jQuery. For Dom manipulation we are using jQuery.
Server side APIs
Asp.Net 4.5 provides APIs using which developers can easily (word easy is very important here) write code which will :- Accept client’s WebSocket request and upgrades HTTP Get request to WebSocket request.
Code for accepting WebSocket request:Hide Copy CodeHttpContext.Current.AcceptWebSocketRequest (// WebSocket delegate goes here)
Note: In case of web forms this code will be written in either HTTP Module or in HTTP Handler and in case of MVC we will use Web APIs.
Code for WebSocket delegate:Hide Copy Codeprivate async Task MyProcessTask(AspNetWebSocketContext context) { //Code goes here }
- Read string or binary data from WebSocket object synchronously or asynchronously. Code for creating WebSocket object:Hide Copy Code
WebSocket socket = context.WebSocket; //context -> parameter of MyProcessTask
Code for receive messageHide Copy CodeArraySegment<byte> buffer = newArraySegment<byte>(newbyte[1024]); //receive data from Client WebSocketReceiveResult result = await socket.ReceiveAsync( buffer, CancellationToken.None); </byte></byte>
Code for send messageHide Copy Code//Send data to client await socket.SendAsync( buffer, WebSocketMessageType.Text, true, CancellationToken.None);
Code example shows that WebSockets requests runs completely asynchronously inside.
Application was waiting for client message asynchronously and for that we are using await socket.ReceiveAsync.
Similarly, asynchronous messages are sent to a client by calling await socket.SendAsync.
New Request Validation features in Asp.Net 4.5
Request validation is one of the important feature in Asp.Net. It examines the incoming requests and determines whether it contains potential dangerous content.
What is meant by dangerous content?
Any HTML or JavaScript code which is added for malicious purpose.What is meant by request content here?
It means posted values, query string, cookies and header of the request.Why Request validation is required?
It avoids XSS (Cross-site-scripting). Let’s say we have a textbox and button in page. When someone click the button, value in the textbox will be displayed in the page itself. Now let’s say if someone puts some kind of JavaScript code with script tag in textbox and when we try to write textbox content into the page, browser will execute the JavaScript code.What happens if request validation fails?
Asp.Net will throw an error “potentially dangerous value was detected" error and stops page processing.
It’s going to be a big problem if we want our application to accept HTML content. Example for application which will accept HTML content are Forum sites.
Solution – Disable request validation
- Either at Page level as
Hide Copy Code
<%@PagevalidateRequest="false"%>
- Or at application level as
Hide Copy Code
<configuration> <system.web> <pagesvalidateRequest="false" /> </system.web> </configuration>
Is this good?
Obviously no!!!Because we have to validate each and every control in page so that XSS will not affect. Project requirement says only some controls are going to accept HTML content hence there is no sense in disabling request validation for all the controls in page (or application).
What Asp.Net 4.5 has in its pocket?
It provides 2 new features
- Deferred request validation
- Introduction of ValidateRequestMode property
In order to understand these two features lets create a simple form as follows
In order to solve this issue we will navigate to web.config and will change requestValidationMode to 4.5 (new in Asp.Net 4.5)
Hide Copy Code
<system.web> <compilationdebug="true"targetFramework="4.5"/> <httpRuntimetargetFramework="4.5"requestValidationMode="4.5"/> </system.web>
It will just vanish the error. Now it’s time to consume the values in code behind for further processing. So let’s write some code in button click handler.
It seems like error is still there. Only difference is now it is coming when we try to access the value.The call to Request.Form["forum_post"] still triggers request validation for that specific request value.
This is what we call deferred request validation.
But how to access those values?
For that we will use Request.Unvalidated.Form
Example:
Hide Copy Code
stringHtmlContent = Request.Unvalidated.Form["TxtHtmlContents"];
What if I want to useServer side controls?
This question only applies for Asp.Net Web Forms. In above example we are using input textboxes (html controls). Now let’s try the same example with Server side textboxes.
Hide Copy Code
<div> (Html Contents): <br/>Server Textbox <asp:TextBoxrunat="server"ID="TxtHtmlContents"/><br/> (Normal Contents): <br/>Server Textbox <asp:TextBoxrunat="server"ID="TxtNormalContents"/><br/> <asp:ButtonID="Button1"Text="Submit"runat="server"OnClick="Button1_Click"name="Address"/> </div>
We will see a strange behavior when we execute the code. Put some HTML content in textbox and click on button. We will get the same “Potential Error”. Setting requestValidationModeto 4.5 just delegates request validation from one time to other time (time when we try to retrieve values). When we closely look into the Asp.Net life cycle events,we will find that just before the Page_Load event an event called LoadPostBackData gets fired, which will get all the values from posted data and load them into corresponding textboxes. It means, behind the scene Asp.Net is trying to access the values from posted form data which is causing error.
What is the solution?
Now the good news is,Asp.Net 4.5 added a new property to every server control called ValidateRequestMode. Set it to “disabled”. Using this property we can disable request validation for individual controls.
Some small important features introduced in 4.5
There are some very small but useful features which I want to address.
Automatic Html encoding with <%: %>
Unobtrusive validation –
which will significantly reduce the amount of JavaScript rendered inline in the page markup and thus reduces the overall page size.New features with regards to HTML 5
- TextMode property of Textbox supports more values now like email, datetime
- Many html 5 controls supports runat=”server” attribute in order to support “~” sign while specifying URL.
- File upload control supports multi file upload
What is Next and Conclusion?
In this article we tried to understand 3 new features in Asp.Net 4.5 and I hope you enjoyed it. We started our journey with Asynchronous HTTP modules and Handlers, then we had demo on web sockets and ended up with new request validation features.
In the further coming series we will talk about Improvements made on Asp.Net MVC
- Asp.Net Web API
- Asynchronous controllers
- Display Mode support
Thanks for reading. Your feedbacks, comments and ratings not only motivates us but also improves us.
Keep coding and keep sharing.
For technical trainings on various topics like WCF, MVC, Business Intelligence, Design Patterns, WPF and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com
Click and go here to get more on ASP.NET /.NET and C# learning stuffs
Do once go through this article which talks about 5 important .NET 4.5 new features.