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.



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 Hosting - Amsterdam :: Improving the C# Debugging Experience - DebuggerDisplay

clock May 28, 2012 09:25 by author Scott

In an effort to start blogging more about the "helpful" items that I have encountered over the years this is one of my first "Quick Tips" related to improving the life of the developer. We all have had those times where we are tracking down a complex problem within an application and all along the way we have to spend endless time mousing over individual classes to find out what their values are when most commonly we just want to know about one or two key values. Well in this post, I'll show you a neat trick using the "DebuggerDisplay" attribute to help make this process easier.

The Code


To get us started I'm going to just dive into the code, consider the following super condensed code sample.


   1:  static void Main(string[] args)
   2:  {
   3:      var badSampleInstance = new BadSample()
   4:                              { Name = "John Smith",
   5:                                  Address = "123 Main Street",
   6:                                  Phone = "515-555-1212" };
   7:      var goodSampleInstance = new GoodSample()
   8:                              { Name = "John Smith",
   9:                                  Address = "123 Main Street",
  10:                                  Phone = "515-555-1212" };
  11:      Console.ReadLine();
  12:  }
  13:   
  14:  public class BadSample
  15:  {
  16:      public string Name { get; set; }
  17:      public string Address { get; set; }
  18:      public string Phone { get; set; }
  19:  }
  20:   
  21:  [DebuggerDisplay("{Name} ({Phone})")]
  22:  public class GoodSample
  23:  {
  24:      public string Name { get; set; }
  25:      public string Address { get; set; }
  26:      public string Phone { get; set; }
  27:  }

From here we can see a very simple set of code with two classes. If you notice I have added an attribute "DebuggerDisplay" to the top of the GoodSample class. The value used for the display contains a few substitutions "{Name}" and "{Phone}". What this does is update all of the display areas in the debugger, that would typically show the type name for the value which isn't helpful to show the formatted value we supplied. An example of this can be seen here.




So as you can see this can help to get a good glance into your custom objects, and reduce a lot of the "mouseover" action that is common while debugging.


I hope that this content was helpful.



European ASP.NET Hosting - Amsterdam :: Read E Mails from ASP.NET

clock May 21, 2012 08:20 by author Scott

This article Illustrate How to read mails from ASP.Net. Using POP commands you can access you email inbox from ASP.Net. Basic POP commands are USER, PASS, LIST, QUIT, RETR.
More details POP command help you can check these links

//Creating Object for POPHelper
//Parameters are Gmail,Yahoo or MSN Pop Server,
//Port number
//bool isSSL
POPHelper objPopHelper = new POPHelper("pop.gmail.com", 995, true);
objPopHelper.UserName = "Your Gmail Username eg:[email protected]";
objPopHelper.Password = "GmailPassword";
objPopHelper.Connect();
GridView1.DataSource = p.DataSource;
GridView1.DataBind();



Code Of Connect Method

