Web Api - Testing with HttpClient

The Web Api is a project that has been on my radar since I first saw Glenn Block’s presentation last year on MIX. I was only recently though, when we decided to really take on REST at work that I really started looking into with in depth.

One aspect that caught my attention was the HttpClient. I’ve been using RestSharp for a while and I have to say that I am really happy with it. I still wanted to test the new HttpClient and see how it compared to RestSharp.

So let’s say I want to call a super duper service that returns a Guid. Here is a VERY simple example of how I would implement a client using RestSharp:

public class GuidClient
{
    private readonly IRestClient _client;

    public GuidClient(IRestClient client)
    {
        _client = client;
    }

    public string Execute()
    {
        var request = new RestRequest();

        RestResponse response = _client.Execute(request);

        if (response.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("Invalid response");
        }
        
        return response.Content;
    }
}

As I said, it's a very simple example. The important part here is that if I get a valid response I want to return the content (which should be the GUID), otherwise I want to throw an Exception. Here are the tests:

[TestFixture]
class GreetingClientTest
{
    [Test]
    public void Throws_exception_if_response_not_OK()
    {
        var mock = new Mock<IRestClient>();
        mock.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
            .Returns(new RestResponse {StatusCode = HttpStatusCode.BadRequest});

        var client = new GuidClient(mock.Object);
        Assert.Throws<Exception>(() => client.Execute());
    }

    [Test]
    public void Returns_content_if_response_is_OK()
    {
        string content = Guid.NewGuid().ToString();
        var mock = new Mock<IRestClient>();
        mock.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
            .Returns(new RestResponse
                         {
                             StatusCode = HttpStatusCode.OK,
                             Content = content
                         });

        var client = new GuidClient(mock.Object);
        var result = client.Execute();
        Assert.AreEqual(content, result);
    }
}

It’s easy to notice how simple the RestSharp abstractions make our job of testing. Mock the IRestClient to return the desired RestResponse and it's good to go.

When creating my first client using the HttpClient I wanted to pass the HttpClient as a constructor parameter in the same manner I did with IRestClient. That’s when I noticed that the HttpClient doesn’t implement any interfaces other than IDisposable. Hum, no interfaces? So how can I mock this thing? Good thing Glenn Block was ready to help on twitter:

“@gblock: @perezgb @howard_dierking with web api you can pass a fake message handler to the client to test.”

So Glenn also sent me the code from one of his talks where he creates a fake handler in order to help testing with the HttpClient. So taking his code I created an HttpClient version of my service and tests:

public class GuidHttpClient
{
    private readonly HttpClient _client;

    public GuidHttpClient(HttpClient client)
    {
        _client = client;
    }

    public string Execute()
    {
        var request = new HttpRequestMessage { RequestUri = new Uri("http://localhost/guidservice") };
        Task<HttpResponseMessage> task = _client.SendAsync(request);
        HttpResponseMessage response = task.Result;
        if (response.StatusCode != HttpStatusCode.OK)
        {
            throw new Exception("Invalid response");
        }
        return response.Content.ReadAsStringAsync().Result;
    }
}

And here are the tests:

[TestFixture]
public class GuidHttpClientTest
{
    [Test]
    public void Throws_exception_if_response_not_OK()
    {
        var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
        var httpClient = new HttpClient(new FakeHandler
                                            {
                                                Response = response,
                                                InnerHandler = new HttpClientHandler()
                                            });

        var client = new GuidHttpClient(httpClient);
        Assert.Throws<Exception>(() => client.Execute());
    }

    [Test]
    public void Returns_content_if_response_is_OK()
    {
        string content = Guid.NewGuid().ToString();
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StringContent(content);

        var httpClient = new HttpClient(new FakeHandler
        {
            Response = response,
            InnerHandler = new HttpClientHandler()
        });

        var client = new GuidHttpClient(httpClient);
        string result = client.Execute();
        Assert.AreEqual(content, result);
    }
}

And this is the fake message handler:

public class FakeHandler : DelegatingHandler
{
    public HttpResponseMessage Response { get; set; }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                           CancellationToken cancellationToken)
    {
        if (Response == null)
        {
            return base.SendAsync(request, cancellationToken);
        }

        return Task.Factory.StartNew(() => Response);
    }
}

Ok, so mission accomplished! I was able to write my service and tests using the HttpClient. One thing I really like is the russian doll model, kinda like the one you can find on FubuMVC, that the DelegatingHandler makes possible. On the other hand, I still like my RestSharp tests better, they seem cleaner but maybe that’s just me. It's the way I've been writing code for a while and I feel comfortable with it. Some times though, we have to push ourselves out of our comfort zone and try different things, right?

Please take all this with a grain of salt as I don’t consider myself to be any kind of expert in the ASP.NET Web Api. Also this is only my first stab at the HttpClient, I plan to keep going with my tests. I'll let you know if I come across anything interesting ;-)

Installing a Topshelf Service using Wix

The idea of this post is not to introduce Topshelf or Wix. If you are here I assume you figured out how cool Topshelf is, you created your service but when it came time to install it using Wix your service is not starting. That’s what happened to me.

The Solution

Basically what you need to do is add an installer class derived from System.Configuration.Install.Installer.

To make it as simple as possible I'm taking the sample from the Topshelf documentation page (topshelf-project.com/documentation/getting-started/) and I'm defining the necessary Installer class so it can be installed from Wix or InstallUtil.exe.

This is the main class that will be run from the Windows Service:

internal class Program
{
    private static void Main(string[] args)
    {
        log4net.Config.XmlConfigurator.Configure();
        HostFactory.Run(
            x =>
                {
                    x.Service<TownCrier>(
                        s =>
                            {
                                s.SetServiceName("tc");
                                s.ConstructUsing(name => new TownCrier());
                                s.WhenStarted(tc => tc.Start());
                                s.WhenStopped(tc => tc.Stop());
                            });
                    x.RunAsLocalSystem();

                    x.SetDescription("Sample Topshelf Host");
                    x.SetDisplayName("TownCrierService");
                    x.SetServiceName("TownCrierService");
                });
    }
}

This is the Service class itself:

public class TownCrier
{
    private readonly Timer _timer;

    public TownCrier()
    {
        ILog log = LogManager.GetLogger(typeof(TownCrier));
        log.Debug("User:"+WindowsIdentity.GetCurrent().Name);
        _timer = new Timer(1000) { AutoReset = true };
        _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} an all is well", DateTime.Now);
    }

    public void Start()
    {
        _timer.Start();
    }

    public void Stop()
    {
        _timer.Stop();
    }
}

This is the required installer class.

[RunInstaller(true)]
public class ProjectInstaller : Installer
{
    private ServiceInstaller _serviceInstaller;

    private ServiceProcessInstaller _serviceProcessInstaller;

    public ProjectInstaller()
    {
        this.InitializeComponent();
    }

    private void InitializeComponent()
    {
        this._serviceInstaller = new ServiceInstaller();
        _serviceProcessInstaller = new ServiceProcessInstaller();

        this._serviceProcessInstaller.Account = ServiceAccount.LocalService;

        this._serviceInstaller.DisplayName = "TownCrierService";
        this._serviceInstaller.ServiceName = "TownCrierService";

        this.Installers.AddRange(new Installer[] { this._serviceProcessInstaller, this._serviceInstaller });
    }
}

Notice that the Installer class and the main program class use the same ServiceName, if you don't use the same name your service will not start.

