Boost Performance by Using a CDN in Your ASP.NET Site

A CDN (Content Delivery Network) is simply a network of data centers spread across the globe which serve static content to a user from the nearest available data center. Thus a request for a static file by a user in Australia
would be served from a nearby AsiaPac data center instead of the US (where the main site may to served from). This reduces the latency and therefore boosts performance.

A secondary factor boosting performance is that typically browsers can only open up 2 simultaneous connects to a host, therefore if your web page will require 20 file requests and all static files are on the same server the requests are
queued two at a time. If a CDN is used, the browser can open up more simultaneous file requests and so boost performance.

Which CDN ?

There are numerous CDNs to choose from, personally I use the Rackspace CloudFiles. Rackspace recently partnered with Akamai and so the CDN network is top notch – although the tools are quite weak. It is not possible to FTP a file
to a CDN but the FireUploader utility for Firefox is satisfactory (note that this had some issues with Firefox 4.0 when I tested it and as such I am still using it with Firefox 3.6).

I won’t list all available CDN options as I have not tried that many, but I also had a good experience with MaxCDN, although their pricing structure is quite unusual and so you should carefully examine this to guage your costs.

One thing to note, Amazon’s S3 storage solution is NOT a CDN. All files served from S3 are served from a single location and not from an array of data centers.  Amazon does have a CDN offering – CloudFront, however I would not recommend this as it did not perform well in any of my testing. The Azure CDN offering had a similar performance to the CloudFront product in my experience and so I wouldn’t recommend it.

How to Use a CDN

Using a CDN is very simple, just upload your static files to the CDN and then set the src attribute of the element (such as an <img> tag).

When a file is requested for the first time it will first be served from the central data center and then cached at the edge location (ie worldwide data center nearest to the requesting user). All subsequent requests will be served from the cache of the edge location until the TTL (Time To Live) value has expired. This can be a gotcha if you are updating the files. This typically happens a lot with css files. Therefore if you update your site’s css file, then upload it to your CDN, site users around the worldwide may be served a cached version of the old file. To get around this you can specify version numbers for your css files, in this way each file is unique and when you push an update the CDN will request the new css file from the central store before caching it.
By way of example if you look at the source for this SharePoint article you will see that most of the static files are served from a CDN.

Free SQL Server Backup Script

The SQL Server backup function accessible from SQL Server Management Studio is convenient but crude, the powerful script allows for backing up multiple databases and setting many other parameters such as compression, verification etc. [DatabaseScripts.com].

Sending Mail from a .NET App Using Amazon SES (Simple Email Service)

Amazon’s Simple Email Service (SES) is a great solution for any project which requires bulk emails. the primary advantage of SES is cost, at $0.10 per 1000 emails sent it is between 5-10x cheaper than other alternatives such as SendGrid. There is a downside to the SES service, however and it is that it currently doesn’t provide an SMTP wrapper so whilst SendGrid and others allow you to simple change your SMTP settings, with SES you will have to do a bit more work.

Amazon (AWS) provides a very useful .NET SDK (complete with dll’s for .NET 2.0, 3.5 and 4.0) which you can simply copy into your project and start calling the Amazon functions from a .NET app such as an ASP.NET site. You can download the SDK here.

The below code shows a simple example of how to use the Amazon AWS SDK in .NET to send emails.

Dim listColl As New System.Collections.Generic.List(Of String)
'//TODO - Write a simple loop to add the recipents email addresses to the listColl object.

Dim client As New Amazon.SimpleEmail.AmazonSimpleEmailServiceClient("aws_public_key_here", "aws_private_key_here")

Dim mailObj As New SendEmailRequest
Dim destinationObj As New Destination(listColl)
mailObj.Source = "from@youremail.com"  '//The from email address
mailObj.ReturnPath = "bounce@youremail.com" '//The email address for bounces
mailObj.Destination = destinationObj

