Registering a namespace for all Razor views

When you want use your own code generating classes like HtmlHelpers in a Razor view, you can register the namespace at the beginning of the Razor view like this:

@using My.Custom.Namespace

But what when you want to use a certain class in almost all of your views? Well, of course you can manually add the using statement to each view, but there is another way. You can add the namespace in your Web.Config file. The catch here is that you don’t need to add it to the Web.Config file in the root of your project, but to the Web.Config file in the View directory.

Just add it to this part of the file:

<system.web.webPages.razor>
	<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
	<pages pageBaseType="System.Web.Mvc.WebViewPage">
		<namespaces>
			<add namespace="System.Web.Mvc" />
			<add namespace="System.Web.Mvc.Ajax" />
			<add namespace="System.Web.Mvc.Html" />
			<add namespace="System.Web.Routing" />
			<add namespace="My.Custom.Namespace" />
		</namespaces>
	</pages>
</system.web.webPages.razor>
Posted in Development | Tagged , | 2 Comments

Escaping curly braces in String.Format

Most of you will know that you can use String.Format to insert and format objects into a string. For example:

int distance = 5;
int time = 15;
DateTime when = new DateTime(2011, 3, 7);

string output = String.Format("You have run {0} miles in {1} minutes on {2:dd/MM/yyyy}.",
    distance,
    time,
    when);

Console.WriteLine(ouput);

This will print “You have run 5 miles in 15 minutes on 03/07/2011″.

But what should you do when you need curly braces in your string? Let’s say you want to do this:

string output = String.Format("The delimiter {text} was found {0} times.", 5);
Console.WriteLine(output);

When you try this, it will give you a System.FormatException saying “Input string was not in a correct format”. That’s because of the the {text} in our string. To solve this, the curly braces need to be escaped. But how? Escaping them with a backslash won’t work. The solution is actually very simple: you need to escape curly braces with… curly braces!

To make our example work, we just have to do this:

string output = String.Format("The delimiter {{text}} was found {0} times.", 5);
Console.WriteLine(output);

This will print “The delimiter {text} was found 5 times.”, just like we want it to.

Posted in Development | Tagged | Leave a comment

How to identify CMYK images in ASP.NET using C#?

I’m trying to create a small and reusable library to resize and save images in ASP.NET applications. Because some browsers can’t display CMYK images, I thought it would be nice to make my library convert CMYK images to RGB when saving them.

My library currently has an Image class, which is basically a wrapper around the System.Drawing.Bitmap class. The System.Drawing.Bitmap class contains a Flags attribute (actually, this property belongs to the System.Drawing.Image class, the base class of Bitmap). This property returns an integer that represents a bitwise combination of System.Drawing.Imaging.ImageFlags. The ImageFlags enumeration has a ColorSpaceCmyk value. If this value is set in the Flags property of an Image instance, that image should be a CMYK image. Unfortunately, the bitwise combination returned by the Flags is bugged.

I have created three images to test this: cmyk.jpg, rgb.jpg and gray.jpg. These are respectively CMYK, RGB and Grayscale images.

Next, I created a console application with the following tt:

static void Main(string[] args)
{
    Bitmap bmpCMYK = new Bitmap("cmyk.jpg");
    Bitmap bmpRGB = new Bitmap("rgb.jpg");
    Bitmap bmpGray = new Bitmap("gray.jpg");

    Console.WriteLine("\t\tRgb\tCmyk\tGray\tYcbcr\tYcck\tPixelFormat");

    Console.WriteLine("cmyk.jpg\t{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceRgb),
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceCmyk),
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceGray),
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceYcbcr),
        IsSet(bmpCMYK, System.Drawing.Imaging.ImageFlags.ColorSpaceYcck),
        bmpCMYK.PixelFormat);

    Console.WriteLine("rgb.jpg\t\t{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceRgb),
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceCmyk),
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceGray),
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceYcbcr),
        IsSet(bmpRGB, System.Drawing.Imaging.ImageFlags.ColorSpaceYcck),
        bmpRGB.PixelFormat);

    Console.WriteLine("gray.jpg\t{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceRgb),
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceCmyk),
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceGray),
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceYcbcr),
        IsSet(bmpGray, System.Drawing.Imaging.ImageFlags.ColorSpaceYcck),
        bmpGray.PixelFormat);

    bmpCMYK.Dispose();
    bmpRGB.Dispose();
    bmpGray.Dispose();

    Console.ReadLine();
}

