C#

Back to school : Getting to know F#

This post starts with a basic introduction of F# and finally ends up writing a simple unit test for an F# member. For those who don’t know what F# is all about, Its a product from Microsoft research and now part of VS 2010 family. Actually from Wikipedia it is described as follows:

F# (pronounced F Sharp) is a multi-paradigm programming language, targeting the .NET Framework, that encompasses functional programming as well as imperative object-oriented programming disciplines. It is a variant of ML and is largely compatible with the OCaml implementation. F# was initially developed by Don Syme at Microsoft Research but is now being developed at Microsoft Developer Division and is being distributed as a fully supported language in the .NET Framework and Visual Studio as part of Visual Studio 2010.

Now, let’s first start by creating an F# project using the built in VS template:

image

 

Once you hit ok, It will end you up with an empty module project like that follows:

image

Now, first of all what is a module in F# ? From MSDN library it is stated as:

In the context of the F# language, a module is a grouping of F# code, such as values, types, and function values, in an F# program. Grouping code in modules helps keep related code together and helps avoid name conflicts in your program.

But, it looks to me rather a namespace in C#. Next let’s create the first type in F#.

  1. type IMonkey =
  2.     interface
  3.        abstract member Name : string with set, get
  4.        abstract member Echo : unit -> int
  5.        abstract member Execute : unit -> unit
  6.     end

 

In F# everything is type , if you mark it as interface then use the interface or less class keyword. Here is in the code block, we can also see that the first member is declared using the with keyword followed by set, get which states that its a read/write property. The second member has :unit-> int , it means that it takes no argument and returns an integer value. Now, what if we had an argument, then the declaration would look like:

  1. abstract member Echo : arg1 : int -> int

 

Moving on to multiple arguments, it needs to be written in a tupled manner:

 

  1. abstract member Echo : arg1 : int * arg2:int -> int

 

The question remains it’s an interface but how we can declare class members that has method body and returns real value. To find out more lets consider this:

  1. type Foo =
  2.     class
  3.       member this.Echo(arg1 : int) =
  4.          10
  5.       static member EchoStatic() = 20
  6.     end

 

Here, type declaration is as expected has a class keyword. But for members there is one instance method and one static method. One returns 10 and another returns  20 but first one has arguments too.  The declaration is slightly different for implemented or class members where the assigned value acts as a return value and you have to specify the argument(s) via colon format and using commas like:

  1. member this.Echo(arg1 : int, arg2: int) = 100

 

Generally in C# we do :

  1. public int Echo()
  2. {
  3.     // something important
  4.     return 10;
  5. }

That is translated to F# in the following way :

  1. member this.Echo() =
  2.  // do somehting important
  3.  10

It concludes that you don’t need to use return keyword in F# instead just write the return value.Of course you have to specify this keyword to let F#  know that its an instance member. Now, moving further what would happen if I would implement “IMonky” interface to “Foo” class.

 

  1. type Foo =
  2.     class
  3.     interface IMonkey with
  4.         member this.Echo() = 10
  5.         member this.Execute() = ()
  6.         member this.Name with get() = "test"
  7.         member this.Name with set(arg1 : string) = ()
  8.         end
  9.         member this.Echo(arg1 : int) =
  10.          10
  11.         static member EchoStatic() = 20
  12.     end

 

Here, for each interface implemented should be wrapped with the following block :

interface <name> with

//  your implementation.

end

Another thing to notice here that how property getter and setter is implemented using the with keyword. Moreover, the assignment with empty parenthesis  like member this.Execute() = ()  marks that the method is returning anything or a void method.

 

Finally, as we are set with declaring an interface, its members and how it is implemented. Now, lets write an unit test that mocks a member from IMonkey. I will be using JustMock but can be done using other tools like NSubstitute (The new player in town) / Rhino. To start, first we need to add the following lines before the type and following the module declaration.

 

  1. open NUnit.Framework
  2. open Telerik.JustMock

 