public void Connect()
        {
            string response = string.Empty;
            ArrayList arrList = new ArrayList();
            try
            {
                //Connect to Host server
                #region Connect Host
                TcpClient _tcpClient = new TcpClient();
                try
                {
                    _tcpClient.Connect(_hostname, _port);
                    //if login is ssl
                    if (_isSsl)
                    {
                        _stream = new SslStream(_tcpClient.GetStream());
                        ((SslStream)_stream).AuthenticateAsClient(_hostname);
                    }
                    else
                    {
                        _stream = _tcpClient.GetStream();
                    }
                }
                catch (Exception ex)
                {
                    throw new POPCommandException("Connection to " + _hostname + " Port: " + _port + " failed. Error Details"+ex.Message);
                }
                #endregion
                // Send POP Commands (USER, PASS, LIST) to Host
                #region POP Commands
                _streamWriter = new StreamWriter(_stream, Encoding.ASCII);
                _streamReader = new StreamReader(_stream, Encoding.ASCII);

                //POP command for send Username
                _streamWriter.WriteLine(POPCommands.USER.ToString()+" "+ UserName);
                //send to server
                _streamWriter.Flush();

                //POP command for send  Password
                _streamWriter.WriteLine(POPCommands.PASS.ToString() + " " + Password);
                //send to server
                _streamWriter.Flush();

                //POP command for List mails
                _streamWriter.WriteLine(POPCommands.LIST.ToString());
                //send to server
                _streamWriter.Flush();
                #endregion
                //Read Response Stream from Host
                #region Read Response Srteam
                //Read Response Stream
                response = null;
                string resText = string.Empty;
                while ((resText = _streamReader.ReadLine()) != null)
                {
                    if (resText == ".")
                    { break; }
                    if (resText.IndexOf("-ERR") != -1)
                    { break; }
                    response += resText;
                    arrList.Add(resText);
                }
                #endregion
                //Binding Properties
                #region Bindings
                //Bind Message count
                BindMailCount(arrList);
                //mails returns List
                _mail = ReadMail(messagecount);
                //get  mails Subjects returns List
                _mailsub = FilterContent(_mail,FiltersOption.Subject);
                _from = FilterContent(_mail, FiltersOption.From);
                _to = FilterContent(_mail, FiltersOption.To);
                SetDataSource(_mailsub, _from);
                #endregion
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
        }


Class Diagram of POPHelper




Reading Mails Using POP Command RETR from ASP.NET

private List ReadMail(int Count)

        {
            List lst = new List();
            try
            {
                for (int i = 1; i <= Count; i++)
                {
                    _streamWriter.WriteLine(POPCommands.RETR+" " + i.ToString());
                    _streamWriter.Flush();
                    string resText = string.Empty;
                    while ((resText = _streamReader.ReadLine()) != null)
                    {
                        if (resText == ".")
                        { break; }
                        if (resText.IndexOf("-ERR") != -1)
                        { break; }
                        lst.Add(resText);
                    }
                }               

            }
            catch(Exception ex)
            {
                errors.Add(ex.Message);
            }
            return lst;
        }

Enumerates for Filer message subject and From Address and ToAddress



Method for Filer Content

private List FilterContent(List Mails,FiltersOption filter)

        {
            List filterItems = new List();
            try
            {
                for (int i = 0; i < Mails.Count; i++)
                {
                    if (Mails[i].StartsWith(filter.ToString() + ":"))
                    {
                        string sub = Mails[i].Replace(filter.ToString() + ":", "");
                        filterItems.Add(sub);
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
            }
            return filterItems;
        }

Creating DataSource for GridView

private DataTable SetDataSource(Listsubject,Listsender)
        {
            int messageCount = messagecount;
            dataTab = new DataTable();
            DataRow drow;
            DataColumn Sender = new DataColumn("Sender", typeof(string));
            DataColumn Subject = new DataColumn("Subject", typeof(string));
            dataTab.Columns.Add(Sender);
            dataTab.Columns.Add(Subject);
            for (int i = 0; i < subject.Count; i++)
            {
                drow = dataTab.NewRow();
                dataTab.Rows.Add(drow);
                dataTab.Rows[i][Sender] = sender[i].ToString();
                dataTab.Rows[i][Subject] = subject[i].ToString();
            }
            return dataTab;
        }



European ASP.NET Hosting - Amsterdam :: Read or Write connection strings in web.config file using asp.net

clock May 4, 2012 08:40 by author Scott

In this article I will explain how to read or write connection strings in web.config file using asp.net.

I have one web application that contains many pages and each page contains relationship with database connection to get data from database and display it on page because of that I need to write database connections for each page to interact with database. Now the server name or credentials of database server has changed in that situation it will create problem because we need to modify the database connections of each page using asp.net.


To avoid this situation it would be better if we place connection string in one place and reuse it in every page wherever we need to connect to SQL Server. Web.config is the best place to store the connection strings in asp.net and it would be safer place to store the connection strings instead of writing connection strings in every web page.


Now we want to add connection string in web.config file for that first create new website using visual studio after that create new website open web.config file and search for “connectionStrings” and add new item in connectionStrings section


After open
web.config file in application and add sample db connection in connectionStrings section like this

<
connectionStrings>
<
add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; "
providerName="System.Data.SqlClient"/>

</
connectionStrings >

Example of declaring connectionStrings in web.config file like this


<
connectionStrings>
<
add name="dbconnection" connectionString="Data Source=Scott;Integrated Security=true;Initial Catalog=MySampleDB" providerName="System.Data.SqlClient"/>
</
connectionStrings >

Here to access my database server there is no need of username and password for that reason I didn’t enter username and password in connection string.


After add dbconnection in connectionString we need to write the some code in our codebehind file to get connection string from web.config file for that add following namespace in codebehind file and write the following code


using
System.Configuration;

This namespace is used to get configuration section details from web.config file.

After add namespaces write the following code in code behind

C# code

using System;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Get connection string from web.config file
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
//create new sqlconnection and connection to database by using connection string from web.config file
SqlConnection con = new SqlConnection(strcon);
con.Open();
}
}

VB.NET

Imports
System.Data.SqlClient
Imports System.Configuration
Partial Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Get connection string from web.config file
Dim strcon As String =
ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString
'create new sqlconnection and connection to database by using connection string from web.config file
Dim con As New SqlConnection(strcon)
con.Open()
End Sub
End Class

OK, finish.



European ASP.NET 4 Hosting - Amsterdam :: How to Solve Error - ASP.NET 4.0 has not been registered on the Web server

clock April 25, 2012 08:07 by author Scott



The above error message indicate that you haven’t configured your ASP.NET 4 on your IIS. To configure IIS7.0 to use ASP.NET 4, please follow this steps:


- Open command prompt under Administrative privileges.

- Navigate to this location C:\Windows\Microsoft.NET\Framework\v4.0.30319.
- Locate aspnet_regiis.exe file.
- Run the utility with –i switch to register ASP.NET 4.0 with IIS7



And you can see it will work now.



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