Finally this is a sample Wix installer for the service:

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
	<Product Id="4bafff3b-b638-4e81-ae2c-97a13c50631d" 
           Name="TownCrierInstaller" 
           Language="1033" 
           Version="1.0.0.0" 
           Manufacturer="TownCrierInstaller" 
           UpgradeCode="57c76289-42b4-40b2-95f0-1652b703cefa">
    
		<Package InstallerVersion="200" Compressed="yes" />

		<Media Id="1" Cabinet="media1.cab" EmbedCab="yes" />

		<Directory Id="TARGETDIR" Name="SourceDir">
			<Directory Id="ProgramFilesFolder">
				<Directory Id="INSTALLLOCATION" Name="TownCrierInstaller" 
                   FileSource="C:\YourPath\TopShelfWix\TownCrierService\bin\Debug\">
          <Component Id="Service" Guid="{B5DC8DF4-1B45-47F4-A2B2-791CEB3E97DF}" >
            <File Id="TCFile" KeyPath="yes" Name="TownCrierService.exe" />
            <File Id="a1ac9979e3f2f48e39252e024a9aa75bb" Name="TownCrierService.exe.config" />
            <File Id="ad345d1dff94646dc81e54e095d1aa7c7" Name="log4net.dll" />
            <File Id="a6f1bc7613d5449e7a3d539422299b580" Name="Topshelf.dll" />
            <ServiceInstall Id="TCInstall"
                     Type="ownProcess"
                     Name="TownCrierService"
                     DisplayName="TownCrierService"
                     Start="demand"
                     Account="yourdomain\youruser"
                     Password="password"
                     ErrorControl="normal" />
            <ServiceControl Id="TCControl"
                     Stop="both"
                     Remove="uninstall"
                     Name="TownCrierService"
                     Wait="no"/>
          </Component>
				</Directory>
			</Directory>
		</Directory>

		<Feature Id="ProductFeature" Title="TownCrierInstaller" Level="1">
			 <ComponentRef Id="Service" /> 		
			<ComponentGroupRef Id="Product.Generated" />
		</Feature>
	</Product>
</Wix> 

Why?

To install a regular (non Topshelf) Windows Service you use InstallUtil.exe. When decompiling it I found out that what it does is scan the service assembly looking for classes derived from the System.Configuration.Install.Installer. Topshelf does have such a class but it’s in the Topshelf assembly which is not the Service assembly itself hence InstallUtil can’t find it.

I'll probably add more information on this issue later, for now I just want to document the solution for me and for anyone else going through the same issue.

I hope this helps.

Dependency Properties

Dependency Properties are quite different from regular CLR properties. Let's take an Age property as a simple example of a normal property. We usually define a private field of type int and then define a Age property wrapping this field with get and set accessors. The code should be something like this:

public class Person
{
    private int _age;
    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}

If instead we wanted to create age as a dependency property instead the code would look like this:

public class Person : DependencyObject
{
    public static readonly DependencyProperty AgeProperty = DependencyProperty.Register("Age", typeof (int),
                                                                                        typeof (Person));
    public int Age
    {
        get { return (int)GetValue(Person.AgeProperty); }
        set { SetValue(Person.AgeProperty, value); }
    }
}

 

Wow, that is really different isn't it? Actually it is so different that I rather take it apart so that we can understand each piece of this code.

Part 1: The class

Dependency properties can only be used in classes that derive from DependencyObject. As you can see in the first example the Person class is a simple class derived from the Object class. In the second example Person is derived from DependencyObject.

DependencyObject is the class that has all the necessary infrastructure that make DP's work. As we go through this article I'll mention more about this class but for now just keep in mind that if you want or need to use DP's your class must derive from DependencyObject.

Part 2: Declaring the Property

As you may have noticed the two examples are totally different. By convention the DP is a public static readonly field of the type DependencyProperty. So the field that will store the actual value of age is not an int? Yep, that is it. As you can see the field if of type DependecyProperty. This is all part of the DP way of life. The actual type of the age (which we know is int) will only be know when instantiating the DP.

Another thing that you may be wondering about is that the filed was named AgeProperty instead of just Age. The suffix Property is included as a convention to denote that this is the static field to the DP.

Part 3: Instantiation

The DependencyProperty class doesn't have a public constructor. To create an instance of this class we need to use the use the Register static method.

 

The simpler overload of this method takes three parameters, the first is a string that sets the name of the DP (Age in our case), the second expects the type of the property, which is int, and the last one represents the type of the class to which the DP is associated (in our example is the class Person).

 

The creation of the DP may be done inline as we've done in our example or it may be move in the static constructor like this:

public static readonly DependencyProperty AgeProperty;
static Person()
{
    AgeProperty = DependencyProperty.Register("Age", typeof(int), typeof(Person));
}

This code is more than a Factory to instantiate the DependencyProperty object, it also (as the name very well describes) registers the new property within the DP infrastructure. If you are interested in low level details, the actual registration occurs a private method called RegisterCommon of the DependencyProperty class. Download the framework source code or use Reflector to look inside.

Part 4: Wrapping the DP

Now that you saw what is really behind a DP you may be asking yourself. Ok, so my property is age of type int, but the DP is actually of type DependencyProperty, so how do I assign a value of 30 to the object that is not really an int? Cool, you are on the right track then!
The work of getting and setting the values of DPs goes through the DependencyObject class. It has a SetValue method for setting the value of the property and a GetValue method to retrieve the value. These methods are public you may use them directly like in the example below:

Person person = new Person();
person.SetValue(Person.AgeProperty, 31);
int myAge = (int)person.GetValue(Person.AgeProperty);

Since these methods are part of the DependencyObject class is clear that they are general purpose methods to retrieve or set values of properties. It is pretty straight forward then that you have to tell which property you want to get the value from. That is when you use your static DependencyProperty field that was already registered. Also the GetValue returns an instance of the class Object so you need to cast it to your type.
This is all good but I bet you are saying that this syntax is too verbose, right? Don't worry I think so too and the WPF team as well. In order to provide easy access to the DPs you may use property wrappers, like in our example. Using this strategy you code will become easier to work with and people don't even have to know if the property is a DP or not.

Person person = new Person();
person.Age = 31;
int myAge = person.Age;

IMPORTANT
When using properties you should be advised that you should not use any other code within the get or set accessors. This warning is documented in every book or piece of documentation I've read so far! Doing anything but using GetValue or SetValue in the accessors may really mess up your program. The thing is that WPF will use in many parts of it's code the GetValue and SetValue methods instead of your property wrapper. If your wrapper adds any thing to the mix you may have inconsistent results through your application, so watch out for this.

But wait, there's more

Now that we have the base idea of DP, let's keep going and try to understand few more concepts.

LocalValue vs EffectiveValue

Understanding this distinction really important in the process of learning WPF. The actual distinction is not even visible at first, but as soon as you begin to study coercion you notice that there is something more than just a value to the property.
The LocalValue is the "real" value, or the value that you set to the property. This value is stored but it may not be the one displayed if you try to use the GetValue method. But why would the property show a value other than the one you set? Let's imagine that in our example we could have a MinAge and a MaxAge properties and we set the values as in the following code:

person.MinAge = 21;
person.MaxAge = 150;
person.Age = 15;
int age = person.Age;

