AKA Marketing.com Logo            VISIT THE BLOG            

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

« Home / Forums »        


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

Blogged thoughts

| by the www.akamarketing.com team

Archive for July, 2007

Inserting Code into Wordpress

Sunday, July 29th, 2007

I’ve shed many tears over the years (I’m a poet, I just don’t know it) when trying to insert code samples into my Wordpress blog posts. Wordpress users who cover technical topics will have shared in my pain and will know exactly what I mean. I therefore feel obliged to let people know about a Wordpress plugin called Code Snippet which I recently discovered and installed. Code Snippet which is available for download at http://wordpress.org/extend/plugins/codesnippet-20/ enables bloggers to post color highlighted code (with optional line numbering) in their posts without fear of it being mangled or hidden by Wordpress. It runs off the GeSHi engine which is generic syntax highlighter which supports a tonne of programming and markup languages.

The installation of Code Snippet is extremely easy. You basically just need to upzip the archive to your desktop, upload it to the wp-content/plugins folder of your overall Wordpress installation folder and then activate it from the ‘Plugins’ tab from within Site Admin. To actually use the plugin you wrap code in code blocks illustrated by the below image.

Code Snippet Code Blocks

You replace the value of the lang attribute with the language your code is written in such as HTML or c#. Below is an example of some PHP code displayed via Code Snippet.

  1. $ufun = “$dfunction”;
  2. switch ($ufun) {
  3.  case $ufun=“Edit”:
  4.  //go to Spoono
  5.     //Header ("Location: ./editor.php?filename=$filename&ffunction=$ffunction");
  6.  include(“editor.php”);
  7.  break;
  9.  case $ufun=“dDelete”:
  10.  echo “delete a dir”;
  11.  //Header ("Location: ./delete.php?filename=$filename&ffunction=$ffunction");
  12.  include(“delete.php”);
  13.  break;
  15.  case $ufun=“dRename”:
  16.  //echo "Rename was selected";
  17.  include(“rename.php”);
  18.  break;
  20.  case $ufun=“dCopy”:
  21.  //echo "Copy was selected";
  22.  include(“copy.php”);
  23.  break;
  25.  case $ufun=“dMove”:
  26.  //echo "Move was selected";
  27.  include(“move.php”);
  28.  break;
  30.     case $ufun=“dDownload”:
  31.  //echo "Download was selected";
  32.  include(“download.php”);
  33.  break;
  35.  case $ufun=“dOpen”:
  36.  //echo "Download was selected";
  37.  include(“filemanager.php”);
  38.  break;
  40.  default:
  41.  echo “You should not be here”;
  42.  }

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. {
  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;
  8.     if(resultCount == 1)
  9.     {
  10.           args.IsValid = false;
  11.     }
  12.     else
  13.     {
  14.          args.IsValud = true;
  15.     }
  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. {
  4.           //test for correct format
  5.          if(args.value == correctformat)
  6.          {
  7.                  args.InValid = false;
  8.          }
  9.          else
  10.          {
  11.                 args.InValid = true;
  12.          }
  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.

12 Lorcan Crescent, Santry, Dublin 9, Ireland +353 87 9807629