My Resume | Contact Me | RSS Feed | Follow Me on Twitter

Code Capers

The Ninja Coding Dojo
RSS Feed Twitter Email

Client Side Validation with jQuery

clock February 24, 2010 by author Michael Ceranski

Validating user input on the client definitely has its advantages. It not only avoids unnecessary round trips to the server but it can also drastically improve the user experience. When I think about client side validation I think about jQuery. If you are familiar with jQuery, then you know that there are a ton a plug-ins available. Just like an Apple IPod has “an app for that”,  jQuery has a “plugin for that”. Anyway, after a quick search I discovered the jQuery Validation plugin.

There are two different ways to use the Validation plugin. The first way, is to the pure JavaScript route. This means you establish all the validation rules, messages and callback events from code. The second way is to decorate your input fields with special CSS classes. The plugin will then inspect the class attribute of each field at runtime and apply validation rules accordingly. In the upcoming example, I used the CSS approach. However, if you decided that you want to go in the other direction there are some excellent demos on the validation plugin homepage.

There are a bunch of different class names that the plugin will honor. The most basic class name is required. However in addition to checking if a field is required you can also perform pattern matching. For example my form has an email field. When someone fills out this field I not only want it to be required, but I also want to make sure that a valid email address is entered. In order to achieve this I use the class name required email. Similar validators are available for website addresses, dates, credit card numbers and more. See the documentation page for the complete list.

Here is a  screenshot of my comment form:

 image

Here is the HTML markup for my form. Notice the class names used in each of the input fields. From the html you can deduce that the full name is required. The Email is required and must be a valid address. The website field is optional but if text is entered is must be a valid URL. Finally, the comment field is required: 

<form id="comment_form" action="#">
<fieldset>
    <ul>
        <li>
            <label>Full Name *</label>                
            <input type="hidden" id="postID" name="postID" value='<%=Model.ID %>' />
            <input type="text" id="author" name="author" class="required" value="" size="40"/>
        </li>
        <li>
            <label>Email *</label>
            <input type="text" id="email" name="email" class="required email" value="" size="40"/>
        </li>        
        <li>
            <label>Website</label>
            <input type="text" id="website" name="website" class="url" size="40" />
        </li>        
        <li>
            <label>Comment *</label>
            <textarea id="comments" name="comments" rows="8" cols="60" class="required"></textarea>
        </li>
        <li>
            <label></label>
            <input type="submit" id="btnSaveComment" value="Save Comment" class="submit" />        
            <img id="ajax_loading" src="/Content/images/ajax_loading.gif" alt="loading" />          
        </li>
    </ul>
</fieldset>
</form>     


To wire up the plug-in you only need one line of code in the document.ready event:

var validator = $("#comment_form").validate();

Summary

Client side validation is a great way to enhance user experience. However, keep in mind that client side and server side validation can be used together. As always, pick the right tool for the job. For example, if you are working with mobile devices that have limited capabilities it may make more sense to use server-side validation.


Special thanks to Elijah Manor who helped me troubleshoot an issue with the validator plugin. I originally only had the id attribute on the input fields which caused some problems with validation, adding id and name is required for this plugin to work correctly.

When it comes to jQuery, Elijah is an expert. If you want more information about jQuery then you should check out the jQuery Podcast (hosted by Elijah), or follow his tech tweets on twitter. Oh, did I mention he has a website too?



Getting Started with LINQ to XML

clock February 21, 2010 by author Michael Ceranski

man-pulling-hair-out I recently announced the WeBlog project. WeBlog is a blogging platform which will support multiple data providers. Out of the box I plan on offering SQL Server and XML support. Most people like the XML option because it drastically reduces web hosting costs. The only problem with XML is that it can be painful to work with. In general, XML makes me want to pull my hair out!

When building a blog you have a few basic entities that you need to deal with. Most typical blogs have posts, categories, tags, users and roles. Therefore I made an XML file to represent each of these items. However, for this tutorial I will focus on parsing the XML for categories. For a point of reference here is the XML structure that I am using to store category information:

 

