Blog

Short and
to the point

ASP.NET : Switching between HTTP and HTTPS automatically

First tell your application which pages or directories should be secured by adding the following to the configuration section of your web.config file...

<configSections>
  <section name="SecurePages" type="System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</configSections>
<SecurePages>
  <add key="~/securepage1.aspx" value="page"/>
  <add key="~/securepage2.aspx" value="page"/>
  <add key="~/admin" value="directory"/>
</SecurePages>

Next create a class file called SecurePages.vb within the App_Code directory of your website.

Add the following classes to SecurePages.vb...
Public Class SecurePage
  Private _path As String = ""
  Private _pathType As String = ""

  Public Property Path() As String
    Get
      Return Me._path
    End Get
    Set(ByVal value As String)
      Me._path = value
    End Set
  End Property

  Public Property PathType() As String
    Get
      Return Me._pathType
    End Get
    Set(ByVal value As String)
      Me._pathType = value
    End Set
  End Property
End Class

Public Class SecurePath

  Public Shared Function IsSecure(ByVal path As String) As Boolean
    Dim lstPages As New List(Of SecurePage)()

    Dim securePage As Boolean = False

    Try
      ' Get list of pages to be served securely from web.config
      Dim sectionPages As NameValueCollection = DirectCast(ConfigurationManager.GetSection("SecurePages"), NameValueCollection)

      For Each key As String In sectionPages
        If (Not String.IsNullOrEmpty(key)) AndAlso (Not String.IsNullOrEmpty(sectionPages.[Get](key))) Then
          lstPages.Add(New SecurePage() With { _
           .PathType = sectionPages.[Get](key), _
           .Path = key _
          })
        End If
      Next

      ' Look for current page in list and return whether to secure it or not
      For Each page As SecurePage In lstPages
        Select Case page.PathType.ToLower().Trim()
          Case "directory"
            If path.Contains(page.Path) Then
              securePage = True
            End If
            Exit Select
          Case "page"
            If path.ToLower().Trim() = page.Path.ToLower().Trim() Then
              securePage = True
            End If
            Exit Select
          Case Else
            securePage = False
            Exit Select
        End Select
      Next
    Catch ex As Exception
      Throw New Exception(ex.Message)
    End Try

    Return securePage
  End Function
End Class

Finally, add code to the Global.asax file which will intercept all page requests and redirect if necessary...
Private Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
  Dim path As String = HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath
  Dim url As String = HttpContext.Current.Request.Url.AbsoluteUri
  If InStr(url, "localhost") = 0 Then
    If HttpContext.Current.Request.ServerVariables("HTTPS") = "on" Then
      ' Do nothing (unless path not secure or you are referencing a Microsoft web handler .axd file)
      If SecurePath.IsSecure(path) Or InStr(path, ".axd") > 0 Then
      Else
        HttpContext.Current.Response.Redirect(url.Replace("https://", "http://"))
        Return
      End If
    End If
    If HttpContext.Current.Request.ServerVariables("HTTPS") <> "on" Then
      If SecurePath.IsSecure(path) Then
        ' Redirect to https version
        HttpContext.Current.Response.Redirect(url.Replace("http://", "https://"))
      End If
    End If
  End If
End Sub

This article is based on the excellent C# version by John Mendez...
http://www.xdevsoftware.com/blog/post/Redirect-from-Http-to-Https-in-ASPNET.aspx


Posted: 2011-09-28

ASP.NET : Membership

FormsAuthentication

Stores an authentication ticket as a cookie to remember whether a user is logged on.

To use forms authentication in your application add authentication XML to the <system.web> section of your web.config file:-

<authentication mode="Forms">
  <forms loginUrl="~/login.aspx">
  </forms>
</authentication>

If a user requests a secure page without logging in they will be redirected to the loginUrl specified.

Applications handling a large amount of users should store data in  SQL Server or Active Directory.
Smaller apps can store user credentials in the web.config file itself (see below).


SqlMembershipProvider

To use this provider you first need to create a SQL Server database to store user accounts.
Run aspnet_reg.exe from a DOS command prompt (look online to find out where this file is located).
Use the interface to specify which SQL server the membership database should be created on.
Add connection string XML to the <configuration> section of your web.config file:-
<connectionStrings>
  <add name="dbMembership"
       connectionString="data source=[IP address];Initial Catalog=aspnetdb;User ID=[your username];Password=[your password];"
       providerName="System.Data.SqlClient"/>
</connectionStrings>

Add membership XML to the <system.web> section:-

<membership defaultProvider="MySqlMembershipProvider">
  <providers>
    <clear/>
    <add name="MySqlMembershipProvider"
         connectionStringName="dbMembership"
         applicationName="[your application]"
         type="System.Web.Security.SqlMembershipProvider"/>
  </providers>