Its similar to an using keyword in C#. I am skipping the type declaration and steps of adding new test methods into it that can be done in the same way as shown above. Thus, let’s consider the following snippet:

 

  1.   [<Test()>]
  2.   member this.ShouldMockMethodCallsWithReturn() =
  3.  
  4.       let monkey = Mock.Create<IMonkey>()
  5.      
  6.       Mock.Arrange(monkey, fun ignore -> monkey.Echo()).Returns(10).MustBeCalled()  
  7.  
  8.       let result = monkey.Echo()
  9.  
  10.       Mock.Assert(monkey)

 

One of the interesting thing here to notice is the variable assignment, where a dynamic variable is constructed using the let keyword which is similar doing the same in C#:

var monkey  = Mock.Create<IMonkey>();

In line 6 of Mock.Arrange,  the fun ignore –> monkey.Echo()  is equivalent to  () => monkey.Echo() in C# but can’t use the () as it means differently in F# therefore used an anonymous variable instead.  Rest is plain old vanilla that is calling the method and asserting the required.

 

Hope this information was helpful.

Enjoy!!


Don’t Parse That XML!

I’ve talked a few times about how the best code you can write is code you never write.  One of the major places I end up seeing developer writing code that they don’t need to write is when parsing XML.

A word of caution before I go into how to not have to parse XML!

What I am going to describe is not always going to be the best solution.  It is an easy solution that will cover simple processing of XML files.  For a large XML file, the solutions I am going to suggest might be memory intensive and take too long.

Seems like everyone is doing it

I’ve walked into so many software development shops and seen code to parse XML files.  It seems to be one of those really common things that not enough developers realize can be completely automated.

I have started to wonder if it is self-propagating.  If developers have a tendency to see it being manually parsed in one place, assume that there is not a better way, then propagate that manual parsing to the next place they go.

Why is it so bad?

First of all, it is not an easy task to parse XML.  Even when using an XML parsing library there is a large amount of code that has to be written, especially for a complex XSD.

XML parsing code is also very fragile.  If the structure of an XML file changes, the code will have to be modified, and the modification can have cascading effects.

Manually generated XML parsing code cannot be regenerated if the structure of the XML changes.

Most importantly, any code you have to write runs the risk of introducing bugs and complexity into the system.

It’s so simple you wouldn’t believe it

So, how simple is it to automatically parse XML into objects?

Very simple.  First I am going to give you the basic pattern, then I am going to tell you how to do it in both C# and Java.

Basic pattern:

  1. Use a tool to generate an inferred XSD from your XML file.  (You can skip this step if you already have an XSD file.)
  2. Use a code generation tool to generate your classes automatically from the XSD file.
  3. In your code, deserialize your XML file into an object tree using the framework you generated the classes from.

If you are doing something more complex than this, without a really good reason, you are doing it wrong!

Learning how to do this in your language of choice is a very important tool to put into your tool bag.  There are many times that I have run into the need to parse XML files, where I have saved many hours of development time, by knowing how to automatically deserialize my XML files into objects.

There are two main ways in which XML serialization frameworks work.

  1. Serializers that auto-generate the classes from the XSD files.
  2. Serializers that use annotations or attributes on classes.

Using a serializer that auto-generates the classes from an XSD is the easiest to use and can work in most cases.  If you need more control over the generation of the XML, you might want to use an attribute or annotation based framework.

One of the biggest barriers in getting started with an XML framework is knowing what to use and how to use it.  I am going to cover 3 options that will get you going for C#, Java SE, and Java Android development.

C# (XSD.exe)

XML serialization is so easy in C# because it is built right into the .NET framework.

The only real piece of magic you need to know is the XSD.exe tool which is installed with Visual Studio.  This one tool can be run to infer an XSD from your XML file and then again to take that XSD and produce fully serializable / deserializable classes.

If you have an XML file named myFile.xml, you can simply go to the Visual Studio command prompt and type:

xsd myFile.xml

Which will produce a myFile.xsd.

Then type

xsd myFile.xsd /c

This will generate a set of classes that you can add to your project, and then you can deserialize an xml file with this simple code:

   1: XmlSerializer serializer = 

   2: new XmlSerializer(typeof(MyFile));

   3:  

   4: Stream reader = new FileStream("myFile.xml",FileMode.Open);

   5:  

   6: MyFile myFile = (MyFile) serializer.Deserialize(reader);

 
It really is that simple.  There is no excuse for hand writing XML parsing code when you can literally take an XML file you have never seen before and turn it into an object in memory in 10 minutes.
The serialization framework and XSD tool provide options for using attributes to control how the XML is generated also.

Java (JAXB)

The steps are slightly more complicated with JAXB, but it is still fairly easy.

First we have to generate an XSD file from an XML file.  JAXB doesn’t do this itself as far as I know, but there is another tool we can use called Trang.

First step, download Trang, then run it like so:

java –jar trang.jar –I xml –O xsd myFile.xml myFile.xsd

You can also use the XSD.exe tool from Visual Studio if you have it installed or download it.  There are a few other tools out there as well.

Once you have the XSD file, or if you already had one you had written, you need to generate Java classes using JAXB’s tool like so:

xjc –p my.package.name myFile.xsd –d myDirectory

Running this command will produce Java files that represent the elements in your XML document.

Finally, to create your objects you can use the JAXB unmarshaller.

   1: JAXBContext jc = JAXBContext.newInstance("my.package.name");

   2: Unmarshaller unmarshaller = jc.createUnmarshaller();

   3: MyFile myFile = (MyFile) unmarshaller.unmarshal(new File( "myFile.xml"));

Not as simple as the C# example, but really quite simple.  I’ve omitted the steps like downloading JAXB and adding it to your class path, but you can see that the process really is not very painful at all.

JAXB also provides some options for customizing the serialization and deserialization.

Android (Simple XML)

You can’t use JAXB with Android.  It seems like because of the Dalvik VM, the reflection part of JAXB doesn’t work.

I found a pretty good and small XML framework that I am using in my Android app that seems to do the trick nicely.  You have to annotate your classes and create them by hand, but it is very simple and straightforward to do so.

The tool is called “Simple XML.”

You can find lots of examples on the “tutorial” tab on the web page.

Basically, you download Simple XML, add the jars to you class path, and create class files with some annotations to specify how to deserialize or serialize your XML.

Here is a small example of an annotated class, from the Simple XML website.

   1: @Root

   2: public class Example {

   3:  

   4:    @Element

   5:    private String text;

   6:  

   7:    @Attribute

   8:    private int index;

   9:  

  10:    public Example() {

  11:       super();

  12:    }  

  13:  

  14:    public Example(String text, int index) {

  15:       this.text = text;

  16:       this.index = index;

  17:    }

  18:  

  19:    public String getMessage() {

  20:       return text;

  21:    }

  22:  

  23:    public int getId() {

  24:       return index;

  25:    }

  26: }

 

To deserialize this xml you just use the following code.

   1: Serializer serializer = new Persister();

   2: File source = new File("example.xml");

   3:  

   4: Example example = serializer.read(Example.class, source)

Very simple and straightforward.  The only downside is generating the Java class files yourself, but that isn’t really very hard to do using the annotations.

No excuses

So there you have it, XML serialization frameworks abound to make your life easier when dealing with XML.  For most simple cases you should never handwrite XML parsing code, even when using a library to help you do it.

Now that I’ve shown you how easy it is, there really are no excuses!

As always, you can subscribe to this RSS feed to follow my posts on elegant code.  Feel free to check out my main personal blog at http://simpleprogrammer.com, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter here.

CreateDelegate<T> – An Exercise in Using Expressions

