AKA Marketing.com Logo

Blogged thoughts, is our web blog. Expect views, opinion, rants and tirades about everything and anything 

« Home / Services / Forums »         Organic Search Engine Optimization (SEO) Solutions. Call now on +00-353-879807629

Subscribe to our SEO / IT related blog by entering your email address below

Blogged thoughts

| by the www.akamarketing.com team

Archive for the 'ASP.NET' Category


ASP.NET input validation overview

Sunday, July 29th, 2007

Coming from a PHP background I’m used to manually adding code to perform validation in my applications to check if this field is filled in and if the value in that field is less than that value etc. Depending on the security context I may validate on the client side (via Javascript), the server side or both. Just because I’m used to doing something though doesn’t mean I like doing it, I’d much rather be spending my time sorting out other more interesting elements of my application.

Imagine the size of the smile on my face then when I started developing with ASP.Net and discovered a whole rake of input validation controls which automatically configure client and server side validation built into the .Net framework. These controls cover a wide range of validation needs (in fact many apps can be completely validated without the developer needing to write a single line of code) and require only basic configuration.

The current incarnation of ASP.Net (2.0) includes six validation controls. These controls are RequiredFieldValidator, RangeValidator, RegularExpressionValidator, CompareValidator, CustomValidator and finally ValidationSummary. I’ll cover these in detail over the next few paragraphs, starting with RequiredFieldValidator.

The most commonly used control is the RequiredFieldValidator. It allows you to specifiy that certain HTML controls must have user input and displays an error message if input is not given. To associate a RequireFieldValidator with an input control you set the ControlToValidate property equal to the ID of the input control. The ControlToValidate property is available to all validation controls except the ValidationSummary control and is a required setting. When I discuss other validation controls later in this post I may not explicitly mention this property in relation to each control, but you know now it needs to be set. Other properties common to all controls (except ValidationSummary) and which are worth a mention include ErrorMessage, Text and EnableClientScript. Both ErrorMessage and Text allow the developer to set the text that displays when some validation fails. If ErrorMessage and Text are both set Text overrides ErrorMessage. I will cover the EnableClientScript property later in this post.

Back to the RequiredFieldValidator - The InitialValue property of the RequiredFieldValidator validation control allows you to ‘tell’ the framework what’s in the HTML control by default and thus if the user does not change this default value be it some text in a textbox or a selection in a dropdown list the HTML control will be considered as not set and thus the error message will show. The InitialValue is particularly useful when you need to validate a dropdown list as often you would have a default item such as ‘– Please Select an Option –’ in the list. If the corresponding value of this option was say ‘0′ then setting the InitialValue to ‘0′ on a RequiredFieldValidator would cause the page to fail validation if the user did not change the selection.

If you need to ensure that the value a user inputs is between some defined range then the RangeValidator control can be used. This control exposes two properties called MinimumValue and MaximumValue which allow you to set the low and high bounds for correct input data. The other significant property of this control is the Type property. The Type property sets the data type of the value to check and can be set to Currency, Date, Double, Integer & String. 

The next ASP.Net input validation control is the RegularExpressionValidator. This allows developers to check if user input matches a specific pattern or form. This validation control is often used to validate email addresses or telephone numbers. Use of this control requires you to set the ControlToValidate property (as you would with the other validation controls) and the ValidationExpression property. The ValidationExpression property accepts a regular expression as input, a regular expression (regex or regexp for short) is a special text string for describing a search pattern. Regular expressions can be quite difficult to write (and even harder to read) however they are very powerful once you get the hang of them. If you are a Visual Studio user you can use its built in Regular Expression Editor which has a couple of prebuilt regular expressions for checking things like email address format, zip code format etc. The Regular Expression Editor is available from within the ValidationExpression property field. The regular expression for matching an email address is below:

  1. \w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

More information about regular expressions can be found at http://www.regular-expressions.info/.

To continue with the CompareValidator then. This control allows you to compare the value in one input control to the value in another or it allows you to compare an input control value to a defined value. An example where you might use the first method of usage would be to compare two password input textboxes to confirm the user has typed in his or her desired password correctly (as dots or asterisks will be shown in place of the real input). To use the compareValidator in this scenario you need to set the ControlToCompare, Operator and Type properties. The ControlToCompare property needs to be set to the second control which you want to compare against the first control as specified in the ControlToValidate property. The operator setting determines what type of comparsion is done, for this you can select a couple of values such as Equal, NotEqual, LessThan etc. One particularly iteresting value for this property is DataTypeCheck which if selected allows you to simply check if input is of a particular data type such as a date or a number (int). The Type property we have seen before, it simply tells the framework to treat the input data as currency, date etc.