'//Create Message
Dim emailSubjectObj As New Amazon.SimpleEmail.Model.Content("This is the Subject")
Dim emailBodyContentObj As New Amazon.SimpleEmail.Model.Content("This is the Body<br /><em>In Html</em>")

Dim emailBodyObj As New Amazon.SimpleEmail.Model.Body()
emailBodyObj.Html = emailBodyContentObj
Dim emailMessageObj As New Message(emailSubjectObj, emailBodyObj)
mailObj.Message = emailMessageObj

Dim response = client.SendEmail(mailObj)

That’s it, there’s really not a lot of heavy lifting to get starting using SES with .NET. the only thing I didn’t show in the code above is the loop for adding email addresses as strings to the generic collection, this loop will vary a lot depending on your exact requirements.
One thing to note above is that you will need to import the namespace Amazon.SimpleEmail.Model

AWS SES is not as full featured as a lot of solutions such as SendGrid, however it does have several useful features out-of-the-box such as the ability to perform email validation:

Dim testEmail As String = "anemail@domain.com"

Dim verRequest As New VerifyEmailAddressRequest()
verRequest.EmailAddress = testEmail
client.VerifyEmailAddress(verRequest)

This should get you going with SES, I will update this page once the service develops.

Using Sequence in SQL Server 2011 (an Alternative to Identity)

Using the Identity attribute for a column in SQL Server is a very convenient way to auto-increment a field in a row and generate unique ID’s for use as a primary key. SQL Server 2011 introduces Sequence, which is similar in many respects but is offers greater performance and flexibility – read our full tutorial on Using Sequence in SQL Server 2011.

Protect Your ASP.NET App From SQL Parameter Injection

Securing your ASP.NET web app from SQL Injection attacks paramount in the design of any ASP.NET app. Say you are viewing a transaction of customer #448, andyour URL looks something like www.myapplication.com/customer.aspx?customerID=448. What is to stop customer 448 from typing in 449,  and viewing another customer’s transaction details? The situation can even escalate into typing in complete SQL statements and executing them inside the original statements you have coded.  Checking for let’s say a customer sessionID and matching it against the URL and the page will still have to be done by the app developer. This article will demonstrates a simple method of protecting against SQL Injection attacks by checking  for valid parameters in an existing ASP.NET application which can be used in any website. The main idea behind this technique is very simple and includes three components.

The Validation Class
This class contains static methods to check for valid values. For example, if you are expecting a string that is twenty characters long,it can check it for you and notify the application every time itencounters an invalid string on any page. There are several methods implemented in the example code. However, you can add your own and customize them to your needs.

Web.config
This is the file where you keep all of your application keys. So for example, if we would like to check for a customerID and make sure it is an integer, we would add a key named <safeParameters> and set its value to orderID-int32. Now every time our application will encounter an orderID parameter it will automatically check to see if it has a valid integer value.

Global.asax
This file will contain a utility method to match all of our known parameter types to their value. This method will be called isValidParameter. Every time a page is being requested, this method will be executed and will then notify the application if the parameteris valid.

The idea behind these three components working together to prevent SQL Injection attacks  is very simple: prepare all your utility methods to check for valid parameters, define all your valid parameters and check for valid values on each page, take into consideration that if you are using a customerID in twenty pages on your application, they all must be of an integer value. Plugging these components into your application is fairly simple and will ensure that an already   running website will prompt you every time a hacker tries to change a query string regardless of whether your programmers have checked for valid parameters or not. Bear in mind that this is a plug-in, and like all plug-ins it will take its toll on your application performance. A truely secure application will embed any security methods inside the page object only using utility classes to assist. However, if invalid parameters are a problem for you, then this is a good solution.

How to Implement the Example:

Step 1: Add a new utility class and copy and paste the code in parameterCheck.cs into it. Do not forget to change the namespace to fit the needs of the application.

 public class parameterCheck{
public static bool isEmail(string emailString){
return System.Text.RegularExpressions.Regex.IsMatch(emailString,
"['\w_-]+(\.['\w_-]+)*@['\w_-]+(\.['\w_-]+)*\.[a-zA-Z]{2,4}");
}
public static bool isUSZip(string zipString){
return System.Text.RegularExpressions.Regex.IsMatch(zipString ,"^(\d{5}-\d{4})|(\d{5})$");
}
}

Step 2: In the Web.config file, add a key under the <appSettings> tag. This key will contain all of the parameters you wish to check for and the types they need to be. The name of the key is <safeParameters>, and the value can be for example: ordered-int32,customerEmail-email.

<appSettings>
<add key="safeParameters" value="OrderID-int32,CustomerEmail-email,ShippingZipcode-USzip" />
</appSettings>

Step 3: In your Global.asax copy and paste the code in the example into your Application_BeginRequest method.

Continues…

ASP.NET Session State Best Practices

Session state is an integral part of many ASP.NET apps but it can also be a drag on performance or result in application errors if used inappropriately. Here are our ASP.NET Session State best practices to ensure you won’t be tripped up by any gotchas:

  • Do not overuse Session State for user data storage.
    One of the problems with Session State is that it is so convenient for user data storage – just store anything using Session["someName"] = someName.Text . This leads developers to overuse Session State and store data that would be better handled by another technique (for example, you can use ASP.NET Membership Profiles to store and retrieve user settings, or use caching for storing miscellaneous items).
  • Try to avoid storing complex objects in Session State.
    Session Sate can store objects of any type (including objects you create) however, they are stored by serializing and then de-serializing them which results in a big performance penalty. If possible try to only store ‘basic’ types such as Integer, Decimial, String, DateTime, GUID etc
  • Use an Out of Process mode if possible
    Session State provides for three configuration modes – In Process, Out of Process using stateview and Out of Process using SQL Server.
    In Process stores the session state data in memory with the same process as the application, this has the advantage of being the fastest mode but it also means that all session data is lost when the app restarts. The app restart is more common than many developers believe, in addition to server and IIS restarts any change in the web.config or global.asax file will restart the app and all session state data can be lost.
    Out of Process (stateserver) stores the session data in memory but in a different process, if you are running a web farm this can even be on a separate machine. Out of Process (SQLServer) stores the session data in SQL Server which is the most stable as it will be recoverable in all scenarios except a database failure but it is also the slowest. Both Out of Process modes protect the session data from loss due to an app restart.
  • Do not store sensitive data in Session State.
    SessionID’s which identify user sessions are sent in clear text and can be intercepted by nefarious users. Once a user’s SessionID has been obtained, data stored in the Session State associated with that SessionID can be easily accessed. Thus you should avoid using Session State to store sensitive data or use SSL or encryption of the data to protect it.
  • Allow users to log out of an application
    You should allow users to log out of the app, upon logon the app should call the Abandon method. This will reduce the scope for a malicious user to get hold of  the unique identifier in the URL and then use it for retrieving user data stored in session state.

ASP.NET Security Tutorial