In a previous blog post I showed a basic example of how to use the Delegate.CreateDelegate() method as an alternative to the slow MethodInfo.Invoke() for dynamically invoking a method of a class at runtime. The only downside of using CreateDelegate is that its not strongly typed. This is usually not a problem when the signature of the method that must be invoked is known at compile as is the case in the example shown in the blog post mentioned earlier.

var subject = new Subject();
var doSomething = (Func<String, String>)
    Delegate.CreateDelegate(typeof(Func<String, String>), subject, "DoSomething");
Console.WriteLine(doSomething("Hello Freggles"));

Here we’re simply able to cast the result to the requested delegate type. But what if a generic method must be invoked for which the type parameters can vary at runtime? You can still use the CreateDelegate method, but you can’t cast the result to a strongly typed delegate type. This means that in order to invoke the created delegate, the DynamicInvoke method must be called on the returned Delegate object. This has the nasty side effect that when the original method being called throws an exception, the DynamicInvoke method wraps the original exception in a TargetInvocationException.  

So in order to find a better way and also exercise my Expressions-fu, I tried to come up with a CreateDelegate<T> extension method that can be used to a create a strongly typed delegate for a MethodInfo object.

Suppose we have to dynamically invoke a method with the following signature:

private void Map<TDomainEvent, TEvent>(TDomainEvent domainEvent, TEvent @event)
    where TDomainEvent : IDomainEvent
    where TEvent : IEvent
{
    ...
}

Given an instance of IDomainEvent and IEvent, using the CreateDelegate<T> extension method that I’m about to show, we can dynamically invoke this method using the following code:

var action = GetType()
    .GetMethod("Map", methodBindings)
    .MakeGenericMethod(domainEvent.GetType(), @event.GetType())
    .CreateDelegate<Action<IDomainEvent, IEvent>>(this);

action(domainEvent, @event);

Here we determine a specific MethodInfo object for the Map method using the types of the event objects we have. Now here’s the code for the strongly typed CreateDelegate extension method.

public static class MethodInfoExtensions
{
    public static TDelegate CreateDelegate<TDelegate>(this MethodInfo method,
                                                      Object instance)
        where TDelegate : class
    {
        return CreateCachedDelegate<TDelegate>(method,
            (typeArguments, parameterExpressions) =>
            {
                Expression<Func<Object>> instanceExpression = () => instance;
                return Expression.Call(Expression.Convert(instanceExpression.Body,
                                                          instance.GetType()),
                                       method.Name,
                                       typeArguments,
                                       ProvideStrongArgumentsFor(method,
                                                                 parameterExpressions));
            });
    }

    public static TDelegate CreateDelegate<TDelegate>(this MethodInfo method)
        where TDelegate : class
    {
        return CreateCachedDelegate<TDelegate>(method,
            (typeArguments, parameterExpressions) =>
                Expression.Call(method.DeclaringType, method.Name, typeArguments,
                                ProvideStrongArgumentsFor(method, parameterExpressions)));
    }

    private static TDelegate CreateCachedDelegate<TDelegate>(MethodBase method,
        Func<Type[], ParameterExpression[], MethodCallExpression> getCallExpression)
        where TDelegate : class
    {
        var @delegate = GetFromCache<TDelegate>();
        if(null == @delegate)
        {
            @delegate = CreateDelegate<TDelegate>(method, getCallExpression);
            StoreInCache(@delegate);
        }

        return @delegate;
    }

    private static TDelegate GetFromCache<TDelegate>()
    {
        Object delegateObj;
        if(_delegateCache.TryGetValue(typeof(TDelegate), out delegateObj))
            return (TDelegate)delegateObj;

        return default(TDelegate);
    }

    private static void StoreInCache<TDelegate>(TDelegate @delegate)
    {
        _delegateCache.TryAdd(typeof(TDelegate), @delegate);
    }