</membership>

This will add your application to the [aspnet_Applications] table.
You can now use the website administration tool to create and manage your application's users.

Note: It is possible to use a database file (ASPNET.mdf) in your App_Data folder but this is not recommended in a live hosted environment.


Security Web Controls

Login - Display a standard login dialog box with username, password and 'remember me' prompts. This control works best with SQL Server or Active Directory membership providers. If your credentials are stored in the web.config file, use text boxes and buttons instead.

LoginView - Display different content dependant on a users role or whether they are logged in or not.

PasswordRecovery - Sends a temporary password to the user allowing them to log in and change it to their own.

LoginStatus - Displays a login or logoff link dependant on whether the user is authenticated or not.

LoginName - Displays the username of the currently logged in user.

CreateUserWizard - Provides a customisable UI for creating new user accounts.

ChangePassword - Prompts the user for their old password and asks them for a new one.


Roles

By using roles in your website you can deliver different content to each user who logs in.

To enable roles add role manager XML to the <system.web> section of your web.config file:-
<roleManager enabled="true" defaultProvider="CustomizedRoleProvider">
  <providers>
  <add name="CustomizedRoleProvider"
       type="System.Web.Security.SqlRoleProvider"
       connectionStringName="dbMembership"
       applicationName="[your application]" />
  </providers>
</roleManager>


You can now use the website administration tool to asign your application's users to specific roles.
Access rules can also now be set up to restrict or allow users access to specific directories.


Storing User Credentials in web.config

It is also possible to store usernames and passwords in the web.config file by adding authentication XML to the <system.web> section:-

<authentication mode="Forms">
  <forms loginUrl="login.aspx">
    <credentials passwordFormat="Clear">
      <user name="user1" password="password1"/>
      <user name="user2" password="password2"/>
    </credentials>  </forms>
</authentication>

Then add the following code to the click event of your login button

If FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text) Then
  FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, True)
  Select Case txtUsername.Text
    Case "user1"
      Response.Redirect("admin/welcome1.aspx")
    Case "user2"
      Response.Redirect("admin/welcome2.aspx")
  End Select
Else
  lblMessage.Text = "Incorrect username or password. Please try again."
End If



Posted: 2011-09-16

ASP.NET : Disable Caching

To prevent caching of your web application simply add the following lines to the <head> section of your MasterPage.

<meta http-equiv="Expires" content="-1">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">

Then add the following to your Page_Load.

Response.Cache.SetCacheability(HttpCacheability.NoCache)

This code can be applied on a page by page basis instead of the MasterPage if you only want to disable caching on individual pages.

Posted: 2011-09-12

ASP.NET : Hide Web Server Information

1. Prevent server error messages from being shown in a production environment.

Add the following to the <system.web> section of your web.config file...

<customErrors mode="RemoteOnly" defaultRedirect="~/error.aspx">
You will then need to create a web page with a more friendly message and save is as error.aspx.

2. Remove 'Response Header' information from HTTP requests in order to prevent disclosure of server type and web technology.
Add the following to the <system.web> section of your web.config file...
<httpRuntime enableVersionHeader="false" />
Add the following to the <system.webServer> section of your web.config file...
<httpProtocol>
 <customHeaders>
 <remove name="X-Powered-By" />
 </customHeaders>
</httpProtocol>

Unfortunately removing the 'Server' header is a little more involved but can be achieved by implementing an httpModule that strips this header out by calling Response.Headers.Remove("Server") from the PreSendRequestHeaders event...

http://www.frederikvig.com/2010/11/removing-http-headers-for-asp-net-sites/

Posted: 2011-07-06

ASP.NET : Session State - Out of Process Mode

ASP.NET can store session state in a running process that is distinct from the ASP.NET worker process.  It is then available to multiple web servers in a web farm and is preserved even if the application is restarted.

To enable, configure the service on both your development and production machines.
  1. Click Start / Run.
  2. Enter services.msc.
  3. Locate the ASP.NET State Service in the Services (local) list.
  4. Right click on it and choose Properties.
  5. Change the Startup Type to Automatic.
  6. Click the Start button.
  7. Click OK.
This will start the aspnet_state.exe process in Task Manager.

Now all you need to do is modify the sessionState element in the system.web section of your web.config file.


<sessionState mode="StateServer" cookieless="UseCookies"
stateConnectionString="tcpip=serverName:42424" />

More information is available here.


Posted: 2011-05-27

Cookie Law

From 26 May 2011 you will need a user's consent if you want to store a cookie on their device. You will also need to provide clear and comprehensive information about the purposes of the storage of, or access to, that information.