<?xml version="1.0" encoding="utf-8"?>
<categories>
  <category id="19770e74-9ec9-4cde-b2ab-e5051aaaf348" description="Posts about my adventures with WeBlog" 
     parent="" name="WeBlog">
    <posts>
      <post id="0e05a782-7440-46e9-8fc4-e33fd51685e9" />
    </posts>
  </category>
  <category id="c223353c-1aef-4a46-afd1-cb61ab1a792d" description="" parent="" name="Tech">
    <posts>
      <post id="1aeaa3a2-6dfb-4a57-a633-0c1597e162ff" />
    </posts>
  </category>
<categories>

From the XML above you can deduce that each category has a ID, Name, Description and Parent. In addition, the category has related posts.

Since my application supports multiple data providers I first created an interface which all providers must adhere to. The methods defined in the interface return common objects. This allows me to abstract from the underlying data store. For example, here is the CategoryModel class which is really just an object representation of the XML:

public class CategoryModel {
    public Guid ID { get; set; }
    public Guid? Parent { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int PostCount { get; set; }
}

Selecting Data

The job of the XML data provider is to create a list of CategoryModel objects by reading the XML. Luckily, this process is relatively simple with LINQ to XML. First, we create an XDocument object and then loop through each category node. For each category we can read the attributes and elements to populate a CategoryModel object which can be added to a generic list:

 public List<CategoryModel> FindCategories()
 {      
     List<CategoryModel> categories = new List<CategoryModel>();
     XDocument xmlDoc = GetCategoryXML();
     var query = from category in xmlDoc.Descendants("category")
                 select new CategoryModel
                 {
                     ID = Guid.Parse(category.Attribute("id").Value),
                     Name = category.Attribute("name").Value,
                     Parent = (Guid?)(category.Element("parent") == null ? (Guid?)null :
                              Guid.Parse(category.Element("parent").Value)),            
                     Description = category.Attribute("description").Value,
                             PostCount = category.Descendants("post").Count()   
                 };
     categories = query.ToList();            
     return categories;
 }

Deleting Data

To delete a category we can use a similar approach. Again we need to create an XDocument and find the correct node by matching the id attribute of the category node. Once, we have the proper node selected we can call Remove() and then save the document:

public void DeleteCategory( Guid id )
{            
    XDocument xmlDoc = GetCategoryXML();
    var category = from x in xmlDoc.Descendants("category")
                where
                    x.Attribute("id").Value == id.ToString()
                select x;
    category.Remove();
    xmlDoc.Save(GetCategoryXMLFilename());   
}

Creating Data

Creating data is also a simple task. You create the category element and then assign the attributes and child elements. The syntax is a little bit different than the select and delete operations but overall it is fairly straightforward:

public void InsertCategory(CategoryModel source)
{
    XDocument xmlDoc = GetCategoryXML();
    XElement category = new XElement( "category",
                            new XAttribute( "id", source.ID.ToString() ),                                    
                            new XAttribute("description", source.Description),
                            new XAttribute( "parent", source.Parent == null ? "" : source.Parent.ToString() ),
                            new XAttribute("name", source.Name),
                        new XElement( "posts" ));
    xmlDoc.Element("categories").Add( category );            
    xmlDoc.Save(GetCategoryXMLFilename());
}

Updating Data

In order to update data you need to first find the correct element in the XML document. Once you have the element selected you can update the attributes and child values by using assignment operators. Once you make the updates you can save the document :

public void UpdateCategory(CategoryModel source)
{
    XDocument xmlDoc = GetCategoryXML();
    var category = ( from x in xmlDoc.Descendants("category")
                   where
                      x.Attribute("id").Value.Equals(source.ID.ToString(), StringComparison.CurrentCultureIgnoreCase)
                   select
                      x ).Single();
    category.Attribute("description").Value = source.Description;
    category.Attribute("name").Value = source.Name;
    xmlDoc.Save(GetCategoryXMLFilename());
}

As I mentioned before, XML is not my favorite format but LINQ to XML at least makes the process bearable. Hopefully this brief introduction will make you feel better about XML parsing. Maybe it will even save you from pulling your hair out!



Announcing WeBlog – A Next Generation Blogging Platform

clock February 19, 2010 by author Michael Ceranski

One of the best ways to keep your skills sharp as a developer is to start your own open source project. For the last 6 months or so I have been trying to come up with ideas on what kind of application I want to build. Since I enjoy blogging so much I decided that I will build my own blogging platform. There are a lot of good blogging platforms already available such as Wordpress, dasBlog and BlogEngine.NET. In order to make something comparative to these products will take a fair amount of time and effort. However, having a pet project like this is fun and I am really looking forward to working on it.

The WeBlog (pronounced We Blog) project is hosted on codeplex. I have already checked in some code and things are starting to take shape even though it is still early in the process. If you want to compile the code you will need need Visual Studio 2010. I figured there is no point starting a project on old technology so I went for the latest and greatest technology with MVC 2 and the .NET Framework 4.

Initial Feature List

Here are the list of features that I want to include in the first release. Once, I start gaining some momentum I will be looking for feedback from the user community.