    private static TDelegate CreateDelegate<TDelegate>(MethodBase method,
        Func<Type[], ParameterExpression[], MethodCallExpression> getCallExpression)
    {
        var parameterExpressions = ExtractParameterExpressionsFrom<TDelegate>();
        CheckParameterCountsAreEqual(parameterExpressions, method.GetParameters());

        var call = getCallExpression(GetTypeArgumentsFor(method), parameterExpressions);

        var lambda = Expression.Lambda<TDelegate>(call, parameterExpressions);
        return lambda.Compile();
    }

    private static ParameterExpression[] ExtractParameterExpressionsFrom<TDelegate>()
    {
        return typeof(TDelegate)
            .GetMethod("Invoke")
            .GetParameters()
            .ToParameterExpressions()
            .ToArray();
    }

    private static void CheckParameterCountsAreEqual(
        IEnumerable<ParameterExpression> delegateParameters,
        IEnumerable<ParameterInfo> methodParameters)
    {
        if(delegateParameters.Count() != methodParameters.Count())
            throw new InvalidOperationException(
                "The number of parameters of the requested delegate does not match " +
                "the number parameters of the specified method.");
    }

    private static Type[] GetTypeArgumentsFor(MethodBase method)
    {
        var typeArguments = method.GetGenericArguments();
        return (typeArguments.Length > 0) ? typeArguments : null;
    }

    private static Expression[] ProvideStrongArgumentsFor(
        MethodInfo method, ParameterExpression[] parameterExpressions)
    {
        return method.GetParameters()
            .Select((parameter, index) =>
                Expression.Convert(parameterExpressions[index],
                                   parameter.ParameterType))
            .ToArray();
    }

    private static readonly ConcurrentDictionary<Type, Object> _delegateCache =
        new ConcurrentDictionary<Type, Object>();
}

I actually provided two CreateDelegate methods here, one for instance methods (the first one) and one for static methods ( the second one). The created delegates are cached in a dictionary because the call of lambda.Compile() seems to be quite expensive.

Now I have to warn you that, based on first preliminary measurements, this implementation probably isn’t going to outperform  Delegate.CreateDelegate(). In fact, if you’re interested have a look at this approach first as it seems much faster. I added some spike code to the Elegant Code repository for those who fancy to take a look.  


Adding options in Expression Blend extensions

Intro

Often extensions for Expression Blend need to store some global variables. Why not use the mechanisms Blend itself offers? I’d like to show you how to add a custom options page to the options dialog.

I’ve started the example project by creating a new C# WPF Custom Control Library project and naming it ExtendingBlendOptionsTutorial. The details on how to create a new Blend Extension can be found here. You need to make sure the Microsoft.Expression.Extensibility and Microsoft.Expression.Framework assemblies are referenced in your project. Both can be found in the Expression Blend installation folder on your machine.

The architectural design is taken from the existing option pages that are used by Blend. Every existing page uses a '’…Page’ , a ‘…Control’ which is contains the xaml for the dialog and a ‘…Model’. The Model is bound to the Control. The example in this tutorial follows the same pattern.

 

IPackage Implementation

Let’s start at the beginning. When Blend is started, it loads the extensions using MEF. Therefore the extension has to be an implementation of the IPackage interface and has to be decorated with an Export attribute.

 image

The code is pretty simple. From the IServices  provided by Blend, an instance of the IOptionsDialogService is requested. This services contain a collection of all option pages. Every options page is an implementation of IOptionsPage.

 

In this case, a new TutorialOptionsPage is created in the Load method. A new TutorialOptionsModel is passed into this. After that the TutorialOptionsPage is added to the list of option pages.

 

[Export(typeof(IPackage))]
public class OptionsTutorialPackage:IPackage 
{   
    public void Load(IServices services)
    {
        IOptionsDialogService optionsDialogService = 
                services.GetService<IOptionsDialogService>();
            
        TutorialOptionsPage optionsPage = 
               new TutorialOptionsPage(new TutorialOptionsModel(services));
        optionsDialogService.OptionsPages.Add(optionsPage);
    }
 