The only exception to this rule would be where the cookie is strictly necessary for the service the user has requested (eg. online shopping).

If a complaint is made about your website you will need to tell the ICO how you have considered the points above and that you have a realistic plan to achieve compliance.

The more privacy intrusive the information gathered, the more priority you will need to give to letting the user know what data is being gathered and getting their consent.

Once you have gained consent for the use of a cookie, you do not need to gain consent for subsequent use of the same cookie (for the same purpose) in future.

Further information is available in this PDF.

Posted: 2011-05-18

Google Panda Update Summary

The Google Panda Update was released in early 2011 in an effort to combat poor quality content on the web.

Penalised 
  • Large amounts of duplicate, low-quality or irrelevant content
  • Excessive keyword spamming (unnatural overuse of a word on a page)
  • Slow page load times
  • Poor spelling and grammar
  • Ads which are inappropriate to the page (especially near the top)
  • Low quality links (from irrelevant sites and link building services)

Rewarded 
  • Original content
  • High quality links (from high ranked sites which are relevant to your content)
  • Video, news and blog content

Posted: 2011-05-18

Setting up as a Freelance Web Designer - Contracts

Firstly ensure that there is no confusion between you and your customer by asking them to fill out a website request form.
1. contact information - name, email, telephone, who will provide graphics, who will provide content
2. project budget - they may not tell you the full amount but this can give you an idea of what they expect to pay
3. company details - company name, address, website URL, products or services, ideal customer, primary competitors
4. project details - brief description, timeframe, redesign or new site, websites to emulate, colour scheme, branding, SEO work required?

When you have this information, draw up a definition of work contract which lists the number of pages, scripts and graphics required for the website. If you can, include estimates of how long each item will take and, if possible list completion dates. By summing up the time taken on each item, you should be able to provide a total project fee. Remember to include any costs incurred buying domains or setting up a hosting service.

Tell the customer how you prefer to be paid and what your penalties are for late payments and bouncing checks. Treat your business seriously, even with friends and family. It may be wise to demand a 30-50% deposit before proceeding with a job. You could also state that this will be forfeit upon cancelation to ensure the client is serious.

It is a good idea to inlcude a design brief which details the objectives and target audience for the site. If the client has requested that you emulate any existing websites, remember to state this. Include details of any logos or colour schemes which need to be adheared to. Specify who owns the copyright for all content, designs, graphics, multimedia and scripts. Inform the customer if you plan to include a link to your website or any personal promotion.

Submit the contract for revision by the customer and when everyone is happy, get a signature.

Posted: 2011-05-10

Setting up as a Freelance Web Designer - Promotion

The first thing to do when promoting your new business is to set up a portfolio website. Your website should show everything you are capable of. Make it standards compliant, accessible, fast, and optimized for search engines. You may even consider doing multiple portfolios for different kinds of customers. Remember to design a logo for your website as these can also be used in letterheads, business cards, advertising, etc.

Portfolios should include screen shots of only your very best wesbites together with descriptions of the work carried out on each. Each screenshot should link to the actual website or preferably your own copy of the website. Ensure you have permission before creating a copy of a clients website. If you can regularly update a blog this will encourage the search engines to crawl your site. You can use blogs to exchange links with other sites.

Once you have created your portfolio you can use analytics to keep track of your visitors. Submit to as many search engines as you can and consider advertising tools such as Google AdWords. You may even choose to design flyers aimed at local businesses.

Ensure your business is listed on relevent uk directories like FreeIndex, Yell, Scoot, etc (just do a search for 'business directories').

Add a public profile of yourself and your business to LinkedIn.

Post advice on forums relevant to your business. You may even be able to include a link to your own website.

Posted: 2011-05-10

Setting up as a Freelance Web Designer - Pricing


You can get up to date information on the latest technology trends at ITJobsWatch. They also provide the latest average daily and hourly rates for web designers. However, don't expect to get paid at the high end of the scale if you are only just starting out in web design. It is best to try to charge slightly less than your competition (just check their websites).

Flat-rate pricing (set amount per page) may work for the majority of customers but some may require back end databases or extensive design work so this can be unfair on the web designer. Hourly rates are clearer for the designer and will be understood by most businesses.

When charging at an hourly rate it is only fair to give your customers an estimate of time scales involved per project. Agreeing to not work more than a set amount of hours on indiviual sections can avoid arguments later and gives the designer a clearer understanding of the customers expectations. You could even publish time and cost estimates on your website to attract customers.

Over time it is best to raise your rates by a small amount each year to keep up with inflation. Most of your customers will accept this.

Posted: 2011-05-10

 

Drop me a line...