private static bool IsSet(Bitmap bitmap, System.Drawing.Imaging.ImageFlags flag)
{
    return (bitmap.Flags & (int)flag) == (int)flag;
}

This doesn’t really do what it’s expected to do:
Results of testing the Flags property

As you can see, both the CMYK and RGB image have ColorSpaceRgb set to true and the ColorSpaceCmyk set to false.

Apparently, this is a known issue. And what’s even worse, whether ColorSpaceCmyk is set to true of false, depends on the operating system the code is run on!

I haven’t been able to find a solution to this problem, so I posted my problem on StackOverflow. Hopefully, I’ll soon get an answer.

Posted in Development | Tagged , | Leave a comment

Anonymous types and the ItemDataBound event

As you will probably know, when you bind a list of items to a Repeater, you can then convert the DataItem to the type of that item in the ItemDataBound event of the Repeater like this:

public class Person
{
    public string Name { get; set; }
	public string Email { get; set; }
	public int Age { get; set; }
}

public void Page_Load(object sender, EventArgs e)
{
	List<Person> people = new List<Person>
    {
        new Person { Name = "Bob", Email = "bob@example.com", Age = 28 },
        new Person { Name = "John", Email = "john@example.com", Age = 31 },
        new Person { Name = "Phil", Email = "phil@example.com", Age = 24 }
    };

    MyRepeater.ItemDataBound += new RepeaterItemEventHandler(PersonDataBound);
    MyRepeater.DataSource = people;
    MyRepeater.DataBind();
}

public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Person p = e.Item.DataItem as Person;

        string name = p.Name;
        string email = p.Email;
        int age = p.Age;
    }
}

But what when you aren’t databinding to a list of a concrete class but to a list of an anonymous type? Well, before .NET 4.0 you had to that like this:

public void Page_Load(object sender, EventArgs e)
{
	var people = from p in DB.GetPeople()
	             select new { Name = p.Name, Age = p.Age };

    MyRepeater.ItemDataBound += new RepeaterItemEventHandler(PersonDataBound);
    MyRepeater.DataSource = people;
    MyRepeater.DataBind();
}

public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        string name = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "Name"));
        int age = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "Age"));
    }
}

Using the new .NET 4.0 dynamic type, this can be done a lot easier:

public void PersonDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
		dynamic person = e.Item.DataItem as dynamic;

        string name = person.Name;
        int age = person.Age;
    }
}

Posted in Development | Tagged | 2 Comments

Some of my extension methods

I’m really starting to appreciate extension methods. They provide an easy way to perform small common tasks you would usually put in static utility classes. Below you can find some I use regularly. The first two are extension methods to DateTime. The last two are for the WebControl class. This is the base class for a lot of, well, WebControls in ASP.NET.

When building a website or a web application, letting users enter a date is a common scenario. Often you have to check if the date is between a minimum and a maximum date. When storing a date entered by a user in MS SQL Server, you actually have to perform such a check, because MS SQL Server can’t store DateTime values smaller than 1/1/1753. To make this easier, I have come up with these two extension methods.

namespace System
{
    public static class ExtensionMethods
    {
        public static bool IsBetween(this DateTime date, DateTime firstDate, DateTime secondDate)
        {
            return (date >= firstDate && date <= secondDate) || (date <= firstDate && date >= secondDate);
        }

        public static bool IsValidSqlDateTime(this DateTime date)
        {
            return date.IsBetween((DateTime)System.Data.SqlTypes.SqlDateTime.MinValue, (DateTime)System.Data.SqlTypes.SqlDateTime.MaxValue);
        }
    }
}

These can be used like this:

DateTime dateToCheck = new DateTime(1492, 10, 12);
DateTime firstDate = new DateTime(1400, 1, 1);
DateTime secondDate = DateTime.Now;

bool isWithinRange = dateToCheck.IsBetween(firstDate, secondDate);
bool isValidSqlDateTime = dateToCheck.IsValidSqlDateTime();

The next two extension methods concern the WebControl class. A few examples of controls that inherit from this class are HyperLink, TextBox, Label and Panel. The WebControl base class provides all these controls with the CssClass property. You can assign a string to this property and that string will be rendered as the class attribute of the HTML tag. Now, a lot of the times when you use the CssClass property, you’re not assigning just one class. You’ll often be assigning multiple classes and in a lot of cases you’ll be assigning different classes based on certain conditions. This is not that handy when you have also assigned a default class in the ASP.NET markup:

<asp:Label ID="MyLabel" runat="server" CssClass="defaultClass" />

Let’s say you want to add different classes to that based on whether the current user is logged in or not. To do that, you would have to repeat the defaultClass like this:

if (userIsLoggedIn)
{
    MyLabel.CssClass = "defaultClass loggedIn";
}
else
{
    MyLabel.CssClass = "defaultClass anonymous";
}

I don’t really like that. That’s why I wrote these extension methods.

namespace System.Web.UI.WebControls
{
    public static class ExtensionMethods
    {
        public static void AddCssClass(this WebControl control, string cssClass)
        {
            control.CssClass += " " + cssClass;
        }

        public static void RemoveCssClass(this WebControl control, string cssClass)
        {
            var classes = from c in control.CssClass.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                          where !c.Equals(cssClass, StringComparison.OrdinalIgnoreCase)
                          select c;

            control.CssClass = String.Join(" ", classes);
        }
    }
}

You can use them like this:

if (userIsLoggedIn)
{
    MyLabel.AddCssClass("loggedIn");
}
else
{
    MyLabel.AddCssClass("anonymous");
}

if (specialCase)
{
    MyLabel.RemoveCssClass("defaultClass");
}

I hope this is useful to you!

Posted in Development | Tagged , | 1 Comment

First look at EF Magic Unicorn

Magic Unicorn

A few days ago, Microsoft released CTP4 of the Entity Framework Feature. In his blog post demonstrating the new features of the EF CTP4, Scott Hanselman proposed a better name than the official “Microsoft ADO.NET Entity Framework Feature 4″: “EF Magic Unicorn Edition”. I quite like that name, so I’ll use it from now on.

The biggest addition the Entity Framework is the ability to use a code-first approach. This means that you just write your basic (POCO) classes representing your model and let the EF Magic Unicorn take care of all the rest. No fiddling around with designers or XML bindings. Instead you can just concentrate on your code!

I thought this looked rather cool, so I decided to give it a go and it only took me a few minutes to get a working example.

Creating a new ASP.NET MVC 2 project

Let’s start with creating a new blank ASP.NET MVC 2 project. Because I want to see how EF Magic Unicorn handles many-to-many associations and self-referencing associations, we’ll to use something very common: posts and categories. A post can belong to multiple categories and a categories can also have multiple posts. A category can also have a parent category and multiple child categories.

Adding the model classes

Now that we have our blank project and we know what we want to test, let’s add two classes to the Models folder:

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Text { get; set; }
    public DateTime PublishDate { get; set; }

    public virtual ICollection<Category> Categories { get; set; }

    public Post()
    {
        Categories = new List<Category>();
    }
}

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }

    public virtual Category ParentCategory { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
    public virtual ICollection<Category> ChildCategories { get; set; }

    public Category()
    {
        ChildCategories = new Lis<Category>();
    }
}

Adding a reference to the Magic Unicorn

We need to download the EF Magic Unicorn. You can grab the installer here. When you run the executable, you can specify where you want to install the Magic Unicorn. Remember that location.

When the installation is complete, choose to add a reference to your ASP.NET MVC 2 project, browse to the Magic Unicorn installation directory and select the Microsoft.Data.Entity.CTP.dll file.

Creating the DbContext

Now that we have our classes in place, we somehow need to tell the Magic Unicorn about them. This also turns out to be very easy indeed. All we need to do is add a class that inherits from the DbContext class (this is new in EF Magic Unicorn) and add a generic DbSet collection (also new in EF Magic Unicorn) for each model class.

using System.Data.Entity;

public class MagicUnicornContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Category> Categories { get; set; }
}

Adding a connectionstring

At this point, we still haven’t created a database. And we won’t need to! We just have to tell the trusty Magic Unicorn where it can create one for us. To do that, we only have to add a connectionstring to the Web.Config with the same name as our DbContext: MagicUnicornContext.

<add name="MagicUnicornContext"
     connectionString="Data Source=AITWS13\sqlexpress;Initial Catalog=MagicUnicorn;Integrated Security=True;Pooling=False"
     providerName="System.Data.SqlClient" />

Adding a controller to test everything

Now we can add a controller to see if everything works. Just add a controller called HomeController, and inside the Index() action method, you can add the following code:

public ActionResult Index()
{
    // Create a new Category
    var parentCategory = new Models.Category
    {
        Name = "Parent category"
    };

    // Create a new Category and set the first one as its parent
    var firstChildCategory = new Models.Category
    {
        Name = "Child category 1",
        ParentCategory = parentCategory
    };

    // Create a new Category and set the first one as its parent
    var secondChildCategory = new Models.Category
    {
        Name = "Child category 2",
        ParentCategory = parentCategory
    };

    // Add the second and third Category to the ChildCategories of the first Category
    parentCategory.ChildCategories.Add(firstChildCategory);
    parentCategory.ChildCategories.Add(secondChildCategory);

    // Create a new Post
    var post = new Models.Post
    {
        Title = "New post",
        Text = "The contents of the first post",
        PublishDate = DateTime.Now,
    };

    // Add the third Category to the list of Categories of the Post
    post.Categories.Add(secondChildCategory);

    // Create an instance of our context
    Models.MagicUnicornContext muc = new Models.MagicUnicornContext();

    // Add the Post and the Categories
    muc.Posts.Add(post);
    muc.Categories.Add(parentCategory);
    muc.Categories.Add(firstChildCategory);
    muc.Categories.Add(secondChildCategory);

    // Save everything
    muc.SaveChanges();

    return View();
}

What we do here is create a new post and three new categories. The first category becomes the parent of the other two categories. The second child category also gets added to list of categories of the post. Next we create a new instance of our MagicUnicornContext, we add the post and the categories to the context and call SaveChanges() on it.

Running it

After giving everything a final check and adding a default view, you can hit Ctrl-F5 and if all goes well, a blank browser window will apprear. It should be empty because our default view is still empty. So that means that no errors have occured!

Check the database

Now we only have to see if the Magic Unicorn actually created our database. You can fire up SQL Server Management Studio, or use the Server Explorer in Visual Studio, connect to your SQL Server and check out the databases. There should be database called MagicUnicorn that wasn’t there before!
Database diagram
When you open the tables, you will see that the Post, the three Categories and the links between were added as well.

Further reading

For more detailed guides about the EF Magic Unicorn, you can have a look at these excellent articles:

Posted in Development | Tagged | 3 Comments

Is formatting strings in a View evil?

Yesterday, I ran into an interesting post by Chris Brandsma about his personal rules when dealing with Views in ASP.NET MVC. While he sure has some valid points, I don’t agree with everything he says in that post. Apparently, I’m not the only one since Jeff Putz beat me to it and made a post on his blog about the same doubts that I have about Chris’ ideas.

The first thing I don’t agree with is that Views shouldn’t do any formatting or parsing. According to Chris, DateTime values should be formatted by the ViewModel and passed to the View as strings. The problem I have with this way of working is: where do you draw the line? Does that mean you also have to let the ViewModel format decimal values representing a price and pass that to the View as a string? Ultimately, it implies that a ViewModel should only have strings for properties. As Jeff points out, this would also mean HtmlHelpers are to be avoided as well. I don’t think there’s anything wrong with letting the View format a DateTime value. Making calculations is something else of course.

The second thing I don’t agree with is that the ViewModel should also pass in the CSS classes of the HTML elements. For me, that’s at least one bridge too far. I agree that you shouldn’t put business logic in the View, but putting markup elements in the ViewModel shouldn’t be done either.

Of course, these are just my virtual two cents on the subject.

Posted in Development | Tagged | 1 Comment

Order on multiple fields with LINQ

This is one of the things I tend to forget when I need to order a list on multiple fields using LINQ. I often start with chaining OrderBy() methods, only to realize that that doesn’t work. When you do that, only the last OrderBy() is taken into account.

What you need to do is start with an OrderBy() (or OrderByDescending()) and then chain ThenBy() (or ThenByDescending()) methods. It actually makes some sense and it is certainly easier to read. I bet I’m not the only one forgetting this.

List<Fruit> fruits = new List<Fruit>
{
	new Fruit { Name="Apple", Color="Red" },
	new Fruit { Name="Apple", Color="Yellow" },
	new Fruit { Name="Plum", Color="Purple" },
	new Fruit { Name="Strawberry", Color="Red" },
	new Fruit { Name="Banana", Color="Yellow" },
	new Fruit { Name="Apple", Color="Green" },
	new Fruit { Name="Orange", Color="Orange"},
	new Fruit { Name="Tangerine", Color="Orange" },
	new Fruit { Name="Lemon", Color="Yellow" }
};

// This one is only ordered by Name
var sorted = fruits.OrderBy(f => f.Name);

// This one is only ordered by Color, not by Name
var sorted2 = fruits.OrderBy(f => f.Name).OrderBy(f => f.Color);

// This one is ordered by Name and then by Color
var sorted3 = fruits.OrderBy(f => f.Name).ThenBy(f => f.Color);
Posted in Development | Tagged | Leave a comment

The plans for 2010 – Update

We’re halfway into 2010 already so it’s time for a little update about my plans for this year. Quite a few things have changed since the original post.

Get certificated

I have decided not to go for the MCTS 70-536 – Application Development Foundation and MCTS 70-562 – Microsoft .NET 3.5, ASP.NET Application Development certificates. Why? Because there is a new certificate: the 70-515 Web Applications Development with Microsoft .NET Framework 4 certificate. Since it covers the .NET 4.0 framework and ASP.NET MVC and doesn’t require you to get another certificate first, it is a lot more interesting.

So as soon as there is a book covering the 70-515 exam, I’m going to get started!

Build a demo application in ASP.NET MVC 2

This hasn’t changed. I still plan to build a small sample application and I finally have an idea what that application might be.

Build a demo application with a NoSQL solution

In the original post, I talked about using MongoDB, CouchDB and/or db4o in an application.

I still want to use a NoSQL solution, but instead of using one of the above, I think I will give Raven DB a try. Raven is an open source document database for the .NET/Windows platform. It is developed by the incredible Ayende Rahien. Since it was built with .NET in mind, it should be a lot easier to use than MongoDB, CouchDB and db4o.

Learn some more about continuous integration

I have started to read some more about continuous integration and it seems it can be quite complicated. I think it might be better to start learning/using a basic part of continuous integration first: source control and versioning. I’m not sure whether to use git or Mercurial. Thankfully, Tekpub has video series about them both.

Posted in Development | Tagged | Leave a comment

Busy times

There hasn’t been a lot of activity around here fore the last few weeks, but I have my reasons. Very good reasons even.

On June 02, 2010 I’m getting married and a few days later I’m going to New York for a week. Both of these require a lot of preparation so there hasn’t been much time to write blog posts.

I do have a few draft posts queued up though, so as soon as I’m back from New York I’m going finish them. At least, that’s the plan.

Let’s hope Giant Cloud of Ash from the Eyjafjallajökull doesn’t mess things up.

Posted in General | Leave a comment