    public void Unload()
    {
    }
}
 

 

 

 

 

The Options Page

The TutorialOptionPage is basically an implementation of the IOptionPage interface.

 

imageProperties:

  • Content - contains a framework element containing the view of the options page. It should contain input elements to set the configuration options.
  • Title - contains the title of the options page. It is shown in the list on the left of the options dialog.
  • Name - contains the internal name of the page.

Methods:

  • Cancel - is called when the user hits the cancel button of the options dialog.
  • Commit - this is called when the user hits the Ok button.
  • Load - is called when Blend starts.

 

 

 

First, let’s have a look at the declarations and the constructor. The TutorialOptionPage class has to implement the IOptionsPage interface to work. This interface can be found in the Microsoft.Expression.Framework.Configuration namespace. References to the TutorialOptionsControl, and the TutorialOptionsModel, are kept. As well as a reference to the IConfigurationObject interface.

The constructor takes an instance of TutorialOptionsModel and stores it.

public class TutorialOptionsPage:IOptionsPage
{      
    private TutorialOptionsControl tutorialOptionsControl;
    private TutorialOptionsModel tutorialOptionsModel;
    private IConfigurationObject configurationObject;
 
    public TutorialOptionsPage(TutorialOptionsModel model)
    {
        tutorialOptionsModel = model;
    }

 

 

 

 

The implementations of the Title and Name properties is very simple. They both just return a string.

public string Title
{
    get { return "TutorialOptionsTitle"; }
}
 
public string Name
{
    get { return "TutorialOptionsName"; }
}

 

 

 

 

The Content property returns an instance of the TutorialOptionsControl, the UI of the options page. It needs an instance of the IConfigurationObject to load the data for the model. This interface is passed to the Load method which I’ll describe in a second.

If the model isn’t loaded, which happens when the changes in the options dialog are cancelled, a new one has to be instantiated. The configuration data has to loaded as well in this case.

The Load method on the model is called. After this, it is passed to the constructor of the TutorialOptionsControl where it will be bound to the UI.

public object Content
{
    get
    {
        if (this.tutorialOptionsModel == null)
        {
            this.tutorialOptionsModel = new TutorialOptionsModel();
            this.tutorialOptionsModel.Load(configurationObject);
        }
        if (this.tutorialOptionsControl == null)
        {
            this.tutorialOptionsControl = 
                new TutorialOptionsControl(this.tutorialOptionsModel);
        }
        return this.tutorialOptionsControl;
    }
}

 

 

 

 

Right, the Load method of the TutorialOptionsPage class. It takes the IConfigurationObject interface as a parameter, which is provided by Blend. It is stored in the class to use it again later. The model is loaded by using the IConfigurationObject.

 

public void Load(IConfigurationObject value)
{            
    configurationObject = value;
    this.tutorialOptionsModel.Load(this.configurationObject);    
}

 

 

 

 

The Cancel method is called when the user hits the “Cancel” button on the options dialog. Both the TutorialOptionsControl and the TutorialOptionsModel are set to null to make sure they will be reloaded the next time the options dialog is opened.

public void Cancel()
{
    this.tutorialOptionsControl = null;
    this.tutorialOptionsModel = null;
}

 

The Commit method is called when the user hits the "Ok” button on the options dialog to save the settings. First the configurationObject has to be cleared to remove any unwanted settings the might be left over. The Save method on the model is called and the configurationObject is giving to it.

Last both the TutorialOptionsControl and the TutorialOptionsModel are reset to be reloaded the next time they’re needed.

 

 

 

public void Commit()
{
    if(this.tutorialOptionsModel!=null)
    {
        this.configurationObject.Clear();
        tutorialOptionsModel.Save(configurationObject);
        this.tutorialOptionsControl = null;
        this.tutorialOptionsModel = null;              
    }
}

 

 

 

 

The Model

 

In this example, the model contains only two properties, two strings. To make sure the UI will be updated correctly, the INotifyPropertyChanged interface is implemented.

Saving and loading of the properties is done  in the Load and Save methods. Both methods make use of an IConfigurationObject. The properties are saved using the SetProperty method from the IConfigurationObject interface. To load the properties, the GetProperty method is called for each property. The same keys are used as with saving and the returned objects are cast to the correct type.

public class TutorialOptionsModel : INotifyPropertyChanged
{ 
 