Securing an ASP.NET application is paramount for any project. Here (in no particular order), in this tutorial we present the primary ASP.NET security best practices:

  • Ensure system patches are fully up-to-date
    Not really an ASP.NET specific best practice but since ASP.NET relies on the underling OS for its operation it is essential to ensure the OS to fully patched with the latest security updates.
  • Secure all connection strings
    Typically an app’s database will stored its most sensitive data so preventing unauthorized reading of the connection string is a must. The connection string should be stored in the web.config file and not in the code behind for pages and also not in the SqlDataSource control or other data source controls. For maximum security encrypt sensitive settings in config files – see Encrypt Connection Strings in ASP.NET for details.
  • Use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings.
    It is possible to generate   the SQL for a command by building strings like below:

    SQLCmdStr = "Select * from users where username =' " & usernameTxt.Text  & "'

    This however allows for the possibility of SQL injection attacks by users directly typing SQL commands into text boxes which are then executed. Instead you can use a parameterized query as below:

    SQLCmdStr = “Select * from Users where Lastname =@LastName”
    SQLCmd.Parameters.Add(New SQLParameter(“@LastName”, ddl.SelectedItem.text))
  • Encrypt any sensitive data stored in View State
    View State is sometimes used to stored sensitive data sure as user names or even account numbers. Since View State is posted back to the server on every postback this data could be intercepted and read, therefore when any sensitive data is stored in View State the the page’s ViewStateEncryptionMode property should be set to true.
  • User input validation
    Always validate user input on the server even if it has been validated on the client since a user can easily bypass most client side validation by turning off javascript. The below code shows how to use Regex on the server-side to valid input:
  • using System.Text.RegularExpressions ;
    
    // Instance method:
    Regex regObj = new Regex(@"^[a-zA-Z'.\s]{1,40}$");
    Response.Write(regObj.IsMatch(Request.QueryString["InputName"]));
    
    // Static method:
    if (!Regex.IsMatch(Request.QueryString["InputName"],@"^[a-zA-Z'.\s]{1,40}$"))
    {
       // Name does not match expression
    }

    Note that user input does not only come from values input by the user on a form on the page. ASP.NET apps also take data form QueryStrings and cookies, these must also be validated in the same manner as input data.

    Continues…

5 Ways HTML5 can Speed Up Your ASP.NET Application

Html5 is often touted as a great solution for delivering multi-platform apps, but the performance boost of using Html5 in existing applications is often overlooked. Here we present 5 ways for you to use Html5 (plus CSS3 of course !) to boost the performance of your ASP.NET and ASP.NBET MVC apps.

  1. Use Html5 Input Types and Form Attributes
    One of the most common tasks in developing a web app is setup the input forms which will normally include client side validation (for example to ensure a valid email was input) , range restrictions (for example a minimum bid amount) and watermarks (ie textboxes with pre-input grayed-out text). This is normally implemented using javascript, ASP.NET simplifies many of these tasks by providing attributes for the ASP.NET TextBox however this is implemented in the final html by auto-generated javascript. This is results in a lot of extra page load and can complicated the debugging.
    Fortunately Html5 includes pre-defined input types such as email which performs many of these functions. For example, a textbox which only accepts an email address and has a placeholder (watermark) of “email address” would be

    <input type="email" placeholder="email address" />

    The are numerous input types included in Html5, a good example of these in operation is at Html5 Forms Demo

  2. Use CSS3 Instead of Images
    Images are often used for styling web elements, such as rounded corners, buttons, gradients, text effects (such as 3D or inset text). CSS3 provides support for all of these out-of-the-box so you page will no longer have to request and load images. With the introduction of IE9, all major browsers now support for these CSS3 properties, although it should be noted that rendering them in mozilla and webkit based browsers (such as Safari and Chrome) requires slightly different CSS code.
    See CSS Performance with Fewer Images for a full listing of all the available CSS3 styles to replace images.

Continues…

ASP.NET ViewState Security

ASP.NET ViewState data is stored in a single Base64-encoded string  such as  this:

id="__VIEWSTATE" value="dDw3NDg2NdTI5MDg7Ozr4="/>

Since this value is not formatted in clear text, developers sometimes assume that their ViewState data is encrypted which is most certainly not the case. This data string can be reverse-engineered this and then viewed. This is an obvious security issue if sensitive data is being stored in ViewState.

To make ViewState secure, there are two choices, hash codes and ViewState encryption.

Use a hash code.

A hash code  is a cryptographically strong checksum. When you use a has code, ASP.NET calculates the checksum based on the current ViewState content data and then adds this to the hidden input field when the page  when is returned to the client.  On the page post back, ASP.NET then recalculates the checksum to  ensures a  match. If a malicious user were to  change the ViewState data, ASP.NET can detect the  the change reject the postback.
Hash codes are enabled by default,  however, sometimes developers elect  to disable hash codes to prevent problems on a web farm when  servers have different keys. Hash codes can be disabled on the page in the .aspx file’s Page directive:

<%@ Page EnableViewStateMac="false" ... %>

To disable hashing site-wide use the  ViewStateMac attribute of the pages  element in  web.config :

<configuration>
<system.web>
<pages enableViewStateMac="false" />
...
</system.web>
</configuration>

For more on hashing, please refer to C# Security – Hashing

Use ViewState Encryption.

Hash codes help to prevent ViewState data from being tampered with but they do not provide much assistance in preventing ViewState data from being read since hash codes can still be converted to clear text. To prevent ViewState being read, use the  ViewState Encryption, which can be turned on at the page level using the ViewStateEncryptionMode property of the Page directive:

<%@Page ViewStateEncryptionMode=”Always” … %>

Or site-wide in the web.config file:

<pages viewStateEncryptionMode=”Always” />

There are three settings for viewStateEncryptionMode:

  1. Always : All ViewState data is encrypted.
  2. Never : No ViewState data is encrypted.
  3. Auto : Data is only encrypted when specifically requested by the ASP.NET control.

The default setting is Auto so no data will be encrypted unless otherwise requested by a control on a page. For a control to request encryption in needs to call the Page.RegisterRequiresViewStateEncryption() method before it is rendered to HTML.

Note that using encryption incurs a performance penalty so it should only be used when necessary.

ASP.NET Control State for Custom Server Controls

State management is a perennial challenge for any web development framework – once a page is refreshed any data on the page (such as text already entered in textboxes) must be persisted using some method. Traditionally ASP.NET solves this problem using View State which inserts text directly into the html of the page which can then be read by the server when the page is posted to the server. This solution works well in most circumstances but the one major issue is performance – View State adds a large payload to each page request and will slow the ASP.NET site/app down. The issue is especially acute when using ASP.NET AJAX since there are numerous background hits on the server and each of which needs to contain the full View State payload.

Control State is designed to be a much more lightweight store of data than view state . Control State is designed to store   data a control is currently using. Technically, control state works in the same manner as view state—storing serializable data that’s placed in a hidden field when a page is rendered. ASP.NET actually puts   view state and control state data into the same hidden field. The only major difference is that control state is unaffected by the EnableViewState property, therefore even if EnableViewState is set to false, acontrol can still store and retrieve data from  control state.

Since control state cannot be disabled, you will need to  carefully restrict the amount of information stored. Normally, it is limited to something critical such as the current page index or else a data key value. To use control state in  a custom server control, you   begin by overriding the OnInit() method and the calling Page.RegisterRequiresControlState() to notify ASP.NET that the control needs to access control state.

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.RegisterRequiresControlState(this);
}

Unlike view state, control state cannot be accessed  directly through a collection and you must override two methods:  LoadControlState() and SaveControlState(). These methods use a slightly irregular pattern. The overall idea is that you need to take any control state which has been serialized by the base class and then combine that with an object which contains your new serializable object. You can do this using the System.Web.Pair class, as shown below:

string myData;
protected override object SaveControlState()
{
// Get state from the base class.
object baseStateObj = base.SaveControlState();
// Combine  with the state object you wish to store
// and then return the final object.
return new Pair(baseStateObj, myData);
}

This technique will enable you to only store  a single object. For storing several items of information, consider creating a custom class which encapsulates all these details (and ensure it includes the Serializable attribute). An alternative method is to  create a chain of Pair objects:

private string strData;
private int integerData;
protected override object SaveControlState()
{
// Get state from the base class.
object baseStateObj = base.SaveControlState();
// Combine with the state objects you want to store,
// and return the final object.
Pair pairA = new Pair(strData, integerData);
Pair pairB = new Pair(baseStateObj, pairA);
return pairB;
}

Continues…