Setting the Age to 15 would not be allowed since the minimum value is 21. The DP infrastructure code has was to enforce these constraints (I'll show it a bit latter). When the code reads the property reads the Age it will return 21 which is the EffectiveValue. Does this implies that the 15 is gone? Nope! The 15 is still stored as the LocalValue (or real value if you will), if you don't believe me just use the ReadLocalValue method to read the Age property.
So the EffectiveValue is the result of applying constraints (or corrections) over the LocalValue. More often than not these values will actually be different.
One last thing about Local vs Effective is how the default value of the property is set. Age is an int, right? What is the default value for an int? Yep, 0 (zero) is the correct answer! So if you do person.Age you expect it to return 0 if you have not done any other initialization to this property. By now you probably figured out that the EffectiveValue has to be initialized to the default value of the property type. So EffectiveValue stores 0. The LocalValue on the other hand only gets a value when it set explicitly. But what is it's value mean while? Null? No, when the LocalValue is not set, the ReadLocalValue will return DependencyProperty.UnsetValue which is a public static field on the DependecyProperty class.

FrameworkPropertyMetadata

This class provides way to pass more parameters for the DependencyProperty. So far our property works fine, but we could do a little more with the FrameworkPropertyMetadata. Let's see some of the important properties that you can pass to the DP through the metadata:

  • DefaultValue: Using this property you can set the default value for the DP
  • CoerceValueCallback: This callback will try to make adjustments (or correct) to the value of the property. Coercion is a concept that we'll discuss a little latter.
  • PropertyChangedCallback: This callback will be fired when the value of the property is changed.
DefaultValue

Let's you pass in a default value for the DP. When you create an instance of the class Person the Age will be equals to 0 (zero). Now a challenge: When the DefaultValue is set where is this value stored, in the LocalValue or EffectiveValue? If you said EffectiveValue you are right. Try to use the ReadLocalValue and you'll see that the value is defined as DependecyProperty.UnsetValue.

Person person = new Person();
object o1 = person.Age; //returns 0
object o2 = person.GetValue(Person.AgeProperty); //is the same thing as the line above
object o3 = person.ReadLocalValue(Person.AgeProperty); // returns DependencyProperty.UnsetValue
CoerceValueCallback

This callback is set to a method that is going to take the value that is attributed to the property and apply some kind of correction to it. Setting a value to the property will change the value of the LocalValue and the EffectiveValue but if the CoerceValueCallback makes some change to the value this modified value is stored in the EffectiveValue while the original, unchanged attributed value is stored in the LocalValue. Let's say that any Age greater than 100 needs to be set as 100. The method to this is really simple:

 

private static object CoerceAgeValue(DependencyObject d, object baseValue)
{
    int age = (int)baseValue;
    return Math.Min(100, age);
} 

Now let's see how an instance of the class Person would behave when having it's value set:

Person person = new Person();
person.Age = 105; //will cause the value to be coerced
object o2 = person.GetValue(Person.AgeProperty); //returns 100 (this is the coerced value)
object o3 = person.ReadLocalValue(Person.AgeProperty); //returns 105 (this is the original value)

Another great example of the power given by this resource is the use of a ScrollBar:

ScrollBar bar = new ScrollBar();
//value = 0 (LV=Unset, EV=0), min = 0, max = 1


The ScrollBar has just been created and it's values are still the default values. Now let's change the Value to 100.

bar.Value = 100;
//value = 1 (LV=100, EV=1), min = 0, max = 1


The LocalValue is now 100 but the EffectiveValue was coerced to respect the Min and Max values. Though the Value shows 1 the actual value is still stored and was not lost.

bar.Minimum = 1;
//value = 1 (LV=100, EV=1), min = 1, max = 1


The Min value is set but it doesn't change the outcome for us.

bar.Maximum = 200;
//value = 100 (LV=100, EV=100), min = 1, max = 200


Now that the Max was set to 200 the coercion will not need to change the value stored in the Value property. Now it finally shows as 100 as we had originally defined. This means that the order in which you set the properties will not affect the final result. If it was not for the was DPs work you would need to first define the Min and Max and only then you could the set Value. This is awesome!!

PropertyChangedCallback

This has one simple mission: Notify that a change was made to the property. In the ScrollBar whenever the Minimum or Maximum are changed a callback is fired, this callback is responsible for coercing the Value of the control using the new Maximum or Minimum.

ValidateValueCallback

The ValidateValueCallback is the last parameter of the DepenencyProperty.Register method. This callback points to a method that will validate the value being attributed to the property. Here is an example of a validation of the Age property:

private static bool ValidateAgePropertyValue(object value)
{
    int age = (int)value;
    return age >= 0;
}

In this method we validate that the Age is greater than zero after all there is no negative ages. I know that you are thinking that this is very similar to the coercion concept, right? They way I perceive the difference is that the Validation is trying to identify an incorrect value while the the Coercion takes a valid value and makes some adjustments according to other properties in the object like the Minimum or Maximum in the ScrollBar example.

Another difference between the two is that the Validate method has one single parameter which is the new value that is being set. Since the method is a static method you do not have access to any other properties in the object which imposes a limitation on the kind of validation that could be made. The Coercion callback has two parameters: the dependency object that has the value and the new value for the property. Since this callback has access to the dependency object it is the ideal place to make the kind of tests that will try to limit the value between a minimum and a maximum.

Putting it all together

I know this is a lot to digest so the best way to really understand it all is to see a full example.

The following code is for a Car class with 3 Dependency Properties: Speed, MaxSpeed and MinSpeed. The speed has to be between the minimum and maximum. Every time the one of these properties is changed the others must me adjusted in order to keep the constraints we imposed.

public class Car : DependencyObject
    {
        #region Dependency Properties

        public static readonly DependencyProperty SpeedProperty;

        public static readonly DependencyProperty MinSpeedProperty;

        public static readonly DependencyProperty MaxSpeedProperty;

        #endregion


        #region Dependency Properties Wrappers

        /// <summary>
        /// Wrapper for the Speed dependency property
        /// </summary>
        public int Speed
        {
            get { return (int)GetValue(SpeedProperty); }
            set { SetValue(SpeedProperty, value); }
        }

        /// <summary>
        /// Wrapper for the MinSpeed dependency property
        /// </summary>
        public int MinSpeed
        {
            get { return (int)GetValue(MinSpeedProperty); }
            set { SetValue(MinSpeedProperty, value); }
        }

        /// <summary>
        /// Wrapper for the MaxSpeed dependency property
        /// </summary>
        public int MaxSpeed
        {
            get { return (int)GetValue(MaxSpeedProperty); }
            set { SetValue(MaxSpeedProperty, value); }
        }

        #endregion

        /// <summary>
        /// Static constructor where all dependecy properties are being initialized
        /// </summary>
        static Car()
        {
            Trace.WriteLine("Static Constructor");
            //configure and register speed property
            FrameworkPropertyMetadata speedMetadata = new FrameworkPropertyMetadata(0, null, CoerceSpeed);
            SpeedProperty = DependencyProperty.Register("Speed", typeof (int), typeof (Car), speedMetadata,
                                                        ValidateSpeed);

            //configure and register min speed property
            FrameworkPropertyMetadata minMetadata = new FrameworkPropertyMetadata(0, OnMinSpeedChanged);
            MinSpeedProperty = DependencyProperty.Register("MinSpeed", typeof (int), typeof (Car), minMetadata,
                                                           ValidateSpeed);

            //configure and register max speed property
            FrameworkPropertyMetadata maxMetadata = new FrameworkPropertyMetadata(1,OnMaxSpeedChanged, CoerceMaxSpeed);
            MaxSpeedProperty = DependencyProperty.Register("MaxSpeed", typeof (int), typeof (Car), maxMetadata,
                                                           ValidateSpeed);
        }

        #region Validate methods

        public static bool ValidateSpeed(object value)
        {
            Trace.WriteLine("ValidateSpeed");
            int speed = (int)value;
            return speed >= 0;
        }

        #endregion

        #region Coerce methods

        /// <summary>
        /// method for adjusting the speed according to the min and max
        /// </summary>
        /// <param name="d"></param>
        /// <param name="baseValue"></param>
        /// <returns></returns>
        public static object CoerceSpeed(DependencyObject d, object baseValue)
        {
            Trace.WriteLine("CoerceSpeed");
            Car car = (Car)d;
            int speed = (int)baseValue;
            //the speed can't be lower than the min speed
            speed = Math.Max(car.MinSpeed, speed);
            //the speed can't be greater than the max speed
            speed = Math.Min(car.MaxSpeed, speed);
            return speed;
        }

        /// <summary>
        /// method for adjusting the max speed according to me min speed.
        /// </summary>
        /// <param name="d"></param>
        /// <param name="baseValue"></param>
        /// <returns></returns>
        public static object CoerceMaxSpeed(DependencyObject d, object baseValue)
        {
            Trace.WriteLine("CoerceMaxSpeed");
            Car car = (Car)d;
            int maxSpeed = (int) baseValue;
            //the max speed can't be lower than the main speed
            return Math.Max(car.MinSpeed, maxSpeed);
        }

        #endregion

        #region Property changed methods

        /// <summary>
        /// this method is fired when the MaxSpeedProperty is changed
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnMaxSpeedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Trace.WriteLine("OnMaxSpeedChanged");
            Car car = (Car)d;
            car.CoerceValue(SpeedProperty);
        }

        /// <summary>
        /// this method is fired when the MinSpeedProperty is changed
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnMinSpeedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Trace.WriteLine("OnMinSpeedChanged");
            Car car = (Car)d;
            //coerce the max speed to ajdust to the new min speed
            car.CoerceValue(MaxSpeedProperty);
            //coerce the speed to adjust to the new min speed
            car.CoerceValue(SpeedProperty);
        }

        #endregion

    }