    private string _value1;
    public string Value1
    {
        get { return _value1; }
        set
        {
            _value1 = value;
            InvokePropertyChanged("Value1");
        }
    }
 
    private string _value2;
    public string Value2
    {
        get { return _value2; }
        set
        {
            _value2 = value;
            InvokePropertyChanged("Value2");
        }
    }      
 
    public void Save(IConfigurationObject configurationObject)
    {
        configurationObject.SetProperty("OptionsTutorialValue1", this.Value1);
        configurationObject.SetProperty("OptionsTutorialValue2", this.Value2);
    }
 
    public void Load(IConfigurationObject configurationObject)
    {
        Value1 = 
            configurationObject.GetProperty("OptionsTutorialValue1") as string;
        Value2 = 
            configurationObject.GetProperty("OptionsTutorialValue2") as string;
    }
 
    public event PropertyChangedEventHandler PropertyChanged;
 
    public void InvokePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

 

 

 

In an actual extension, the model can be used in other parts of the extension to make the configuration available for other classes. Just make sure you call the Load method.

 

User interface

The user interface for the Options Dialog is just XAML. In this example I have created a WPF UserControl with  two textboxes to let the user enter some text. Both values are stored in Blend's configuration files. The textboxes are bound to the two properties of the model.

image

The XAML that is used to create this UI:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="48" />
        <RowDefinition Height="48" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="124" />
        <ColumnDefinition Width="176*" />
    </Grid.ColumnDefinitions>
    <TextBox Margin="4"  
                VerticalAlignment="Center"                 
                Grid.Column="1" 
                Text="{Binding Value1}" />
    <Label Content="Value 1:"                
            HorizontalAlignment="Right" 
            VerticalAlignment="Center" />
    <TextBox  Margin="4,12" 
                Grid.Column="1" 
                Grid.Row="1" 
                Text="{Binding Value2}"/>
    <Label Content="Value 2:" 
            HorizontalAlignment="Right" 
            VerticalAlignment="Center"  
            Grid.Row="1"  />
</Grid>

 

 

 

 

The data context of this UserControl needs to be set to the instance of TutorialOptionsModel. This is done through the constructor of the control.

public partial class TutorialOptionsControl : UserControl
{
    public TutorialOptionsControl(TutorialOptionsModel tutorialOptionsModel)
    {
        InitializeComponent();
        this.DataContext = tutorialOptionsModel;
    }
}

 

 

 

 

After compiling and starting the options page should look something like this now:

image

 

Classes and Interfaces

Here are the diagrams of the classes and interfaces used in the tutorial.

image

 image

 

Sourcecode

The code for the project can be downloaded here.

 

Share




Mocking LINQ to SQL (Continued…) using OpenAccess

After making the post on mocking LINQ to SQL, this morning i was having a chat with Stephen forte and come to know that Telerik has a new product named Visual Entity Designer that enables you to define your domain model very easily through just few clicks and builds a nice LINQ to SQL model that mimics model similar to Entity framework / MS LINQ to SQL. Being curious, i thought of giving a spin with it and try to mock OpenAccess LINQ to SQL implementation using JustMock.

 

Now, before i start, i also found that OpenAccess has a free / express version that works on top express databases (Ex. SqlExpress) but supports all the features that full version offers. I will be using the free version here. The download is provided at the end of the post along with a link pointing to Steve's introduction of the designer.

 

Once you have downloaded OpenAccess Q2, you first need to create a class library project and inside the add item dialog you need to choose  “Telerik OpenAccess Domain Model” option . Actually, it looks to me same as creating an entity framework edmx just the extension is rlinq.