Hopefully your beginning to see that the above validation controls can really make a developers life a lot easier, however they don’t do everything and there will often be a need for custom validation logic to help you completely fool proof your apps. This is where the CustomValidator control comes handy. This control allows the you to write custom validation logic. An example where you might use a CustomValidator might be to check if a username is already taken on a new account form. This would require a peek in the database and thus requires the validation to be performed on the server, however CustomValidator validation functions can run on the client side too (if no server side resources are needed of course).  

The CustomValidator is (because it’s custom) a little more difficult to work with than the other validation controls. If your validation logic can only run on the server (and it’s impossible for a client side function to therefore work) you can ‘get away’ with only setting the ControlToValidate property. If however you want and can have client side custom validation you need to set the ClientValidationFunction equal to the name of the Javascript function which will handle the validation logic.

What about the ServerValidationFunction property? Well there isn’t one, to tie a CustomValidator control to a server side validation function you actually need to go through the controls ServerValidate event (in Visual Studio click the yellow lightning bolt and you’ll see it) and select your server side function. Since I finally got around to installing a wordpress plugin which allows me to display nicely formatted color coded code in my posts lets write up a server side validation function to see the format required.

  1. void CheckForDuplicateUserName(object source, ServerValidateEventArgs args)
  2. {
  3.  
  4.      //create connection,
  5.      //create SQL command - something like "select count(username) from users where username = ‘args.value.ToString()’"
  6.      //execute it and store result in an int variable called resultCount;
  7.  
  8.     if(resultCount == 1)
  9.     {
  10.           args.IsValid = false;
  11.     }
  12.     else
  13.     {
  14.          args.IsValud = true;
  15.     }
  16.  
  17. }

You might be able to figure out that args.Value holds the value of the ControlToValidate control and to send the result back to the framework you set args.IsValid to true or false. If you set args.IsValid to false it means validation has failed and the specified error message will be displayed to the user, in this case the error message could be something like ‘That username is already taken, please select another one’. Obviously the above is only template code, in production code you would server.htmlencode() args.Value to be sure no malicious user is trying to attack your app, you would probably want to escape apostrophes too, additionally you may want to throw some try and catch blocks around your DB logic. In the example the data (a username represented by args.Value) fails validation if a record is returned from the DB meaning there is already a user with that username.

Using a client side validation function with CustomValidator is very similar to using a server side function, in fact the only difference is the parameters that the functions take. The format is given below:

  1. function CheckForCorrectFormat(oSrc, args)
  2. {
  3.  
  4.           //test for correct format
  5.          if(args.value == correctformat)
  6.          {
  7.                  args.InValid = false;
  8.          }
  9.          else
  10.          {
  11.                 args.InValid = true;
  12.          }
  13.  
  14. }

The final control which I’ll talk about is the ValidationSummary control. This control is different from the five aforementioned controls in that it doesn’t actually test or validate anything, its purpose is to provide a single place where you can display all a pages validation error messages from validation controls such as RequiredFieldValidator, RegularExpressionValidator etc. Consolidating all error messages like this is quite user friendly, particularly for larger forms. The default usage of a ValidationSummary control does not require the setting of any properties, you can literally just drag it on your page and the error messages (set via the ErrorMessage property) from all other validation controls on the page will show up.

Two interesting properties of the control include ShowMessageBox and ValidationGroup. ShowMessageBox allows you to instruct the framework to show any validation error messages in a Javascript alert box. This could be useful if space is a concern on your form design. The ValidationGroup property allows you to set the ValidationSummary control to only show error messages from certain and not all validation controls on a page. You use the ValidationSummary ValidationGroup property in conjuction with the ValidationGroup property of the five regular validation controls.

It is important to note that the messages which a ValidationSummary control shows are taken from the ErrorMessage property of each individual validation control it works with, it does not work with the Text setting which sets the text to display when validation fails for a specific validation control. This means you could set the Text setting for all your regular validation controls to say a ‘*’ to signify something is required and also set the ErrorMessage property for them same controls to a string such as ‘The firstname field is required’ and have that message displayed in your ValidationSummary control.  