We can create an instance of the Car class in the initialization method of any window you like. Here is the my test code:

Car car = new Car();
Trace.WriteLine(string.Format("Speed:{0} Min:{1} Max:{2}",car.Speed,car.MinSpeed,car.MaxSpeed));
Trace.WriteLine(string.Format("Speed LocalValue:{0} EffectiveValue:{1}", car.ReadLocalValue(Car.SpeedProperty),
                car.GetValue(Car.SpeedProperty)));
car.Speed = 60;
Trace.WriteLine(string.Format("Speed: {0} Min:{1} Max:{2}",car.Speed,car.MinSpeed,car.MaxSpeed));
Trace.WriteLine(string.Format("Speed LocalValue:{0} EffectiveValue:{1}", car.ReadLocalValue(Car.SpeedProperty),
                car.GetValue(Car.SpeedProperty))); 
car.MinSpeed = 40;
Trace.WriteLine(string.Format("Speed: {0} Min:{1} Max:{2}",car.Speed,car.MinSpeed,car.MaxSpeed));
Trace.WriteLine(string.Format("Speed LocalValue:{0} EffectiveValue:{1}", car.ReadLocalValue(Car.SpeedProperty),
                car.GetValue(Car.SpeedProperty))); 
car.MaxSpeed = 80;
Trace.WriteLine(string.Format("Speed: {0} Min:{1} Max:{2}",car.Speed,car.MinSpeed,car.MaxSpeed));
Trace.WriteLine(string.Format("Speed LocalValue:{0} EffectiveValue:{1}", car.ReadLocalValue(Car.SpeedProperty),
                car.GetValue(Car.SpeedProperty)));

When you run this code you get the following output showing the order in which the methods were called:

Static Constructor
ValidateSpeed
ValidateSpeed
ValidateSpeed
ValidateSpeed
ValidateSpeed
ValidateSpeed
Speed:0 Min:0 Max:1
Speed LocalValue:{DependencyProperty.UnsetValue} EffectiveValue:0
ValidateSpeed
CoerceSpeed
ValidateSpeed
Speed: 1 Min:0 Max:1
Speed LocalValue:60 EffectiveValue:1
ValidateSpeed
OnMinSpeedChanged
CoerceMaxSpeed
ValidateSpeed
OnMaxSpeedChanged
CoerceSpeed
ValidateSpeed
CoerceSpeed
ValidateSpeed
Speed: 40 Min:40 Max:40
Speed LocalValue:60 EffectiveValue:40
ValidateSpeed
CoerceMaxSpeed
OnMaxSpeedChanged
CoerceSpeed
Speed: 60 Min:40 Max:80
Speed LocalValue:60 EffectiveValue:60

I hope this was usefull.

How to Learn WPF

I have been studying WPF more seriously for about two months. It is an amazing technology with a lot of new concepts that may be hard to grasp at first. In order to help others that may be trying to learnWPF and don't know where to start here is my take on it.

Although there is a lot of good material on the Internet the best way to learn (in my opinion) is still a good book. I have browsed through few books:

I found that the best one to get started with WPF and to read from cover to cover is Essential Windows Presentation Foundation by Chris Anderson. It is a relatively short book with about 500 pages. You will find that it is really easy to read with good examples and direct explanations. I have to say though that this book is not a good reference book. Don't let the fact that this is a 2007 book scare you away, this one is all about concepts and those didn't change since version 3.0 of the framework.

The other book I really liked was Pro WPF in C# 2008. This one is a in depth dive into WPF and maybe is not the book you would want to get started with. On the other hand this is the best reference book. It is really easy to browse since it has a dedicated chapter for each topic. Actually, this is the only book among the ones I looked at that has this format. The other books try to group related topics in the same chapter, which makes a good read but harder tolookup a specific thing.

The other book I would recommend is Windows Presentation Unleashed. It has an in depth coverage of all topics and is really easy to understand. The only thing I have against it is that it is a bit outdated since it was written for the framework 3.o. I wouldn't by this one but if you have someone you can borough from then I guess it isok.

There is also really good material on the MSDN site. Many of the books I mentioned before are heavily based on this documentation. The books are still more friendly to read but if you are looking any one topic in special the MSDN documentation is a really good place to search. Here is the link.

After you have a clear understanding on concepts such as Dependency Properties, Routed Events, Commands and Binding you have to look atMVVM concepts. This makes WPF even more amazing. I recommend getting started with Josh Smith's article on the MSDN Magazine called WPF Apps with The Model-View-ViewModel Design Pattern. Also make sure you follow the WPF Disciples.

If you are the screencast type of guy (or gal) you can checkout a lot of great videos on the WindowsClient.net site. Make sure you go to the Learn section.

Well, I think that is it. I'll update this post if I remember anything else but for now I think that this is plenty of material for you to get on your way to becoming aWPF master :-).

OCIEnvNlsCreate failed with return code -1

"OCIEnvNlsCreate failed with return code -1 but error message text was not available". This was the error that was really anoying my last week. I've had this problem before on one of our servers and this time it showed up in one of my co-workers machine.

Once again Sysinternals came to the rescue. When I used ProcessMonitor to watch the application running I noticed that it couldn't load some of Oracles dlls. The really strange part was that the dlls it was complaining about were from Oracle 10 and the client we were using were from version 11. I then decide to use ProcessExplorer to checkout out application process in order to find out what dlls were really loaded. Imagine my surprise when I saw that the application had the oci.dll from version oracle client 10 running. At some point someone had put a copy of this dll on the windows/system32 folder, and that was the dll that was being loaded instead of the correct one that was in the Oracle install directory.

After we deleted the incorrect dll our program still had the same error. Turns out that the ORACLE_HOME environment variable was not set either. Once we set the variable and restared IIS it was all fine! So, to sum up:

Error:

OCIEnvNlsCreate failed with return code -1 but error message text was not available

Solution:

 1 - Check if the ORACLE_HOME environment variable is set correctly. Here is how to do it.

 2 - Use Process Explorer to check out what versions of Oracle's dlls are loaded. If it's a different version from the version of the client you have installed, remove these incorrect versions from your machine. They may have been there from a previous client installation.