 image

Next, it will give you an option to choose an empty model or populating it from your database. I would rather choose to populate it from my Northwind database in SqlExpress. That prompts me up with this screen

image

Here to note that i actually first found  the “New Connection” option disabled [may be due to express version] and set my target database using the “Server Explorer” inside visual studio and found it populated as shown above.

Next, i have to choose a model name and by default it suggests “NorthwithEntityDiagram1” but i prefer to choose  “NorthwindDataContext” since things are more with data than with diagram.

image

Once everything is set. I am off to the main topic. I will use the same example from previous post. Accordingly, i created the EmployeeRepository class:

  1. public class EmployeeRepository
  2. {
  3.     public EmployeeRepository(NorthwindDataContext context)
  4.     {
  5.         this.context = context;
  6.     }
  7.  
  8.     public IQueryable<Employee> GetEmployeesByHire(DateTime frm, DateTime to)
  9.     {
  10.         return from emp in context.Employees
  11.                where emp.HireDate >= frm && emp.HireDate <= to
  12.                select emp;
  13.     }
  14.  
  15.     private readonly NorthwindDataContext context;
  16. }

This is plan and simple. There is only method that returns list of employees by hire for a date range. The goal is [those who have missed my previous post] to run the LINQ query into my fake collection to assert the expected behavior of this method.

Therefore, i will be creating a fake data context and for context.Employees i will return my custom collection and finally assert the expected behavior.

  1. [TestMethod]
  2. public void ShouldAssertGetEmployeesByHireDate()
  3. {
  4.     var context = Mock.Create<NorthwindDataContext>();
  5.     var repository = new EmployeeRepository(context);
  6.     Mock.Arrange(() => context.Employees).ReturnsCollection(GetFakeEmployees());
  7.  
  8.     var employees = repository.GetEmployeesByHire(new DateTime(2008, 1, 1), DateTime.Now);
  9.  
  10.     Assert.AreEqual(1, employees.Count());
  11.     Assert.AreEqual(3, employees.FirstOrDefault().EmployeeID);
  12. }
  13.  
  14. private static IList<Employee> GetFakeEmployees()
  15. {
  16.     return new List<Employee>
  17.     {
  18.        new Employee {EmployeeID = 1, HireDate = new DateTime(2004, 12, 1)},
  19.        new Employee {EmployeeID = 2, HireDate = new DateTime(2006, 7, 1)},
  20.        new Employee {EmployeeID = 3, HireDate = new DateTime(2009, 3, 1)}
  21.     };
  22. }

 

That’s it. As “ReturnsCollection” does a number of tasks on behalf of the developer and which is not required for all cases except for IQueryable / IEnumerable implementations, having few feedbacks from my last post, we have made this as an extension method. The reason is not to pull it up every time for mocking members where you don’t need it.  Therefore, when you need it you just have to include the following line on top your class:

  1. using Telerik.JustMock.Helpers;

The helpers extension[from SP1] also gives an opportunity to add more domain specific methods like “ReturnsCollection” without ever cluttering the core API.

----

You can check the introductory post from Steve of Visual Entity Designer here:

http://www.stephenforte.net/PermaLink,guid,734374ef-65ac-442c-a8f1-571ca9084729.aspx

The free version of OpenAccess ORM can be found here (there are other free and interesting tools as well):

http://www.telerik.com/community/free-products.aspx

OpenAccess version of the sample can be downloaded from: Here

-----

Enjoy!!

Update : RLINQ is not a product on its own rather a extension that Visual entity designer generates [Pardon my ignorance].


  • Sponsored Links

  •  

    September 2010
    M T W T F S S
    « Aug    
     12345
    6789101112
    13141516171819
    20212223242526
    27282930  
  • .

    Copyright © 1996-2010 Answer My Query. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress