Paul Ulvinius Blog

From one developer to another

I’ve moved!

Posted by paululvinius on July 19, 2010

This blog is now running on my home server under a much better domain name, namely www.paululvinius.se/blog.

Please update your bookmarks, see you on the other side! ;)

Posted in Uncategorized | Leave a Comment »

My top 5 SEO and web site performance tools right now

Posted by paululvinius on November 12, 2009

  1. YSlow
  2. IIS SEO Toolkit
  3. SEOMoz
  4. Website Grader
  5. Pingdom tools

Not necessarily in any order, I rather think they complement each other pretty well.

Posted in Uncategorized | Leave a Comment »

The power of partial views, JQuery and AJAX in ASP.NET MVC

Posted by paululvinius on June 16, 2009

One really nice benefit you get from using ASP.NET MVC is that you get structured url:s out of the box looking like this: http://www.mycoolsite.com/Products/Create, Products/List, Products/Details, Categories/List, etc. Each url maps to an action within a “controller”, that returns a “view” that is supposed to render exactly what you expect from reading the url. So, “Products/Create” tells us that we are going to see a view, where we will be able to create a product – but enough with the obvious.

While url:s specific to user actions like this make everything very structured and maintainable, we often need to cross these boundaries. What if we want to create a “product” and a “category” from the same page? A page in a website often contains combinations of different responsibilities like this common scenario: While editing a product, a user realizes that he/she wants to create a new category for the product. To solve this nicely we might want to embed a “create category” part within the “create product” view. This is where “partial views” in ASP.NET MVC come in. Additionally, we probably don’t even want the web page to reload while adding categories, making it possible to fill in half a product form, realize that you need more categories, add these, and finally submit the product form. This is where AJAX and JQuery enter the scene.

Let’s take a look at how we can implement a pattern like this in ASP.NET MVC using the scenario mentioned above. Let me first point out that there are of course a bunch of ways you can implement this, but I’ll try to give you an example of a pretty neat implementation with a couple of benefits, along with some discussions on the way. The source code can be downloaded here.

So we need to manage products and categories. To shorten things down a bit, let’s say we already have all the basic pieces put together. We can list and create products in an ordinary fashion. When we create a new product we can select a category from a list of categories in a drop down list, but we can’t create new categories quite yet. So nothing except the basics so far (note that I’m not going through all the basics in this article, see other sources for that).

Products and categories are of course two different entities in the model. They should each have its own Controller class and of course separate views for GUI rendering, maintaining “separation of concerns”. Don’t forget the twist though, we want to evolve from the standard flow of things by making it possible for a user to add categories from the “create product” view. For clarity, let’s take a sneak peek at the final input form for adding a product and/or categories.

CreateaNewProduct

From a strict MVC viewpoint, one could argue that we have somewhat of a philosophical conflict here since we are mixing two “concerns” in the same view, namely products and categories. But luckily there are ways you can implement this and still be a good citizen. Most importantly, we need to break out the “Add new category” GUI-part (as seen in the image above) as something called a “partial view”. Think of a partial view as a slice of a page or like a user control in ASP.NET. In the process, we’ll also have to make a couple of design decisions and, of course, deal with some technical challenges as well.

So, let’s first create the “partial view” for adding a new category. This step is pretty straight forward. First, we need to create the CategoryController class with an action method that we’ll call “Create”, and that returns a PartialViewResult.

CategoryController1

Once you have created the action method, you can create the “view” by simply right-clicking somewhere inside the method and choose “Add View” from the context menu. The “Add View” dialog has an option for “Create a partial view”, which we want to do in this example.

image

In the “Create.ascx” that has now been generated for you, just add the html markup you need. Remember this is only a part of a page (again, think user control). In our case, this is where we want to create the html form for adding a new category.

CreateCategory

The next step requires decision-making. We now want to use the newly created partial view in the hosting view. Basically, ASP.NET offers two ways of doing this.

Use RenderPartial when you need to render something that naturally is a part of the hosting view and its Model (if present). You can pass the entire model or of course any subset of it, or you can choose not to pass any model at all. Examples:

<% Html.RenderPartial("partialViewName"); %>
or if you need to pass the model…
<% Html.RenderPartial("partialViewName", Model); %>

Alternatively, use RenderAction when you need to render something that naturally is not a part of the hosting view or its Model. This is the one we are going to use in this example, since adding categories doesn’t necessarily have anything to do with adding products. We just happened to realize that we wanted to host one within the other for the soul purpose of making a more efficient user interface. Example of use:

<!— Invoke the “Create” action method in the “Category” controller and render its partial view –>
<% Html.RenderAction("Create", "Category"); %>

You can find blog posts that focuses on the “one versus the other” discussion, like here or here.

The next step is to make sure that we can post the “Add category” –form and handle the return logic. This requires some server side and some client side programming. We are going to communicate with data only, through JSON (so no formatting). Before digging into server side, let’s take a look at the client side for a moment. We can either choose to go entirely with JQuery, or we can use JQuery together with some built-in Ajax helpers in the Mvc framework. Let’s go with the latter, it produces less code and makes more use of the framework we’re using. The JQuery-only approach could provide a higher level of control though, and if you are a true JQuery friend this choice could be the more attractive one. Note: The downloadable source code for this article also includes the “JQuery-only approach, hidden in a html comment at the bottom of Create.ascx.

So, we are going to use the built-in Ajax helper method “BeginForm” (in System.Web.Mvc) to create the html form. This helper renders a script in the forms “onsubmit” event that takes care of the AJAX call to our server. The new version of the Create.ascx looks like this:

CreateCategoryAjax

The first BeginForm-parameter decides the name of the action method to invoke (we haven’t implemented the action method quite yet). The second one takes an AjaxOptions object that we can fill with settings (coverage of the AjaxOptions class is out of scope for this article. For more info, go to the AjaxOptions class reference). You can use the OnComplete property to provide the name of a JavaScript function to call when the server responds.

CreateCategoryScript

This function will get called and passed a Sys.Mvc.AjaxContext JavaScript object (here named “context”). The AjaxContext object has a get_data() method that returns the JSON result that was returned from the server. First, we need to deserialize the string JSON result to a JavaScript object. For this we can use the built-in “Sys.Serialization.JavaScriptSerializer.deserialize()” method. The rest is just some code to add the new category in the drop down list, select the new category and clear the category name textbox.

On the server side we need to add the action method that the client code will invoke.

JsonCreate

To avoid any trouble, choose a different name than the (non-post) method that we just named Create earlier. If they have the same name, the RenderAction method will choose the method with the same http verb as the hosting view, and this is not always what you want. All of a sudden you could end up getting a view that tries to render pure JSON data as a GUI :) So, to take control over what action method gets used and when, the simplest way is to use unique names in these cases. However, there are also other ways to go around this issue.

That’s it, feel free to download the complete source code of course. With the helper methods of ASP.NET MVC in combination of partial views and some JQuery, there aren’t that many steps to take in order to add powerful AJAX enabled functionality to your web sites.

Posted in Ajax, ASP.NET MVC, C#, JavaScript, JQuery, Visual Studio | 4 Comments »

How you dynamically submit a ASP.NET MVC AJAX Form from JavaScript and JQuery

Posted by paululvinius on March 3, 2009

I ran into a problem the other day when trying to submit a form generated with Ajax.BeginForm(…). I have an <a> -tag with a click-event, so when you click the <a> -tag the form is submitted. First of all, if you use a submit button or image submit button there is no issue, this only applies if you want to submit the form programmatically from JavaScript. The BeginForm method generates a form with inline JavaScript in the forms onsubmit attribute. The problem you run into is that this code never gets executed when you call the forms submit method directly from JavaScript.

To get around this issue, you can bind a function to the submit event that contains the same code as the code in the onsubmit attribute. You can do this as soon as the DOM is ready to be manipulated:

image

Feel free to copy/paste from here:
$("form").submit(function(event) { eval($(this).attr("onsubmit")); return false; });

The key here is to pass the event parameter (otherwise it will work only in IE but not in FF for some reason), use eval to run the onsubmit code and finally return false to prevent the form from being submitted in a traditional non-Ajax manner.

Now you should be able to submit the form programmatically like below:
<a onclick="$(this).parents(‘form’).submit();return false;">Send</a>
(this code only works if the <a> –tag is located within the form)

If anyone finds another solution to this problem please let me know, but in the mean time this works fine.

Posted in Ajax, ASP.NET MVC, JavaScript, JQuery | 8 Comments »

First thoughts – CRUD scaffolding in the ASP.NET MVC 1.0 Release Candidate (RC)

Posted by paululvinius on March 1, 2009

For quiet a while a was trying to come up with something really good to write about on this first “dramatic” blog post. Finally I came to my senses, that’s not how you blog in the first place! Instead, here is just a random topic from my mind right now, to break the ice if nothing else :)

Credit to the CRUD scaffolding in the ASP.NET MVC 1.0 Release Candidate (RC)! The support for T4 templating is a cool feature and is especially useful in projects where you have lots of pages that shares the same design and layout, or if you’re in a large company and you want everyone to get the same default look and feel when new views are created across projects.

And the but…

Don’t know if I’m the only one, but it seems like my projects never end up being repetitive enough for me to actually use these features. At the end of the day, every new page (or view) I create turn out to share almost nothing with the previous one. Of course this totally depends on the project anyways, they are really awesome features, and maybe I just need to learn how to make better use of them.

Posted in ASP.NET MVC, Visual Studio | Tagged: , , | Leave a Comment »

Open source tag cloud in C# 3.0

Posted by paululvinius on September 20, 2008

Check out my Tag cloud open source project at http://www.codeplex.com/TheTagCloud.

The code is written in C# 3.0 using some of the latest language features like LINQ, object initializers and Lambda expressions.

Posted in ASP.NET, ASP.NET MVC, C# | Leave a Comment »

Issue with HR-XML schema in SQL Server 2005

Posted by paululvinius on November 23, 2007

We are developing a HR-software which stores its data as HR-XML (the Candidate schema) directly in a database table using SQL Server 2005. The XML-column is typed to the schema so that we get schema validation and data type storing optimization. In our tests everything runs fast, especially with the XML-indexes the database provides. The only issue we have encountered is that the XML schema has some string patterns which SQL Server also warns us about:
Warning: Type ‘http://ns.hr-xml.org/2007-04-15:LocalDateType&#8217; is restricted by a facet ‘pattern’ that may impede full round-tripping of instances of this type.

The problem lies in the HR-XML type “LocalDateType”, which isn’t compatible with SQL server 2005 since it forces you to follow the pattern “\d\d\d\d-\d\d-\d\d”. SQL Server 2005 doesn’t allow this because there is no “Z”-postfix decorating the date. In SQL Server 2005, values of type xs:datetime, xs:date, and xs:time must be specified in ISO 8601 format and include a time zone (http://msdn2.microsoft.com/en-us/library/ms345115.aspx, chapter: “Using xs:datetime, xs:date, and xs:time”).
E.g. the element:

“Candidate/CandidateProfile/PersonalData/PersonDescriptors/BiologicalDescriptors/DateOfBirth” is defined with the type LocalDateNkNaType which in turn refers to the types “LocalDateType NotKnownLiteral NotApplicableLiteral”. The only usable choice here is obviously LocalDateType, which is not supported by SQL Server 2005. We chose to store DateOfBirth somewhere else, in favor of altering the schema. Its tempting to just add that ‘Z’ in the HR-XML schema, but being 99.99% compatible is just annoying.

Posted in Uncategorized | Leave a Comment »

Use FxCop to enhance your .NET code

Posted by paululvinius on August 11, 2007

I finally dusted off my copy of Microsoft FxCop (a program that analyzes your assemblies with reflection and finds out more stuff about your code than you probably want to know). The best thing about this tool is that its really clever. It analyzes design, performance, naming conventions, security and localization. It thereby covers many steps in the project life-cycle. During design, it can help you with design implementation decisions. During implementation it can help you with code optimization and see to that you follow naming conventions for managed code. During testing it can function as a complement to static testing / code review. Run it on your assemblies from time to time, I bet it will help you find some nasty bugs.

By following the naming conventions, you not only make sure we speak the same programming language, but also the same “dialect” if you will. They are formed to increase readability and maintainability and by implementing them you also tend to write more consistent code.

Of course, its a lot about making a decision about what rules are reasonable in a given project. But even in the process of doing that, you will find yourself considering some questions that are easily forgotten. If nothing else, it can be an educational trip to the Microsoft .NET Framework Design Guidelines which the tool is based upon.

Posted in Uncategorized | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.