I hope this will help someone else!

Find and Replace using Regular Expressions within Visual Studio

Regular expressions can be a great addition to the Find and Replace functionality within Visual Studio, specially when you want do do some transformation on the text you are looking up. Lately I’m working on a simple conversion class to transform some HTML into RTF. I got a list of special characters in HTML that I had to convert to the RTF equivalent and for that I needed to create a dictionary. The values where listed in a text document like this:

\'b0 \tab &deg;\par
\'b1 \tab &plusmn;\par
\'b2 \tab &sup2;\par
\'b3 \tab &sup3;\par
\'b4 \tab &acute;\par
\'b5 \tab &micro;\par
\'b6 \tab &para;\par
\'b7 \tab &middot;\par
\'b8 \tab &cedil;\par
\'b9 \tab &sup1;\par
\'ba \tab &ordm;\par
\'bb \tab &raquo;\par
\'bc \tab &frac14;\par
\'bd \tab &frac12;\par
\'be \tab &frac34;\par

And I needed to create a dictionary with the key being the HTML code (third column) and the RTF code (first column) the value. Like this:

Dictionary<string, string> charsMapping = 
    new Dictionary<string, string>();
charsMapping.Add("&euro;", @"\'80");

Here is the expression to find the matches within Visual Studio: __ {\\’:a:a}{.}{&:a;}{\\par}

Each pair of { } is a group to be matched. The difference is that the usual \w (letters or numbers) is :a. In my expression I have four groups the fist is the match for the RTF character and the third is the match for the HTML code. Knowing that the Replace expression is as follows: __charsMapping.Add(”\3”, @”\1”);

Here is how it would look like in VS:

Doing this is much easier then creating the dictionary by hand of even writing a console app to do the replace. Sure I could have used some other text tool to do the same but it wouldn’t be as much fun as figuring out how to do it in VS.

Here is the final output:

Dictionary<string, string> charsMapping = 
    new Dictionary<string, string>();
charsMapping.Add("&deg;", @"\'b0");
charsMapping.Add("&plusmn;", @"\'b1");
charsMapping.Add("&sup2;", @"\'b2");
charsMapping.Add("&sup3;", @"\'b3");
charsMapping.Add("&acute;", @"\'b4");
charsMapping.Add("&micro;", @"\'b5");
charsMapping.Add("&para;", @"\'b6");
charsMapping.Add("&middot;", @"\'b7");
charsMapping.Add("&cedil;", @"\'b8");
charsMapping.Add("&sup1;", @"\'b9");
charsMapping.Add("&ordm;", @"\'ba");
charsMapping.Add("&raquo;", @"\'bb");
charsMapping.Add("&frac14;", @"\'bc");
charsMapping.Add("&frac12;", @"\'bd");
charsMapping.Add("&frac34;", @"\'be");
charsMapping.Add("&iquest;", @"\'bf");

Of course the number of characters was much bigger but it doesn’t matter here. If you need more info on regular expressions you might want to check out the Regular-Expressions.info site, they have a lot of good info on the subject. There are some specifics to using regular expressions on VS so you need to make sure to visit MSDN Reference.

Linq: Using Group By with Multiple Columns

I have a group of classes that I build to get metadata from the database to use with my code generators. The class has the following structure:

public class ConstraintMetadata
{
    public string ConstraintName { get; set; }

    public string ColumnName { get; set; }

    public string ConstraintType { get; set; }

    public string TableName { get; set; }
}

I wanted to write a group by clause using Linq to group the objects I retrieved from the db by TableName, ConstraintName and ConstraintType. This would allow me to have one object for each constraint with a list of all the columns. Since Linq only allows one object in the group by clause the way out is to create an anonymous object with all the properties I want.

var constraints = from c in constraintsMetadata
                  group c by new
                             {
                                 c.TableName, 
                                 c.ConstraintType, 
                                 c.ConstraintName
                             } into g
                      select new
                      {
                          g.Key.ConstraintName,
                          g.Key.ConstraintType,
                          g.Key.TableName,
                          Columns = g.Select(x=>x.ColumnName).ToList()
                      };

Now, if I want to get all the constraints for a table and print it to the console window I can do this:

var tableConstraints = constraints.Where(x => x.TableName == table.Name);

foreach (var tableConstraint in tableConstraints)
{
    Console.Out.WriteLine("Constraint Name:{0}, Table:{1}, Type:{2} Columns:", 
        tableConstraint.ConstraintName , 
        tableConstraint.TableName, 
        tableConstraint.ConstraintType);
    foreach (var column in tableConstraint.Columns)
    {
        Console.Out.WriteLine(column);
    }
}

 

Find out the calling method

This is one that I found really interesting. I needed to log which methods were calling a certain method, I knew that reflection was the answer but I never thought it would be so easy.

Have you used the CallStack window on your VisualStudio when you are debugging? Well, all that information is available through the System.Diagnostics.StatckTrace class. This means that you have access to method calling stack to do whatever you like.

The StackTrace is composed of an array of StackFrames which represent each method on the stack.

To demonstrate this I’ll create a class with four methods (Method1, Method2, Method3, Method4) which will be called in the following order:

Main -> Method1 -> Method2 -> Method3 -> Method4

class Program
{
    static void Main(string[] args)
    {
        StackTraceTest stt = new StackTraceTest();
        stt.Method1();
    }
}

class StackTraceTest
{
    public void Method1()
    {
        Console.Out.WriteLine("Inside Method1");
        Method2();    
    }

    private void Method2()
    {
        Console.Out.WriteLine("Inside Method2");
        Method3();
    }

    private void Method3()
    {
        Console.Out.WriteLine("Inside Method3");
        Method4();
    }

    private void Method4()
    {
        Console.Out.WriteLine("Inside Method4");
        StackTrace st = new StackTrace();
        StackFrame[] frames = st.GetFrames();
        for (int i = 0; i < frames.Count(); i++)
        {
            Console.Out.WriteLine("StackTrace info: Index: {0}/Method: {1}", 
                i, frames[i].GetMethod().Name);
        }
    }
}

Each method displays a message on the console letting you know that it has been invoked. When the program gets to Method4 it will print the name of the methods on the stack.

Here is the output:

Put a break point on the end of the Method4 and you can take a look at VisualStudios CallStack window to compare with the console output.

As a test you might want to move the StackTrace code to the other methods to see that it will show all the method that led to method currently executing.

For more information look at the StackFrame and MethodBase classes at MSDN.

When to use GUID over Autoincrement

The autoincrement feature in SQLServer tables is one that is really very handy. I’ve always like Oracle databases but it’s sequences are really much more complicated to manage than the autoincrement columns in SQLServer. If you are doing a project that is only going to run on Oralce or SQLServer either approach is fine and you won’t have any trouble.

The project I’m working on however has a requirement to work just the same on Oralce or SQLServer and the possibility that other databases may be added in the future. From day one my first worry was about if we were going to use Autoincrement and Sequences or we had to find another way out. The way out in this case would be to use GUID (Globally Unique Identifiers). In out case we chose to use Autoincrement for SQLServer and Sequences in Oracle. Mostly this approach was chosen because the guys that hired me thought that it would be much easier to search database for a record with a primary key like 1 or 15604 then something like 3F2504E0-4F89-11D3-9A0C-0305E82C3301. And I agreed with them on this, it is really simpler to say to the guy next to you to check if the person with id 2350 exists in the database the to tell him a GUID.

Of course we had a price to pay for this decision. Our DAL (Data Access Layer) was much more complicated because we had to deal with the Autroincrement vs Sequences problem. Imagine that you have a simple table called person with two columns only: ID and Name. Look at the difference in the insert clauses for each database:

Oracle
INSERT INTO PERSON (ID, NAME) VALUES (SEQ_PERSON.NEXTVAL, 'GABRIEL');
SQLServer
INSERT INTO PERSON (NAME) VALUES ('GABRIEL');

Observe that with Oracle I have to specify the PK column and in SQLServer I don’t and even worst I have to call the sequence SQL_PERSON to get the next value for the insert. If I want to return the value of the ID of the record we just inserted I’d have to do this:

Oracle
INSERT INTO PERSON (ID, NAME) VALUES (SEQ_PERSON.NEXTVAL, 'GABRIEL') RETURNING ID INTO :ID;
SQLServer
INSERT INTO PERSON (NAME) VALUES ('GABRIEL');
SELECT CAST(SCOPE_IDENTITY() AS INT);

I think you get the point right? There are a lot of differences in both databases! If we had choosen to use GUID id’s our life in the DAL would be much simpler. The GUID would be generated in the DAL which would make the insert statements very similar if not equal most of the time. Returning the generated GUID would also be a piece of cake. It’s true that using numeric PK’s creates better indexes and would consume less space but I find that these improvements would’ve been superseded by the ease in development.

So to sum up, when developing a system that should be database independent I would recommend using the table’s primary key’s as GUID in order to avoid using Autoincrement and Sequences. Your DAL layer would be more uniform and you could use ANSI SQL more often.

Just in case you are wondering we did when we couldn’t use ANSI SQL we created a SQL translator that would convert all the commands create for SQLServer to Oracle and this translator is part of our DAL generator so when I create a DAO for SQLServer the generator will create its’ structure and also Oracle’s all at once.

Find out about VS2010 on Channel9

If you want to find out what’s coming up in Visual Studio 2010 you have to check out the new podcast on Channel9 called 10-4. The first podcast of the series shows you how to download and install VS2010. The cool thing is that installation is already available as a virtual machine so you don’t need to worry about messing up you development machine.

The second episode shows a feature that is really simple but I always wanted. It let’s you manage you list of recent projects so that you can pin or remove projects. I know, I know… this is not going to change my life and there are a whole lot of more meaningful features but I just thought it was pretty cool since I’ve always wanted this.

Visit the 10-4 podcast site and draw your own conclusions on VS2010 new features.

jQuery Intellisense in VS 2008

Microsoft has shipped a patch to Visual Studio 2008 and Visual Web Developer 2008 Express that enables intellisense support for jQuery and will allow developers to add configuration information to other libraries such as Prototype so that they too can have the intellisense support. Read more about it in ScottGu’s Blog

ASP.NET MVC: DropDownList

Here is an example of how to use the Html.DropDownList helper method available in the MVC framework to generate a combo in you page.

Let’s use the Northwind example and say that you want to create a product and in the product for you need to select a category to which this product belongs in a dropdownlist.

The first step is in the select the list of categories in the appropriate controller action. In my case I’m going to use the new Action.

public ActionResult New()
{
    ViewData["CatList"] = new SelectList(_db.Categories.ToList(), "CategoryID", "CategoryName");
    return View();
}

Notice that I used the SelectList class. In this case I used the constructor that takes 3 parameters:

  1. The list of categories I got from my Linq DataContext
  2. The name of the property of the Category class that has the ID value that is going to be stored in the select list and which will be the value that actually is passed to the Product class
  3. The name of the property of the Category class that has the value I want to display to the user

The SelectList class will be used by the DropDownList helper to generate the html code. Here is part of the View code:

...
<tr>
       <td>Category:</td>
       <td><%= Html.DropDownList("CategoryID",(SelectList)ViewData["CatList"]) %></td>
</tr>
...

 

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.

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.

Set a property of a server tag dynamically

Setting a property of a server tag is pretty standard stuff:


<asp:TextBox ID="TextBox1" runat="server" Text="My name is Gabriel" />

Now, what if you want to use a class to set the value?


<asp:TextBox ID="TextBox1" runat="server" Text='<%= DateTime.Now %>' />

This will give you an error like this:

Server tags cannot contain <% ... %> constructs

If you ever need to solve this kind of problem I found a very interesting solution in the Infinites Loop Blog

It’s a very clever solution to use the Expression Builders, introduced in the Asp.Net 2.0 feature, to let you execute your custom code within the server tags.

Passed 70-529 today

I just passed the 70-529 exam and now I’m a MCTS Web and Distributed Applications. For those that are still thinking of taking this exam here are a few tips.

Usually I use Microsoft preparation books to study for certifications. This time I started using a book from the same collection:

MCTS Self-Paced Training Kit (Exam 70-529): Microsoft .NET Framework 2.0 Distributed Application Development

I have to say that I didn’t like this book. I didn’t think that the content was well approached and the writing style was also not for me. I still followed the book to the end but I had to complement it with two other books, one the had a good web services section and another that had a good remoting section. These books are:

Pro ASP.NET 2.0 in C# 2005 (This one complements the web services part)

Pro C# 2005 and the .NET 2.0 Platform (This one complements the remoting part)

Also a good starting point is the articles on the 4 Guys from Rolla that will give you a pretty good introduction to web services and it’s best if read before you read any of the books above.

Next week I’ll go on vacation and when I come back I’ll start my studies towards the MCPD Web Developer certification. I should take the test by the end of November. I’ll let you know how this goes.

LINQ: OrderBy with nullable columns in TypedDataSets

This article shows a tip on how you can do sorting using the LINQ OrderBy with Typed DataSets. For our example I’ll use the the Northwind Database and it’s Customers table. I’ll use two columns in this table. One is the ContactName which doesn’t have any null values and the Region column which has null values.

First lets populate the DataTable we want to query using TableAdapter I had previously generated in the DataSet.

CustomersTableAdapter ta = new CustomersTableAdapter();
DataSetNorthwind.CustomersDataTable dt = ta.GetData();

I want to use LINQ select all values ordering them by the Region column (which may be null). So here is the initial idea:

 var query = from r in dt.AsEnumerable()
                        orderby r.Region
                        select r;

Ok, no compilation errors but when you run the query you will get an error:

The value for column ‘Region’ in table ‘Customers’ is DBNull. -> System.InvalidCastException: ...

If you think about it this is expected. The nullable columns in the DataSet all have an IsNull method to check if the column is null or not and avoid this kind of error. We are going to use the IsRegionNull() method in our favor to help us solve the problem:

var query = from r in dt.AsEnumerable()
        orderby (r.IsRegionNull() ? "" : r.Region)
        select r;

I used the ternary operator to check if the column region is null or not. If it is then I’ll use an empty string as the value, if it’s not null I can call the Region property to get the value.

To see the ending result you can print all the values:

foreach (DataSetNorthwind.CustomersRow row in query)
{
     Console.WriteLine("{0} - {1}", row.ContactName, 
          row.IsRegionNull() ? "" : row.Region);
}

Of course you could have filtered out the rows with null regions, but the goal here is to show what you can do to order the rows when you have a column with values that may be null.

Get the number of business days between two dates

Here’s a simple way of getting the number of business days between two dates using C#.

DateTime dtBegin = new DateTime(2008, 8, 6);
            DateTime dtEnd = new DateTime(2008, 8, 13);

            int dayCount = 0;

            //while the End date is not reached
            while (dtEnd.CompareTo(dtBegin) > 0)
            {
                //check if the day is not a weekend day
                if ((dtBegin.DayOfWeek != DayOfWeek.Saturday) && (dtBegin.DayOfWeek != DayOfWeek.Sunday))
                {
                    dayCount++;
                }
                //go to next day
                dtBegin = dtBegin.AddDays(1);
            }

You can enhance this method consulting a list of holidays to check if the current date is indeed a business day. For this you have to have the list of holidays somewhere. In our example I’ll create a fake method that will provide the holidays list.

public static void CalculateNumberOfWeekdays()
        {
            DateTime dtBegin = new DateTime(2008, 8, 6);
            DateTime dtEnd = new DateTime(2008, 8, 13);
            List<DateTime> holidays = GetHolidays();

            int dayCount = 0;

            //while the End date is not reached
            while (dtEnd.CompareTo(dtBegin) > 0)
            {
                //check if the day is not a weekend day
                if ((dtBegin.DayOfWeek != DayOfWeek.Saturday) 
                    && (dtBegin.DayOfWeek != DayOfWeek.Sunday)
                    && (!holidays.Contains(dtBegin)))
                {
                    dayCount++;
                }
                //go to next day
                dtBegin = dtBegin.AddDays(1);
            }
            Console.WriteLine(dayCount);
        }

        public static List<DateTime> GetHolidays()
        {
            List<DateTime> holidays = new List<DateTime>();
            holidays.Add(new DateTime(2008, 8, 7));
            return holidays;
        }            

See you next time.

DataSet Designer (Editor) Missing

his week one of my co-workers had a strange problem with his VisualStudio 2008. All the sudden he couldn’t view the DataSet designer in any applications. When the DataSet file was clicked all that it showed was the XML file, no sign of the Designer.

We don’t know what happened but as I tried to figure out the problem I found that there’s very few information about this problem on the Internet, so I decide to blog about it so that it might help someone in distress.

If you’re having this problem you might first try to right click the DataSet file and then select the Open With… option. A list of editors will show, if you don’t see the DataSet Editor then you you have the same problem we did.

 

I have found a few posts about it, here are the solutions proposed:

  • Run the following command in the VisualStudio prompt: devenv /resetsettings
  • Run the following command in the VisualStudio prompt: devenv /setup
  • With Visual Studio setup disc select the Repair option.
  • Re-install Visual Studio.
All these are valid solutions and I found people on the web who claimed that this helped them but for my unfortunate teammate it didn’t help. The only thing that did it for us was:
  1. Remove VisualStudio
  2. Delete any folder left from VS installation
  3. Install VisualStudio

Finally, problem solved! I know this is not an optimal solution, far from it but at the end of the day it works. Nothing else did. I hope this post helps some else.

Problem with FormView inside UpdatePanel

Today I struggled for a while with a FormView that for no apparent reason wasn’t updating some of my fields to the database. After sometime I noticed that the fields that were not getting inserted into the database where the ones I had wrapped inside an UpdatePanel. Coincidence? I don’t think so…

I did a few tests and noticed that that was the problem indeed. I can’t say exactly what is the problem but it seems like that the FormView doesn’t like to have it’s fields inside an UpdatePanel.

The way I found to get around this issue is to populate the parameters manually in the events of the ObjectDataSource (ODS). So if you’re trying to insert a record you might using the Inserting event of the ODS to populate the problematic paramters:

protected void ObjectDataSource1_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
    {
        e.InputParameters["FirstName"] = ((TextBox)FormView1.FindContro("TextBoxFirstName")).Text;
        e.InputParameters["LastName"] = ((TextBox)FormView1.FindContro("TextBoxLastName")).Text;
        e.InputParameters["City"] = ((TextBox)FormView1.FindContro("TextBoxCity")).Text;
    }

In the Inserting event of the ODS the InputParamters have already been populated (at least the ones outside the UpdatePanel) but the record hasn’t been inserted yet, so you are intercepting the parameters, adjusting it’s values and then letting it continue with the insertion.

I hope this code spares someone to have to go through the tests I had to do.

GridView: Select last inserted record

The other day a responded a post on the asp.net forums about this so I think it might be useful to others.

Imagine if you have a GridView using pagination. When you insert a new record using a DetailsView or a FormView you want this new record to be automatically selected on the GridView, even if it’s not at the same page (of the GridView) that you currently have selected.

//returns a collection of records, including the one you just inserted
DataRowCollection drc = Dal.GetData();

//RecordID is the id of the record you just inserted, 
//you need to store this somewhere when you insert the record
DataRow dr = drc.Find(RecordID);

//having found the datarow of the record you need to know it's position(index) in the results
int index = drc.IndexOf(dr);

//Get the page the record will appear on
int page = index / GridView1.PageSize;

//If you're not already on the right page, set the PageIndex to the correct page
if (GridView1.PageIndex != page)
{
     GridView1.PageIndex = page;
}

 //gets the index of the record in the page
GridView1.SelectedIndex = index - (page* GridView1.PageSize);

 

Cache using Dynamic LINQ and Generics

You know those tables in your systems that are almost static (never change) by are consulted thousands of times a day? Well, the other day at work some asked me if we could avoid all this trips to the database.

The solution I came up with creates a cache at our BLL (Business Logic Layer) avoiding DAL layer to be called. First of all our base architecture is based on the principles on the asp.net tutorial Creating a Business Logic Layer. This article basically creates something very similar to a proxy pattern before the DAL which gives me the perfect place to intercept any calls to the DAL and consult my cache.

To avoid the trip to the database, when the BLL is instantiated I do one query to the database which returns all the records in the table. The resulting DataTable is stored in my cache class which is declared as static in the class. This will make possible that the cache is populated only once. All subsequent queries will fetch the results from the Cache instead of making a trip to the database.

The cache table is very simple. It stores a DataTable and performs filters in it using LINQ syntax. I had other options but since I was starting to work with LINQ at the time it seemed like a good choice. For this code I use the Dynamic LINQ which I mentioned in my previous post.

In order to work with TypedDataSets (which was a requirement for me) I create the Cache class to accept the DataTable and DataRow types.

public class CacheDataTable<T, S>  where T : DataTable where S : DataRow
    {
        private T cacheDataTable;

        //stores the DataTable that will be used for future consults
        public CacheDataTable(T dataTable)
        {
            this.cacheDataTable = dataTable;
        }

        //returns a DataTable filtered by the expression
        public T GetData(string expression, params object[] values)
        {
            IEnumerable<S> tmp = ((IEnumerable<S>)cacheDataTable).AsQueryable().Where(expression, values);
            return getDataTablePopulated(tmp);
        }

        //returns all the records
        public T GetData()
        {
            return getDataTablePopulated((IEnumerable<S>)cacheDataTable);
        }

        //takes an enumeration and creates a new DataTable
        private T getDataTablePopulated(IEnumerable<S> rows)
        {
            T dt = Activator.CreateInstance<T>();
            foreach (S row in rows)
            {
                dt.ImportRow(row);
            }
            return dt;
        }
    }

After having the Cache class defined you can use it in the BLL like this:

public class CountryBLL
{
        CountryDAL dal;

        //the cache is static so that it is shared among all instances from the CountryBLL class
        private static CacheDataTable<DataSet1.CountryDataTable, DataSet1.CountryRow> cache;

        public TBG_CountryBLL()
        {
            dal = new CountryDAL();
            //tests if the cache class has not been created yet. Only happens at the first access
            if (cache == null)
            {
                cache = new CacheDataTable<DataSet1.CountryDataTable, DataSet1.CountryRow>(dal.GetData());
            }
        }

        public DataSet1.CountryDataTable GetData()
        {
            //gets all records from the cache
            return cache.GetData();
        }

        public DataSet1.CountryDataTable GetDataByPK(decimal id)
        {
            return cache.GetData("id == @0", id);
        }
}

Coded like this the CountryBLL will only cause a database connection at its first instantiation. This approach should only be used with tables which are static (or almost). If one record is inserted in this table it would demand the application to be restarted so that the static cache variable would be unloaded and created again. There are ways around this but it is not the objective of this post.