Most of what I wanted to cover in relation to ASP.Net validation controls has been covered but before I end I do want to mention the EnableClientScript property which is available to all validation controls. This setting can be used to instruct the framework to do client side validation via Javascript on all supported browsers and is set to True by default. If you set this value to false on any validaton control the framework will only perform server side validation for that control which means a postback is required. Turning off client side validation for one validation control and not the others can result in things being out of sync which can lead to a bad user experience so be sure to go with all client side validation, all server side validation or the default implementation of both (for all controls), do not mix and match. The combination of using both client side and server side validation means that a postback can be avoided due to the Javascript client side stuff which is a nice convenience to the user however if a bold user tries to bypass security by turning off Javascript the server side stuff will still nab him good and proper, this sort of good user experience without compromising security is what the ASP.Net Framework provides in abundance. It should be noted however that if you need to access a server side resource like a DB (as in our CustomValidator username server side logic above) well then to avoid mixing and matching (and the problems that brings) you will need to go with server side and only server side validation for all controls.

Well that’s the end of another post, the first in a while I must admit, in it you got exposure to all six of the validation controls built into the ASP.Net framework. I certainly didn’t attempt to cover every single little detail of these controls hopefully however I have given you a good grounding as to what is possible and also provided a good base for further research. If you have any questions please leave me a comment and I will do my best to help out.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Digg
  • Furl
  • YahooMyWeb
  • Reddit
  • Simpy
  • De.lirio.us
  • StumbleUpon
  • Technorati
  • Netscape
  • Spurl
  • blogmarks
  • blinkbits
  • SphereIt
  • Slashdot
  • Ma.gnolia

ASP.NET search engine optimization

Sunday, March 11th, 2007

Has anyone noticed how clumpy and verbose the source code is of some .NET generated .aspx pages are? I mean this can’t be good food for the stomaches of the major search engines, nor can it be good for download times. There is no point is creating a feature rich .aspx website in comparatively double quick time with an advanced IDE like visual studio 2005 which runs on an equally advanced framework like .NET 2.0 when that very same IDE and framework is causing so much code blote and badly placed code (much of it probably unnecessary) that it is likely hampering your positions in the search engines and/or causing people to leave your site before it is even fully loaded.

Of course the amount of bloat created depends on what type of pages your programming but often the end produced source code can be ‘cleaned up’ regardless of what controls, interfaces etc. you are using. It’s just a matter of knowing what to look out for really. One of the main culprits are as far as I can see is ASP.NET’s ViewState mechanism.

ASP.NETs ViewState is the built in mechanism which enables controls such as textboxes, labels, datasets etc. to maintain their states (data) between postback requests for the same page. It does this by hashing the current state of the page and controls into a string and saves this into a hidden field called __VIEWSTATE. At the server, ViewState is used to recontruct the web page and its server controls. This is fine and prevents an ASP.NET developer having to manually repopulate form controls using POST values like is the case with something like PHP, however it is not without a cost. Have a look below at the value of a hidden __VIEWSTATE textfield which was produced from a .aspx page with only a menu and treeview control on it.

‘/wEPDwUJMzg4NTE1Mzc4D2QWAgIDD2QWBAIDDzwrAAkCAA8WCB4NTmV2ZXJF
eHBhbmRlZGQeC18hRGF0YUJvdW5kZx4MU2VsZWN0ZWROb2RlZB4JTGFzdEluZ
GV4AgFkCBQrAAIFAzA6MBQrAAIWCB4EVGV4dAUJQ3VzdG9tZXJzHghEYXRhUG
F0aAUQLypbcG9zaXRpb24oKT0xXR4JRGF0YUJvdW5kZx4QUG9wdWxhdGVPbkR
lbWFuZGdkZAIJDzwrAA0CAA8WAh8BZ2QMFCsABQUPMDowLDA6MSwwOjIsMDoz
FCsAAhYKHwQFBEhvbWUeB0VuYWJsZ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JTG9jYXRpb25zHwhnHwlnHwUFMC
8qW3Bvc2l0aW9uKCk9MV0vKltwb3NpdGlvbigpPTRdLypbcG9zaXRpb24oKT0
yXR8GZ2RkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQlU
cmVlVmlldzGl0+HS1X8B5jfomTSld5U3ULhXjg== ‘

Obviously if I was to add more controls this value would grow accordingly. ViewState is enabled for all controls by default, luckily though ASP.NET has made the EnableViewState property available for setting true or false on a control by control basis and thus you can disable it for certain controls which you might never change like a label or a readonly datatable which might be populated from an external source such as a database or an XML file. For example below is the value of the same __VIEWSTATE hidden field (from above) with EnableViewState set to false for the menu control which gets populated from an XML file when the page loads and thus its state will not change between requests/postbacks.