  • Multiple Data Provider Support - Data can be stored in XML or in SQL Server. The data layer will be extensible so people can write their own providers. By having XML as an option, hosting is cheaper because you will not need to pay for a database.
  • Migration from BlogEngine.NET will be included in the first release. This is for selfish reasons :-)
  • Theme support – The goal is to make theme development a relatively simple task so I can get people in the community to develop new ones.
  • Full syndication support – RSS and Atom
  • Social networking support. Will start with twitter first. If time permits I will work on a mechanism to find tweets related to a post and add them to the comments section (a.k.a. Tweetbacks).
  • Anti-Spam features - Comments will use the ReCaptcha and Askimet to block spam comments. Comment moderation will be included.  
  • Gravatar support.
  • Trackbacks and Pingbacks.
  • Windows Live Writer Support – A must have, can't write posts without it!

Why Build Another Blogging Engine

First of all, there are a lot of different technologies and skills required to build a successful blog engine. Even if the project fails to gain popularity it will still be a good learning experience. The goal, is to build a new blogging platform that can be used as a showcase for modern .NET programming technologies.

Secondly, most of the developers that I admire have built or worked on a blog platform. The list includes Scott Hanselman (dasBlog) , Phil Haack (Subtext) and Rob Conery (see the video series on TekPub Build Your Own Blog—Rails ).

Thirdly, I really enjoy blogging. Its a way to give back to the community and share ideas and solutions with other developers. Unfortunately, It's not always easy to come up with ideas to write articles about. This project should provide me with plenty of content for the months (and possibly years) to come. As a side effect I will be building my very own blogging platform!



Dynamic Master Pages in MVC

clock February 17, 2010 by author Michael Ceranski

I have been working on a new project where I wanted to introduce the concepts of themes. This means that end users will be allowed to change the look and feel of the web application from a configuration menu. In order to deliver this functionality I needed to be able to dynamically change the master page on the fly.

My initial response was to use the Page PreInit event. The Page PreInit event is called write before the master page is assigned and therefore makes it a good candidate for dynamically assign the the master page. Unfortunately this is a Page level event. In order to use this solution I would need to override this method on every page. This would be a maintenance nightmare so I immediately eliminated this as a viable solution.

Another solution is to use the View method to assign the master page.

public ActionResult Index()
{
    return View("Index", MyApp.Properties.Settings.Default.Theme);
}

Unfortunately, this solution is also a maintenance nightmare because the change would have to be made in so many places.

Since I am using MVC, I figured that there must be an event somewhere in the controller class that I can override to dynamically assign the master page. After a little bit of reading I discovered the OnActionExecuted event. The OnActionExecuted event passes in a ActionExecutedContext object which can be used to access the ViewResult. The ViewResult class has a MasterName property which can be used to dynamically assign the master page. The code looks like this:

public class HomeController
{
     protected override void OnActionExecuted(ActionExecutedContext filterContext) {
         var action = filterContext.Result as ViewResult;
         if (action != null) {
             action.MasterName = MyApp.Properties.Settings.Default.Theme;
         }  

         base.OnActionExecuted(filterContext);
     }
}

 

Unfortunately, setting the master page in each controller is still not a very elegant solution. I wanted to centralize the code in a single location. Therefore, I decided to create a base class named BaseController that all the other controllers will inherit from.

public class BaseController : Controller
{
     protected override void OnActionExecuted(ActionExecutedContext filterContext) {
         var action = filterContext.Result as ViewResult;
         if (action != null) {
             action.MasterName = MyApp.Properties.Settings.Default.Theme;
         }  

         base.OnActionExecuted(filterContext);
     }
}

Now all my existing controllers can inherit the functionality by making a simple change:

public class PostController : BaseController

This was the perfect solution for my problem because the code is centralized in a single location and it does not require page or view level changes.



C# 4 – Named and Optional Parameters

clock February 13, 2010 by author Michael Ceranski

C# 4 has added two new features regarding parameters that should help improve developer productivity. Optional and named parameters give you some new ways to conquer old problems.

Optional Parameters

In the past when we wanted to create methods with varying numbers of parameters we would use overloaded methods. Overloading is the process of creating methods with the same name but of varying parameters. For example, say we have a method named GetRandomNumber which has three different method signatures:

static void Main(string[] args)
private static Random random = new Random();       

public static int GetRandomNumber(int max)
{
    return random.Next(max);
}

public static int GetRandomNumber(int min, int max)
{
    return random.Next(min, max);
}

public static int GetRandomNumber()
{
    return random.Next();
}

With C# 4, we now can consolidate these into a single method using optional parameters. Optional parameters allow you to declare and initialize a variable from within the method signature. Any parameter that has a default value assigned to it can be excluded when you invoke the method. Therefore we can consolidate our previous code to:

private static Random random = new Random();

public static int GetRandomNumber(int min = -1, int max = -1)
{            
    if (min == -1 && max != -1)
        return random.Next(max);
    else if (min != -1 && max != -1)
        return random.Next(min, max);
    else
        return random.Next();
}

The classic scenario for using optional parameters arises when you are interacting with COM interfaces like the Microsoft Office Automation APIs. If you have worked with the Office APIs before, then I am sure you are familiar with the infamous Type.Missing. Before C# 4, we would have to use the following code to format a range of cells with Excel:

var excel = new Microsoft.Office.Interop.Excel.Application();
excel.Workbooks.Add();
excel.Visible = true;

var format = Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1;

excel.get_Range("B10", "B40").AutoFormat(format, 
   //and now for 6 Type.Missing parameters....yuck
   Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

This code seems wasteful due to the fact that we have to fill in six of the seven parameters with Type.Missing. In C# 4, the call to the AutoFormat is simplified. We can basically avoid all the repetitive Type.Missing parameters and only specify the first parameters. This reduces the code to:

excel.get_Range("B10", "B40").AutoFormat( format );

Named Parameters

Finally, the other new feature in C# 4.0 is named parameters. Named parameters come in handy in situations when it is easy to forget what order the parameters come in. Going back to my first example I had a random number generator that took a min and a max value. If for some reason I reversed these parameters my methods would either return the wrong results or fail. However, with named parameters we can “bind” the parameters by specifying the parameter name and the value together.  Here is an example:

Console.WriteLine( GetRandomNumber( max : 100, min : 1 ) );

Admittedly, none of the features are earth shattering. We had workarounds for these issues before so its not like we are really gaining anything in terms of functionality. However, these new features will save you some typing. After all, these days its all about productivity!



About the author

MikeMy name is Michael Ceranski. I am a software developer from Buffalo NY. I have been writing code for over 10 years starting with Borland Delphi and later migrating to the .NET stack. I enjoy blogging about .NET, MVC and jQuery and I hope to spread my enthusiasm for technology by sharing my thoughts and ideas with you.

View my resume

Cumulus

This will be shown to users with no Flash or Javascript.

Sign in