Where is the RenderPartial method?

I was coding an demo application using the ASP.NET MVC Beta 1 and all the sudden I couldn’t access the RenderPartial method of the HtmlHelper from a Helper method I was writing. So where did it go?

I noticed that in the previous release the RenderPartial was a static method but in the Beta 1 they changed it to an Extension Method for the and it now lives in the namespace ’’‘System.Web.Mvc.Html’’’. So if you want to use this method all you need is to import this namespace in the classes where you are using the System.Web.Mvc.HtmlHelper class. In the Views you will notice that it keeps working as if nothing changed, that’s why the MVC’s development team has already added the System.Web.Mvc.Html namespace in the web.config. Here is the namespace node of the web.config the in MVC Beta 1.

<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="System.Linq"/>
   <add namespace="System.Collections.Generic"/>
 </namespaces>

 

Extension Methods

Extension methods are one of my favorite features of C# 3.0, they allow you to create new methods and plug them in classes already defined without having to derive them or even change it’s source code.

Everyone uses the DateTime class and a lot of those people have a class with handy methods to handle DateTime. Many of the handy methods would look better in the DateTime class but you can’t change it’s source code and you don’t want to derive from it and create a new DateTime class (of course). With extension methods you can plug these new methods in the DateTime class.

Let’s create a simple method named ’’‘DaysSince” that operates on two dates returning the number of days from one date to the other. The logic of the method is really simple:

    public static class DateUtil
    {
        public static int DaysSince(DateTime d1, DateTime d2)
        {
            TimeSpan ts = d1.Subtract(d2);
            return ts.Days;
        }
    }

You would use this class like this:

DateTime today = DateTime.Now;
DateTime pastDate = new DateTime(2008, 10, 9);
Console.WriteLine(DateUtil.DaysSince(today, pastDate);

My goal now is to be able to do this:

DateTime today = DateTime.Now;
DateTime pastDate = new DateTime(2008, 10, 9);
Console.WriteLine(today.DaysSince(pastDate));

To make this change just put a ’’‘this’’’ keyword in front of the first parameter of the static method. Now it should be like this:

public static class DateUtil
{
    public static int DaysSince(this DateTime d1, DateTime d2)
    {
        TimeSpan ts = d1.Subtract(d2);
        return ts.Days;
    }
}

That is it, you can now make a call to the DaysSince method from any DateTime instance variable.

Here a the rules for creating a ExtensionMethod:

  1. Create a public static class (you call call it anything you want)
  2. Create the method you want as a public static method
  3. The first parameter of the method must always the a ’’‘this’’’ keyword followed by the class you want to plug the method to and the name of the parameter
  4. Whenever you want to use the extension method the ’’‘namespace’’’ in which the class is into must be referenced

If you want to create a method ’’‘WeeksAgo’’’ that let you get a new DateTime x weeks before the a certain date all you need to do is this:

public static class DateUtil
{
    public static int DaysSince(this DateTime d1, DateTime d2)
    {
        TimeSpan ts = d1.Subtract(d2);
        return ts.Days;
    }
    public static DateTime WeeksAgo(this DateTime d1, int numberOfWeeks)
    {
        DateTime newDate = d1.AddDays(-numberOfWeeks * 7);
        return newDate;
    }
}

And then you can use it like this:

Console.WriteLine(today.WeeksAgo(2).ToString());

Really cool addition to your utility belt, isn’t it?

C# Custom Type Conversions

C# allows for implicit and explicit type conversion between classes when there is an inheritance situation. Something like this:

class BaseClass { }

    class DerivedFromBaseClass : BaseClass { }

    class Program
    {
        static void Main(string[] args)
        {
            BaseClass bc = new DerivedFromBaseClass(); //implicit conversion

            DerivedFromBaseClass dbc = (DerivedFromBaseClass)bc; //explicit conversion
        }
    }

Ok, this shouldn’t be anything new to know since this is a feature present in all object oriented languages I know. But now I want to talk about a stranger kind of conversion and for this I’ll have to mix apples and oranges.

Let’s define to classes: Apple and Orange.

class Apple
    {
        public string Farm { get; set; }

        public Apple(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an apple from the {0} farm", this.Farm);
        }

    }

    class Orange
    {
        public string Farm { get; set; }

        public Orange(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an orange from the {0} farm", this.Farm);
        }
    }

As you can see these two classes are totally unrelated, they don’t have any inheritance relation with each other.

Let’s convert Apples to Oranges using the cast-like sintax. This is possible using the keywords ’’‘operator’’’, ’’‘explicit’’’ in a static method that will do the conversion. Here are the changes to the Apple class so that it can be converted explicitly to an Orange.

class Apple
    {
        public string Farm { get; set; }

        public Apple(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an apple from the {0} farm", this.Farm);
        }

        public static explicit operator Apple(Orange o)
        {
            Apple a = new Apple(o.Farm);
            return a;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Orange o = new Orange("GreatSouth");
            Console.WriteLine(o.ToString());

            Apple a = (Apple)o; //explicit conversion
            Console.WriteLine(a.ToString());
        }
    }

Ok, it works. You can also do an implicit conversion but in this case you must be aware that it will also create (automatically) the explicit conversion. This is why you can’t define both these conversions in the same class. Following is the changes necessary to the Orange class so that you can make implicit and explicit conversions from Apples to Oranges:

class Orange
    {
        public string Farm { get; set; }

        public Orange(string farm)
        {
            this.Farm = farm;
        }

        public override string ToString()
        {
            return string.Format("I'm an orange from the {0} farm", this.Farm);
        }

        //this will allow implicit and explicit conversion
        public static implicit operator Orange(Apple a)
        {
            Orange o = new Orange(a.Farm);
            return o;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Apple a = new Apple("GreatSouth");
            Console.WriteLine(a.ToString());

            Orange o = a; //implicit
            Console.WriteLine(o.ToString());

            //or you could do it like this
            o = (Orange)a; //explicit
            Console.WriteLine(o.ToString());
        }
    }

I hope you found this interesting. Once again a know that my examples are not always the most thought out but I’m certain that you got the idea and will be able to put it work in a real life situation.

Set the Default Database in SQL Management Studio

Hi, this one is for the lazy programmers (like I). If you work a lot of time on the same project chances are that you know that every time you create a new query on SQL Server Management Studio it always sets your connection to the Master database. For those who are annoyed like me, you can configure the default database of your user to whatever you want.

  1. On the Object Explorer expand the Security folder.
  2. Expand the Logins folder.
  3. Right click your user and select Properties.
  4. Now select the Default Database you want.

That’s it!

ASP.NET MVC Beta was released

The beta version of the ASP.NET MVC framework is out of the oven! This is good news people, means that it’s only a few tweaks a way from the final version. ScottGu says on his blog that there are features to be implemented but the core is done and there won’t be any more major changes. Here are a few resources for you:

Download ASP.NET MVC Beta The asp.net site has a lot of articles and videos

Understanding how yield keyword works

If you work with C# you must know that in order to traverse a collection using the ‘foreach’ construct the collection must implement the IEnumerable interface. There’s a lot of documentation about that on the web so I won’t go into it. What I’d like to show you is an alternative to the IEnumerable interface using the ‘yield’ keyword. Take a look at this code:

public class Player
    {
        public string Name { get; set; }

        public Player(string name)
        {
            this.Name = name;
        }
    }

    public class Team
    {
        Player[] players = new Player[3];

        public Team()
        {
            players[0] = new Player("Gabriel");
            players[1] = new Player("Elisa");
            players[2] = new Player("Rafaela");
        }

        public IEnumerator GetEnumerator()
        {
            foreach (Player player in players)
            {
                yield return player;
            }
        }
    }

You can now test the code in a foreach like this:

 public static void TestYield()
        {
            Team team = new Team();
            foreach (Player player in team)
            {
                Console.WriteLine(player.Name);
            }
        }

This is really interesting, right? But how does it work? Shouldn’t the iteration through the players array start from scratch every time you call the method? Nope! This is where the magic of the yield comes in. Every time the yield is executed it will “pause the state” of the iteration and the next time the method is called it will resume the iteration from the next item. I could even rewrite my code in the following way and it would have the same effect:

public IEnumerator GetEnumerator()
        {
            yield return players[0];
            yield return players[1];
            yield return players[2];
        }

This code is only for demonstration purposes, I know that iterating the array like this wouldn’t be very smart :-) I just wanted to show you that the execution will pause.

This woks because in compile time the method using the yield will be transformed into a class which implements the IEnumerator interace and it’s stated will be maintained like any other object, that is why you get the impression the method is paused. It’s cool to understand how these things work under the hood, isn’t it?

MaskEditExtender causes problem with TextChanged event

Have you ever used the Ajax ControlToolkit MaskedEdit control? Last week I found an unexpected behavior with it.

Page:

<form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

        <asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
        <cc1:MaskedEditExtender ID="TextBox1_MaskedEditExtender" runat="server" 
            CultureAMPMPlaceholder="" CultureCurrencySymbolPlaceholder="" 
            CultureDateFormat="" CultureDatePlaceholder="" CultureDecimalPlaceholder="" 
            CultureThousandsPlaceholder="" CultureTimePlaceholder="" Enabled="True" 
            Mask="99-99-99" TargetControlID="TextBox1" ClearMaskOnLostFocus="False" 
            MaskType="Number">
        </cc1:MaskedEditExtender>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />

    </div>
    </form>

CodeBehind:

 protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox1.Text = "101208";
        }

        protected void Button2_Click(object sender, EventArgs e)
        {

        }

This page has one edit with a MaskEditExtender and two buttons. On the first button click I change the value of the TextBox. On the second button click I do nothing. If I click the first button then the second, the TextChanged event of the edit will fire. Funny, right? Here is the reason.

Let’s say you have a mask like this: 99-99-99. To apply the value to the textbox you do:


TextBox1.Text = "101208";

The resulting value on the web page will be: 10-12-08. Here is the catch: The mask is applied to the textbox only after the page is rendered using JavaScript. So the value for the control in the ViewState is 101208 and the value in the page is 10-12-08. When another postback occurs the framwork will detect that the value in the page is different from the value in the ViewState therefore it fires the TextChanged event when in fact the value hasn’t changed.

You can avoid this behavior by setting the value to the TextBox already with masked value.


TextBox1.Text = "10-12-08";

I hope this can help someone out there.

.Net Source Code

Have you ever wondered what’s behind all the classes you use in the .Net framework? Now that Microsoft opened the code you can have a pick at it.

I think that the looking at this code is a great way to learn and also be a better programmer since you will understand what happens behind the scenes. If you have a doubt if some API or control is the source of a performance problem you can take a look for yourself.

VisualStudio let’s you download the code as needed during debug but there’s a great tool called NetMassDownloader that will allow you to download all the code at once. The total size of the source code is about 170 MB.

There’s also a good post on the CodeProject site that will show how to set it up with VisualStudio: http://www.codeproject.com/KB/dotnet/netmassdownloader.aspx.

Have fun.