‘/wEPDwUJMzg4NTE1Mzc4D2QWAgIDD2QWAgIDDzwrAAkCAA8WCB4NTmV2ZXJ
FeHBhbmRlZGQeC18hRGF0YUJvdW5kZx4MU2VsZWN0ZWROb2RlZB4JTGFzdEl
uZGV4AgFkCBQrAAIFAzA6MBQrAAIWCB4EVGV4dAUJQ3VzdG9tZXJzHghEYXR
hUGF0aAUQLypbcG9zaXRpb24oKT0xXR4JRGF0YUJvdW5kZx4QUG9wdWxhdGV
PbkRlbWFuZGdkZBgBBR5fX0NvbnRyb2xzUmVxdWlyZVBvc3RCYWNrS2V5X18
WAQUJVHJlZVZpZXcxU1/1MUWW6NZaM/KXGnbkTXRYJ3w=’

That’s quite a difference right? And because the control does not change between requests/postbacks the page works exactly as before. Disabling the ViewState for the treeview control would further reduce the contents of the __VIEWSTATE hidden field, it too is populated from an external data source and thus does not require ViewState enabled. Therefore to reduce filesize and keywords to source ratio for SEO purposes turn off viewstate for each control which will not change between multiple requests for the same .aspx page. You can find the biggest ViewState contributors by examing the ‘Control Tree’ section of the trace.axd file. You need to have first enabled tracing of course.

Additionally the usual good practice of using external .js files rather than in-source embedded code will further reduce unneeded bloat and allow your .js file to be cached which should enhance download times.

Aside from generally cleaning your code up there are some other steps of optimisation which can be taken too. Specifically in terms of search engine optimisation an interesting feature of ASP.NET 2.0 is URL mapping. This allows a defined friendly URL such as akamarketing.com/televisions.aspx to be mapped to a complex SEO unfriendly URL such as akamarketing.com/store.aspx?productid=202030&basket=303303&name=television. This means that the actual URL which is the long complex one can be accessed from the shorter SEO friendly one. The original URL will of course still work too. From a programming point of view everything is exactly the same which means all the GET query parameters in the URL are still available. From an end user and search engine perspective the URL is much more friendly and spiderable. Additionally the improved keyword density in the shorter nicer URL versus the longer complex one should facilitate ranking boosts on MSN which deems keywords in URLs to quite significant and it should certainly help on the other major search engines such as Google and Yahoo too.

URL mappings must be manually defined in the web.config file, so if your adding dynamic content including new products, categories, articles etc. to your website/database a lot you will have to manually add a new mapping entry into the web.config file for each item you wish to be accessible via an SEO friendly URL. The entries follow a standard layout though so I’m sure a script could be written which examines your database and outputs the relevant mapping XML code which you could then simply copy and paste into the web.config file, infact I may write one myself over the next week or so if I get the chance. The format itself is shown below.

URL Mappings

As you can see the individual mappings must come between opening and closing tags of the urlMappings element and this element in turn must be included within the system.web element of the configuration file.

Moving on then let’s mention page titles. Not suprisingly ASP.NET provides you with the ability to dynamically change the content of a webpages HTML title tag - you know the one at the top of the browser which Google, Yahoo and MSN love to see your keywords in. It is very important that what’s included in this tag reflects your page content specifically, having something generic just won’t do. When your content is being read from a database (ie - it’s dynamic) the title tag will need to be set dynamically at runtime based on the current content item. There are a number of ways to do this, however the most simple is to access the title property of the HTML header and update it as needed. Before you can access a pages header programatically you have to set it to run on the server side by including the runat=”server” directive in the pages opening HTML head tag. To then access the title tag it is a simple as Header.Title = “new title value”; Of course in a live website you would set Header.Title to some database derived value.

In addition to the pointers above the usual common sense SEO techniques such as good content, good structure and good navigation of course still apply just as they would for any webpage or website, so try not to get completely caught up in the ‘power’ of ASP.NET while at the same time disregarding the cornerstones of SEO as you’ll most likely find yourself stuck in a bit of pickle.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Digg
  • Furl
  • YahooMyWeb
  • Reddit
  • Simpy
  • De.lirio.us
  • StumbleUpon
  • Technorati
  • Netscape
  • Spurl
  • blogmarks
  • blinkbits
  • SphereIt
  • Slashdot
  • Ma.gnolia