Hope this will help someone :-)

Dynamic Queries using LINQ

LINQ is great; I’m having all kinds of use to it lately. The other day I needed to do something different, I needed to write a LINQ query dynamically, constructing the LINQ query as a String and then executing it (which is pretty common thing when you’re using SQL).

I was already convinced that I would need to spend a couple of weeks writing such functionality. Turns out that Microsoft has already written a LINQ Dynamic Query Library. It doesn’t come with the framework but you can download it and include in your project. Take a look at ScottGu’s Blog to see his post about it.

Here is an example:

Suppose I have a LocalDBDataSet with a mapping to the Table Person (Name, Sex, Phone).

If I wanted to get all the people in the table and perform a LINQ query to filter only the Males (M) I could do it like this:

PersonTableAdapter ta = new PersonTableAdapter();
DataTable dt = ta.GetData();
IEnumerable<LocalDBDataSet.PersonRow> drCollection = 
    ((IEnumerable<LocalDBDataSet.PersonRow>)dt).AsQueryable().Where("SEX == @0", "M");

I know this isn’t the most exciting example ever and I would need dynamic LINQ to do it but I just wanted to show you what you could accomplish. You get the idea, right?

With this kind of resource you could accomplish a lot of cool stuff. In the next post I’ll show how you can write a Cache class that can be queried with LINQ to avoid unnecessary trips to the database.

You can download the LINQ Dynamic Query Library here or here

First impressions on ASP.NET Dynamic Data Preview

Today I saw a screen cast of ASP.NET Dynamic Data for the first time. As a Rails enthusiast I must say that I was very excited.

One of the ideas behind this technology is moving application logic into the models and removing them from the pages. Personally I think that idea is more than correct since a validation rule on a certain field will be repeated in every page where the field shows up.

Another great feature is the ability to quickly get something running. That is one thing that really facilitates talking to clients, after all there is no better way to talk a client than showing something running and from there you can define further requirements and move on with the development process.

I’m very excited to see the direction in which Microsoft is going with new ideas like the Dynamic Data Preview and the MVC framework. It shows that they a really connected to what is going on in the development world and keep taking the new ideas from other technologies and improving the .Net framework. So far the future of 3.5 looks bright.

To get to know the ASP.NET Dynamic Data Preview better look at the following screencast by David Ebbo: ASP.NET Dynamic Data Preview

Using Scope_Identity with TableAdapters

I find TableAdapters to be a very helpful resource so I use them a lot. However, every now and then I stumble upon some scenario where the TableAdapter needs some creativity to work. Imagine the following:

Scenario:

  1. Need to insert a Person and an Address in the Database;
  2. You populate all the data in just one page;
  3. The table PERSON has an primary key named ID which is an Identity, so SQLServer will generate the ID upon the record insertion;
  4. You need to Insert a record in the ADDRESS table that will need the ID of the person just inserted;
  5. You’re using TableAdapters;

For this you’ll need the SCOPE_IDENTITY function provided by SQLServer in the TableAdapter code.

The TableAdapters code is frequently regenerated so you need to protect this code from being overwritten on regeneration. The best solution for this is extending your TableAdapter and overriding the method you need to protect.

First step

Add a new insert query in the PERSONTableAdapter named InsertQueryReturnID with a code like this:

INSERT INTO [PERSON] ([NAME], [PHONE], [EMAIL]) VALUES (@p1, @p2, @p3);
SELECT CAST(SCOPE_IDENTITY() AS INT);

The key here is the SCOPE_IDENTITY() function which will return the last inserted id in your connection so you’re safe about inserts made by other users.

Second step

Add a new class named PERSONTableAdapterExtended to your project. This class will inhererit from PERSONTableAdapter. Next, copy the code for the InsertQueryReturnID method from the Designer file from your DataSet and paste the method to your extended class. Substitute the method’s virtual modifier by an override modifier (because you want to override the method from the base class).

Another important change is in the way you execute and return the id. Normally the insert would be executed with a command.ExecuteNonQuery() command which would return the numbers of rows affected. Our SQL will return the ID of the record inserted so will replace that code by (int)command.ExecuteScalar(). The final method should look like this:

public class PERSONTableAdapterExtended : PERSONTableAdapter
    {
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.TableAdapter")]
        [global::System.ComponentModel.DataObjectMethodAttribute(global::System.ComponentModel.DataObjectMethodType.Insert, false)]
        public override int InsertQueryReturnID(string p1, string p2, string p3)
        {
            global::System.Data.SqlServerCe.SqlCeCommand command = this.CommandCollection[1];
            if ((p1 == null))
            {
                command.Parameters[0].Value = global::System.DBNull.Value;
            }
            else
            {
                command.Parameters[0].Value = ((string)(p1));
            }
            if ((p2 == null))
            {
                command.Parameters[1].Value = global::System.DBNull.Value;
            }
            else
            {
                command.Parameters[1].Value = ((string)(p2));
            }
            if ((p3 == null))
            {
                command.Parameters[2].Value = global::System.DBNull.Value;
            }
            else
            {
                command.Parameters[2].Value = ((string)(p3));
            }
            global::System.Data.ConnectionState previousConnectionState = command.Connection.State;
            if (((command.Connection.State & global::System.Data.ConnectionState.Open)
                        != global::System.Data.ConnectionState.Open))
            {
                command.Connection.Open();
            }
            int returnValue;
            try
            {
                returnValue = (int)command.ExecuteScalar();
            }
            finally
            {
                if ((previousConnectionState == global::System.Data.ConnectionState.Closed))
                {
                    command.Connection.Close();
                }
            }
            return returnValue;
        }
    }

Step Three

Now you’ll use only the PERSONTableAdapterExtended class instead of the PERSONTableAdapter generated class. This will protect your code from changes when the DataSet is regenerated

Passed 70-536 today

Today I passed the 70-536 exam (Microsoft .NET Framework 2.0 – Application Development Foundation). Some parts of the exam are really interesting because you get to use them every day, like regular expressions, IO, threads, reflection etc. Others are a little more boring to study like Application Domains. Overall the contents of the exam are very helpful for developers who write more serious coding.

For those who are thinking about taking the exam, here is the recipe I used:

  1. Studied about 2 hours a day for 2 months
  2. Used the MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0 Application Development Foundation, which is quite good
  3. Worked with .Net for about 2 years
  4. It is very important to write code. Don’t think you can just read a book and go take the exam. Explore different scenarios, try new ideas. Only then you’ll be ready for the exam.

Now my next goal is to pass 70-528 and get the MCTS certification. This one should be easier to pass since I work with web apps every day. In about two months I hope I will have nailed it.

Autocomplete has a problem with numbers

When using Ajax ControlTookit Autocomplete Extender I noticed that when the value I wanted to dislplay was a number starting with 0 (zero), like 0012, this initiating zero is removed and the result would show as 12. I didn’t want this beahavior so after googling for a few minutes I found a post that had a solution.

The each string of the list that is returned to the page should have escaped double quotes before and after the string. In the following example I take a DataTable and loop through it, creating a new List in which I add the element 0 (zero) of each row sorrounding it with the escaped double quotes.

List<string> list = new List<string>(10); 

 for (int i = 0; i < dt.Rows.Count; i++)
 {
     list.Add("\""+ dt.Rows[i][0].ToString() + "\"");
 }

 string[] arrayString = list.ToArray();

I can only assume that when the result is rendered on the page ajax library try to convert the results to numbers. Surrounding each number with escaped double quotes forces them to be treated as strings.

Thanks to my friend Allison Bertoloto who brought this problem to my attention.