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 :: 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 Hosting - Amsterdam :: Commenting Server Controls in ASP.NET

clock July 10, 2012 07:39 by author Scott

How often do you just use an HTML comment to remove old code, or new functionality that isn’t ready yet? Are HTML comments effective for ASP.Net server controls? From a pure development context, they probably are. When we factor in security, they no longer provide the functionality that was intended. This post will explain an issue with how ASP.Net handles this situation and why it is not sufficient from a security perspective.

I am going to use a very simplistic example to make it easier to understand and to save space. Please do not let this simple example downplay the significance of this issue. In this example, I have added two label controls and a button control. I will walk through a few different scenarios to explain what is happening. Here is what the relevant part of the html page looks like:


  1: <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
  2:     <h2>
  3:         HTML Comment Test Page
  4:     </h2>
  5:     <p>
  6:         <asp:Label ID="lblUserName" runat="server" />
  7:         <asp:Label ID="lblAcctNum" runat="server" />
  8:         <asp:Button ID="cmdSubmit" runat="server" Text="Submit"
  9:             onclick="cmdSubmit_Click" />
 10:     </p>
 11: </asp:Content>

Below is the relevant code from the default.aspx.cs code behind file.  This is the code that contains the button click event that will be important throughout this post.

  1: protected void Page_Load(object sender, EventArgs e)
  2: {
  3:     lblUserName.Text = "joeUser";
  4:     lblAcctNum.Text = "933-3222222-939239";
  5: }
  6: protected void cmdSubmit_Click(object sender, EventArgs e)
  7: {
  8:     lblUserName.Text = "This shouldn't have happened.";
  9: }

When we run the page, the following output is exactly what we expect.  The labels are populated with their respected values and the button is there. 

  1: <h2>
  2:     HTML Comment Test Page
  3: </h2>
  4: <p>
  5:     <span id="MainContent_lblUserName">joeUser</span>
  6:     <span id="MainContent_lblAcctNum">933-3222222-939239</span>
  7:     <input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" id="MainContent_cmdSubmit" />
  8: </p>

I would like to call out separately the EventValidation value.  It is beyond the scope of this post to fully explain EventValidation within .Net, but the short explanation is that it is used to only allow expected events to be triggered on the server.  The value is a hash of the allowed values and events.  Here is the value for this page:

  1: /wEWAgLFs4viAgKP5u6DCOTYhw/mo3AHFQHnB8XMEMHlrATJQZUNTjLevOMdQoay

Now lets comment out the button control and a label control and see what happens.  I will comment out the account number because I realized there are some problems with it.  It is displaying sensitive information and it is vulnerable to cross-site scripting.  I want to remove the button, because it is old functionality and I don’t want anyone to be able to perform that action going forward.  Here is what the new HTML data looks like:

  1: <h2>
  2:     HTML Comment Test Page
  3: </h2>
  4: <p>
  5:     <asp:Label ID="lblUserName" runat="server" />
  6:
  7:     <!--<asp:Label ID="lblAcctNum" runat="server" />-->
  8:     <!--<asp:Button ID="cmdSubmit" runat="server" Text="Submit"
  9:         onclick="cmdSubmit_Click" />-->
 10: </p>

It is important to note that I did not make any changes to the code behind file, because it was a) easier to update the html document and b) it doesn’t require me to change compiled code.  Although neither of these are good reasons, they are just used for the example.

Here is what the new HTML output looks like:


  1: <h2>
  2:      HTML Comment Test Page
  3: </h2>
  4: <p>
  5:      <span id="MainContent_lblUserName">joeUser</span>
  6:
  7:      <!--<span id="MainContent_lblAcctNum">933-3222222-939239</span>-->
  8:      <!--<input type="submit" name="ctl00$MainContent$cmdSubmit" value="Submit" id="MainContent_cmdSubmit" />-->
  9: </p>

The good news is that the elements are commented out, as we expected, but do you see a problem?  On line 7, the account number is still being populated and on line 8 the button was processed as well to a proper HTML button, rather than the asp:control that we commented out.  I would have expected that the controls would not have been processed because they were commented out. 

The .Net framework does not detect that the ASP.Net server controls are within HTML comments and still processes them as if they were not commented out.  Now, that sensitive data I was trying to remove, is just not displayed on the page, but still available in the source of the page.  All a user would have to do is View Source to see it. 

Remember I also mentioned I wanted to remove this label because it was vulnerable to cross-site scripting.  Well, unfortunately, it still is.  Just because it lives inside of HTML comments doesn’t mean if the proper values are sent down it is still protected.  It is possible for an attacker to submit data that will break out of the comment and then add their own execution steps.

Also, notice that the button looks valid.  What would happen if the end user decided to remove the comments around the button?  In this case, the button would still fire as it did in the first example.  There are other ways to trigger this button, but re-enabling it with a proxy or browser add-in is the easiest.  Lets take another look at our EventValidation value:

  1: /wEWAgLFs4viAgKP5u6DCOTYhw/mo3AHFQHnB8XMEMHlrATJQZUNTjLevOMdQoay

This value is the same as the last time we checked it before commenting out the button control.
  Since it is the same, we know that the same events are available to us and the button will be accepted.  This could cause a problem if the code is not ready for prime time, or has been removed due to issues of some sort.

A better way to resolve this issue is to set the Visible property for each of the server controls you no longer want to exist on the page, or just remove them if you are using source control.
  By setting the visible property to “False”, the .Net framework will not process that control and send it to the browser.  This also effects the EventValidation.  Lets look and see what happens when we set the Visible property in the HTML.

  1: <h2>
  2:     HTML Comment Test Page
  3: </h2>
  4: <p>
  5:     <asp:Label ID="lblUserName" runat="server" />
  6:
  7:     <asp:Label ID="lblAcctNum" Visible="false" runat="server" />
  8:     <asp:Button ID="cmdSubmit" runat="server" Visible="false" Text="Submit"
  9:         onclick="cmdSubmit_Click" />
 10: </p>

Here is the output:


  1: <p>
  2:     <span id="MainContent_lblUserName">joeUser</span>
  3:
  4:    
  5:    
  6: </p>

Notice how the button and label are no longer being output to the browser at all.
  This is much better and more secure.  Lets check the EventValidation value just to make sure it has changed. Oh, wait, because there are no other events on this page, EventValidation not longer exists.  That means that no events would be accepted by our page.  If other events existed, or if a listbox existed, then our value would have been different.  If we tried to then submit the button click event, an ASP.Net error would have been raised. 

As you can see, there are some issues when just using HTML comments for your server controls.
  ASP.Net has an issue, maybe a bug, that doesn’t detect this behavior and processes the controls as if they were allowed.  Remember, it is easy to re-enable a commented out control, so make sure you avoid that situation.  Just because a controls is commented, doesn’t mean it will represent a security risk, but any instance of this should be examined for potential security problems.




 



European Visual Studio 2012 Hosting - Amsterdam :: New Features in Visual Studio 2012

clock July 4, 2012 08:14 by author Scott

For Microsoft, 2012 is the Year of New Releases. Major releases of Windows 8, Windows Server 2012, System Center 2012, and SQL Server are all due. Not to be left out, Visual Studio (VS) 2012 will also be released this year, and Microsoft recently made the Visual Studio 2012 Release Candidate (RC) available. You can download it from the Visual Studio 2012 RC downloads page. Here are some of the most important new features in this VS 2012 release.

Revamped UI


The UI is probably the first thing you’ll notice about VS 2012 RC. The monochrome scheme in earlier versions of VS 2012 was met with a bitter backlash as developers took an instant dislike to it. In fairness, the idea was to deemphasize the UI and make the code stand out more. However, that was a bad idea. VS 2012 RC reintroduces color, and once again you can tell the difference between the icons on the toolbars. That said, personally, I prefer the VS 2010 UI and colors (except for the cool game-like installer in VS 2012 RC).


Ability to Build Metro-style Applications

Without a doubt this is the most important new feature in VS 2012. VS 2012 lets you build Metro apps using HTML, JavaScript or XAML and VB, C# or C++, and it includes a new set of Metro-style app templates. It also supports building Windows Phone applications.


Microsoft.NET Framework 4.5

While it’s not technically a part of VS 2012, every new release of Visual Studio is accompanied by a new release of the .NET Framework. In this case, it's the new .NET Framework 4.5. Its big changes include improved support for parallelism and IPv6, support for zip compression, HTML 5, WebSockets, and WPF Ribbon bar support. ASP.NET Web Forms has been updated to support the asynchronous modules and handles, lots more.

LightSwitch

In earlier releases of Visual Studio, LightSwitch was a separately purchased product. The VS 2012 release includes LightSwitch in the VS 2012 Professional editions and above. I always said LightSwitch was a developer tool and not a user tool, and it seems that Microsoft now agrees. The VS 2012 LightSwitch has a new theme, support for branding, and improved performance.

IIS Express


Visual Studio used to use its own ASP.NET Development Server as the default web server for locally running and testing web applications. However, that meant you often ran into a variety of differences and incompatibilities when you went to deploy your applications on IIS. VS 2012 solves this problem by using IIS Express as the default local web server. IIS Express is a lightweight, self-contained version of IIS. It has all of the core capabilities of the full-fledged IIS, but it doesn't run as a service.

Support for WinRT

In conjunction with the new support for Windows 8 and Metro, VS 2012 also includes support for the new WinRT subsystem. WinRT (Windows RunTime) is the new programming model used by Metro. VS 2012 supports WinRT development in C++, C#, VB, and JavaScript. Programs written using WinRT should run on both Intel and ARM processors.

New Solution Explorer

As you begin to use VS 2012, you’ll definitely notice the new Solution Explorer. It's like a cross between the old Object Browser and Class View. You can navigate your project’s objects and drill down into methods and properties. It also enables you to search and preview file, objects and external items.

New SQL Server Object Explorer

Visual Studio has always been weak in the area of SQL Server navigation. VS 2012 improves its SQL Server integration with the new SQL Server Object Explorer, which is more like SQL Server Management Studio than the old Server Explorer. The new SQL Server Object Explorer shows column data types as well as primary and foreign keys.

Visual Studio 2012 Hosting with HostForLIFE.eu with only 2.45 euros/month.



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