Erik Lieben

My blog about software development / Mijn blog in astronauten engels :-)

 View Erik Lieben's profile on LinkedIn  Follow eriklieben on Twitter

ASP.NET MVC 4 Mobile Templates: Extending display modes to support iPhone, iPad, Android, AndroidTab, Windows Phone, etc.

The new asp.net MVC bits contain a great new feature that allows you to define a custom view (html) for mobile devices out of the box. The only thing you need to do to enable this is adding .mobile on the end of the filename. As can be seen in the screenshot below. By adding the extra file, it will automatically switch and render the correct html. When there is no html available it will just render the default (desktop) version.

image

While this is a great feature, it doesn’t really fit the needs for building mobile apps, because you would probably soon want to have a custom version for mobile tabs.

Luckily Microsoft made this functionality easy extendable and it even allows you to extend it for different goals.

You can create specific views for any condition that you are able to make with the request object.

 

To keep the sample code simple, below I’ve created code that will switch to a specific view for a given mobile device. So when browsing with an iPhone it will show the iPhone view,

iPad will show the iPad view and Windows Phone will show the Windows Phone view. When no match can be made to my custom matches, it will still perform the check Microsoft build

to check for mobile devices. So for example, you are able to build specific views for the iPAD, other mobile devices and the default desktop.

image

image

 

The code:

To do this you just need to add a few lines of code, first of all from within the Application_start method in the Global.asax.cs add a call to RegisterCustomDisplayModes();

Global.asax.cs

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    RegisterCustomDisplayModes();

    BundleTable.Bundles.RegisterTemplateBundles();
}

image

Then add a method called RegisterCustomDisplayModes():

Global.asax.cs

/// <summary>
/// Register custom display modes
/// </summary>
public static void RegisterCustomDisplayModes()
{
    Dictionary<string, Func<HttpContextBase, bool>> displayModes = new Dictionary<string, Func<HttpContextBase, bool>>
        { 
            { "iPhone", c => c.Request.UserAgent.IndexOf("iPhone", StringComparison.InvariantCultureIgnoreCase) > 0 },
            { "iPad", c => c.Request.UserAgent.IndexOf("iPad", StringComparison.InvariantCultureIgnoreCase) > 0 },
            { "WindowsPhone", c => c.Request.UserAgent.IndexOf("Windows Phone OS", StringComparison.InvariantCultureIgnoreCase) > 0 },
            { "AndroidTab", c => c.Request.UserAgent.IndexOf("Android", StringComparison.InvariantCultureIgnoreCase) > 0 },
            { "AndroidPhone", c => c.Request.UserAgent.IndexOf("Android", StringComparison.InvariantCultureIgnoreCase) > 0 && c.Request.UserAgent.IndexOf("mobile", StringComparison.InvariantCultureIgnoreCase) > 0 }
        };
    displayModes.Keys.ToList().ForEach(
        key =>
        DisplayModeProvider.Instance.Modes.Insert(
            0,
            new DefaultDisplayMode(key)
            {
                ContextCondition = c =>
                {
                    if (c == null || c.Request == null || string.IsNullOrWhiteSpace(c.Request.UserAgent))
                    {
                        return false;
                    }

                    return displayModes[key](c);
                }
            }));
}

image

What the above will do is in order of the above list walk thru the conditions, as soon as there is a match it will redirect it to that view. Because it get’s inserted at the first position, it is always before the default display modes defined by Microsoft (like the mobile one). I am not 100% sure that this is the correct way to catch Android devices, but that is something you could modify easily.


Permalink | Comments (0) | Post RSSRSS comment feed

C# .NET 4.5 Unable to access wcf web service or website on localhost from windows 8 metro application

Hi,

This took me some time to figure this out, so let’s hope this blog posts saves you the time. For some reason you are not allowed to access the local host from a windows metro application in the current developer preview of windows 8. This still can be very useful while debugging and still developing your application.

Still you can setup windows to allow it by doing the following:

  1. Open up your Package.appxmanifest file and copy the ‘Package family name’.
  2. Open up the command prompt
    1. Go to C:\Windows\System32
    2. execute the command: CheckNetIsolation loopbackexempt –a -n=
    3. and paste the Package family name after the -n=
    4. press enter.
      image
  3. Open up your firewall settings and click advanced settings
    image
  4. Select Inbound Rules
  5. Select New rule
  6. Select the option Port in the wizard
    image
  7. Select the port where your web service runs on and click next
    image
  8. On the next screen, click allow the connection and click next
    image
  9. Check all the 3 checkboxes in the next screen
    image
  10. Give the rule a name and save it.

Now it should all work! Be aware you need to either disable your firewall or add a port for each web service you use local. Not sure why this is, but for some reason metro applications run with certain network settings that the firewall blocks. When switching metro apps, don’t forget to run the checknetisolation command.

Happy coding,

Erik


Permalink | Comments (0) | Post RSSRSS comment feed

Building a HRM system with the MVVM pattern–Creating the MVVM base classes

What will this blog post cover?

This blog post will show you the basic elements of an M-V-VM framework and setup the basic infrastructure we require to build our application. It might be that currently (this blog post) doesn’t make sense at all for you, please be patient and continue to read and try to understand as much as possible. When we actually build the application this will all become more clear.

What parts do we need?

To answer this question it’s important to first know how parts will interact with each other.

  1. The communication between the view and the view model will be handled by the use of bindings and commands. The commands feature is a default WPF feature just like bindings.
  2. Communication between view models can be archived with a communication bus, which can be seen as a channel to communicate over. (The communication bus is sometimes also called event aggregator).

Why… why do view models need to communicate with each other?

This allows them to tell each other something changed. For example:

If you have a view model to set the current culture or current project that’s open. Then you want to make all the other view models aware of that the change.

Or if you have a master detail view with 2 view models than at some point you might receive a selected item command execute on one view model and you want to notify the other view model that the selected item is changed.

The visual representation of the parts we require:

image

 

 

 

 

 

 

 

 

 

 

At the top there are styles and templates, these are default WPF features to modify the looks of controls inside your view. Next to what’s shown above, we also require some mechanism to connect the view to the view model. We will start with writing code to do that.

The view model locator

The entrance point of our application is the View. When a view is loaded it should have the data context set to the view model. This allows the communication between those 2 to start. To allow this magic to happen we use the view model locator. This class will allows us to do this without adding code in the code behind and allows use to use dependency injection for it.

How does this works:

In our App.xaml we will add a resource which points to our ViewModelLocator class:

image

Now we can reuse this resource everywhere in our application to set the data context of the view:

image

The class itself is very simple. It is a dynamic object, which will simply call the IoC container (our class that takes care of the dependency injection) to get an object by a given name.

(The code on line 22 is to support this functionality in Silverlight, I discovered that in the current version of SL it’s not allowed to bind to a dynamic object. So in Silverlight you would need to bind to [MainWindowViewModel] to archive the same)

image

With this in place, you’ve got the first part working :-) So on each view we will use, we will call the view model locator with the name of the view model that we would like to bind to and set it as the data context. This will allow you to just data bind to commands and data objects in your view model. Later on I will explain you how the dependency injection works, for now just assume that it will always give back the correct view model. (TODO: add reference to future blog post)

The view model base class

From the view, we now arrived at the view model. Let’s build a base class for this, which we can inherit for each view model to make sure we don’t repeat the default behavior each time. Our view model base class will implements the INotifyPropertyChanged interface, to notify listeners(view) when properties change so the binding can be updated to the latest values.

Below is the code:

image

The NotifyPropertyChanged method will allow you to notify on change of a property (See the sample below for an property called employee). When only implementing the default, the event should be fired with a string that contains the name of the property that changed. This is a little bit risky, because when you refactor and forget to change the string, everything will still compile, but the properties won’t be updated on the bindings. When using the method above, with the expression, you will get compile errors if the name is different and refactoring will always work as you assume.

image

The Culture Manager will be covered later on. This is used to provide the multi language user interface. For now just ignore it.

The Relay command

To communicate from the view to the view model, we will send it commands to react on. These commands will be send using the relay command, which is an implementation of the interface in .NET called ICommand.

The relay command will just execute the assigned Execute command action that is set on it. It’s just someone standing in the middle, when you scream on, he or she will turn a button on (execute the assigned command in this case). The CanExecute predicate allows you to define if the the action is active or not (if a button can be clicked).

In a later blog post, when we start to build the actual application, I will demonstrate you how to activate these commands on button click, mouse over events, etc..

image

Communication between view models

To communicate between view models we require a communication channel/ bus. I’ve didn’t placed this channel in the base view model class, because I think you can have more than 1 channel in your application and this should be handled in the class that inherits from the base class. For example: it can be that you setup a communication channel to communicate messages that are directed at the global application level and one channel that is directed to specific screen that the end user can interact with.

This class is an implementation of the mediator pattern. The mediator pattern defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referencing each other explicitly.

What the object basically does, it keep a register of other classes that are subscribed to a certain message. As soon as you notify the message over the communication channel it will check the register and notify everyone that is subscribed to the message.

image

Most of the code is just default .NET code, so I assume you are able to understand it (it doesn’t feel complex, let me know if I need to explain it more).  Still, there is one weird class in there called weak action.

The weak action implements the weak reference class and allows us to keep a reference to an object (the action) that might be garbage collected. If this was a normal reference and the view model was disposed, the garbage collector would not clean up the view model, because it thinks it’s still alive.. one of it’s objects (the action) is still active on the communication bus. The weak reference will allow the view model to be collected and will just remove the action out of the list to notify, when it’s not active.

The code of the weak action is very basic, it will just create the delegate it’s still alive.

image

And that's end for today, as you can see this isn’t much code. I will walk you thru some of the other basic classes and concepts in the next blog posts, after that we will arrive at the part where we will implement them in real life, so it starts to make sense :-)

Give me the code… I want to play with it.

Currently I looking for time in my schedule to setup a CodePlex project to share this code.

I assume I got this setup and working by the end of next week. I will update this text as soon as everything is setup or you can check the codeplex project site itself http://hrmsystem.codeplex.com/.


Permalink | Comments (0) | Post RSSRSS comment feed

Building a HRM system with the MVVM pattern - Introduction post

What’s this?

This blog post is the start of a series of blog posts that will give insight in building an application from scratch using cool patterns. It’s not the best way; it’s not the worst way; it’s the way I like to follow today :-) I will probably refactor this post along the way.

In this series I will build a sample application that can be used for demonstrating different ideas and allows me to show you the ideas against an actual application. This will allow me to test out the ideas, and allow you as a reader to see how they are implement for real, instead of looking at a sample and thinking, great, how will I get that I my application?

The application

The application we will build is a human resource management system, in short HRM system. In am not an expert in this domain, but I’ve figured I could at least make up something useful to build :-)

Specification

Let’s first start by defining the global domain context and write out what we will build. I’ve sat down with the customer (myself) and created a chart defining what our system will do. This is translated from Dutch, so it might contain wrongly translated words, but I assume you will get the idea.

Global overview of domain

image

So at the top we have our vision, we want to build a great HRM system green. We might have a small document somewhere defining a wonderful destination vision. The next layer down blue is the scope of this application. What will be our focus on during the amount of time we have to build this application?

It consists of the following modules or parts:

  • Employee – which comes down to CRUD on employees
  • Work leave –register and report free time of employees
  • Overtime – register and report the over time of employees
  • Work planning – management, do you have enough employees to complete your tasks
  • Absenteeism – register and manage employees that are ill (short and long term)

The next layer down orange contains the focus areas, this is where we would create use cases / user stories from.

As one of the stakeholders of the application I will throw in extra requirements I want this application to be a multi language application, because one part of the staff of my HR department is Dutch and one part is English. The management of HR is a English speaking person and the employees are Dutch. (This allows me to demo multi language). And the application should run as a windows application on the machines of the HR department employees.

We now have enough functional specification to start. Let’s move to the technical side.

Application Architecture

The application we will build, will be using 3 layers of separation. There are many different ways of separating applications in layers. We will use this one as long as it feels good and maybe later on redefine it when needed.

image

The data layer will be responsible for retrieving and persisting entities used inside the application. It will transform every incoming object to something your domain layer is aware of. In stone age (when there where no computers and only humans): This layer would exist of at least 2 people sitting behind a desk, 1 person that translates your request to an archivist, the archivist will store or lookup what you need, and the translator will translate it back to something you understand. You don’t know  how to translate anything neither know how to store or find something in the archive. They have the knowledge and responsibility to do it for you.

The domain layer contains the mayor part of your application, it knows the applications view of the world around it. For example: In real life, a person can either be male or female. If the application is not gender specific, then it doesn’t care, doesn’t want to know this detail. In stone age, this layer would be the workers that perform the actual work to produce something. They have the knowledge to build something and might talk in ways the customer of the product might have a hard time understanding.

The presentation layer contains the parts the end users will actually see. This are the windows or webpages in applications. In stone age, this can be a little bit seen as the seller of the goods (when he is trying to sell it, not the actual transaction). He promotes the products, and stands in front of the customer and shows them why the should be interested in buying this. If we have multiple sellers of goods, then they all might promote and try to sell the products in a different way, but If they sell or if they require more information they all talk to the workers in the domain layer in one way. They only know what’s been told to them by the workers and they are the experts in translating that to a great story/ experience for the customer so that they will buy the product.

MVC, MVP, M-V-VM which fancy name will we use?

There are many different patters to present your application to the world. One of the most famous ones in WPF world latterly is the M-V-VM pattern, which is the one we will use in this application. Below I will explain the others so you are aware of them. I think this gives you a better understanding of the M-V-VM pattern itself, if you know the history.

Presentation patterns are not something new, they have been around for ages. Today there are even different variations of the single patterns itself. We will not focus on that in this blog post, just be aware they are there.

MVC

The MVC (Model View Controller) pattern was first described in 1979 by Trygve Reenskaug at Xerox Parc http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html. In this pattern the model represents the actual data of the application and the logic to modify it (todays: data entities, repository, data services, etc.), the view represents the user interface with it’s logic and contains the state of the application. The controller takes care of the communication between them. The model is unaware of the controller and the view, so for example the model could be unit tested without them.

image

In short an interaction will work like this:

  • A request comes into the controller
  • The controller finds the correct view and model and combines them together
  • The view knows the current state of the application (for example: if something is modified or if a checkbox is checked)
  • The view will notify the controller synchronize it’s state with the model (for example: if you press the save button, it will fire an event to the controller saying I’ve changed please handle it.)
  • The controller will send the model the changed data and it will verify the data and store it.
  • The model will then notify the view, to let it know the data is changed

image

At first it might seems weird that the model sends out an event to let the view know it’s changed. This is because there can be more than 1 view listening to changes on the model. So if you have 2 views open and change the data in one view and let the controller update the model, both views will update and not only the one that you changed the data in (which basically is already updated, because you made your changes there).

MVP

The MVP (Model View Presenter) pattern was first described in 1996 by Mike Potel at Taligent http://www.wildcrest.com/Potel/Portfolio/mvp.pdf.  It’s a little bit like the next version of MVC or the evolution of the MVC pattern, but you could also identify it as a variant of the MVC pattern. The model represents the same as in the MVC pattern. The view is in charge of rendering the data and contains a direct reference to the presenter to delegate user interaction. The presenter will interpret the interaction and modify the view based upon it. So the presenter will control the view, instead of provide a communication channel, like the controller does in MVC. It will mostly contain a reference to the view in the form of an interface and will directly set property values on the view.

image

In short an interaction will work like this:

  • A request arrives at the view
  • The view delegates the request to the presenter
  • The presenter will load the required data from the model (can be a selection of the model)
  • The presenter will set the data on the view
  • The view will delegate the button press event to the presenter (user pressed save button)
  • The presenter will handle the event and call the model
  • The model will validate and persist the data and modify the presenter it’s updated
  • The presenter will set the new values of the model on the view

image

In this pattern the state of the application is still stored in the view.

PM & M-V-VM

The M-V-VM (Model View View Model) pattern was first described in 2005 by John Gossman at Microsoft http://blogs.msdn.com/b/johngossman/archive/2005/10/08/478683.aspx. It is identical to the PM (Presentation Model) defined by Martin Fowler in 2004 http://martinfowler.com/eaaDev/PresentationModel.html , but is more specific to the binding mechanism which is available in XAML. The main difference between the MVP pattern and this is that the state of the application is moved from the View to the Presenter (or View Model). The M-V-VM pattern is available in a variant called View first and View Model first. We will focus on View first.

image

In short the interaction will work like this:

  • A request arrives at the view
  • The view binds the data context to the view model
  • The view model will initialize itself with data from the model
  • The view is bound to the view model’s properties (will get it’s data that way)
  • The view will delegate the button press command to the view model (user pressed save button)
  • The view model will handle the command and talk to the model if required
  • The model will validate and persist the data and send the view model the updated data
  • The bindings on the view model will update the view

image

Great, so now how will we use this?

To use M-V-VM you can use one of the many frameworks available like MVVM Light http://mvvmlight.codeplex.com/or Caliburn http://caliburn.codeplex.com/. In this system we will build it as simple as possible from scratch. This might not be the best path to take, but I think this path will expose you to the ideas behind it and allow you to pick a framework that fit’s best with your own needs. For now, we will continue with the concepts. The next blog post will focus on creating the base classes (and will contain the actual code yeah!).

You should probably have a global view of the different presentation patterns by now. Since our application contains more than only presentation logic, I will continue to shortly explain the other patterns we will use to build out our application.

Dependency Injection (DI)

DI is a specific form of inversion of control, which is another scary term. DI is simply said a way to remove hardcoded dependencies between objects within your application and inject them dynamically at runtime. Applications with hard coded dependencies are hard to test, maintain, and change.

For example:

If you want to create an object which has 3 dependencies on other objects, that again have 16 dependencies on others, and those have x dependencies on others, etc. etc. Then you need to create them all, but what if you only want to test the functionality of the first object you’ve created and don’t really care about the rest. With DI you can just inject 3 dummy dependencies into the object you want to test, and let them return what you would expect.

In our application we will make use of Ninject (http://ninject.org/) for DI, just because it got a cool ninja logo. You can yourself pick any DI framework you want.

Repository pattern

The repository pattern abstracts away the logic to store objects to a data store. The repository has the following knowledge: how to store and retrieve objects out of the data store (for example a database). Using this pattern will allow you to later on switch the data storage easily, because the application is unaware of the underlying data store. In a later blog post we will look deeper into this. In stone age: This is the desk of the archivist, where you tell them.. I want this.. they are responsible for performing your action and retrieve or store your object.

Unit Of Work

The unit of work pattern will be used together with the repository pattern, to perform a sort of transactions. Let’s say a user adds 5 items separately, but you only want to save them if the user clicks save when closing the application. In a later blog post we will look deeper into this.

What’s next?

In the next blog post, I will show you how to build the core components (base of M-V-VM, repository, etc.) for our application, so we can later start to implement them. After we got this in place, we can go back to the global overview of the domain diagram and pick the functionality we will build first.


Permalink | Comments (0) | Post RSSRSS comment feed

Building a control template/style for the tabControl to clone the office 2010 ribbon File look

image

Looking at the file tab of word 2010, I’ve wondered if a WPF tab control could be transformed to this layout. At first, this felt like something that could never be done, without doing a lot of magic or building it from scratch. After playing around for a while I discovered the power of WPF and it’s enormous flexibility.

The hardest part to figure out was creating the arrow on the right side of the selected item and keeping the light gray border line across the whole left bar. I’ve almost solved this (there is still a small 1px difference in my result), but it’s close enough.

The style I ended up with looks a little bit different than the actual control, but if you need to choose between rewriting a whole control or just only modifying it’s style, then I think accepting difference is more effective than going for the exact clone. And still, if you would want to use this, you would probably still transform it to your taste. You might need to optimize it for your usage, if you want to use it, because I’ve only tested it with the content below. It’s basically for you to learn how to do this, not to just copy & paste and reuse without understanding anything about it Smile

 

 

 

 

 

Let’s start, first of all we will need to get the tab control in place:

<Window x:Class="TestClient.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <TabControl Name="tabSteps">
        <TabItem Header="Info" IsSelected="True">
            <TextBlock>Info content</TextBlock>
        </TabItem>
        <TabItem Header="Recent">
            <TextBlock>Recent content tab</TextBlock>
        </TabItem>
        <TabItem Header="New">
            <TextBlock>New content tab</TextBlock>
        </TabItem>
        <TabItem Header="Print">
            <TextBlock>Print content tab</TextBlock>
        </TabItem>
        <TabItem Header="Save &amp; Send">
            <TextBlock>Save &amp; send content tab</TextBlock>
        </TabItem>
        <TabItem Header="Help">
            <TextBlock>Help tab</TextBlock>
        </TabItem>
    </TabControl>
</Window>

This will create a window, with a tab control like you would expect:

image

What we only want to do is modify the visual appearance of this tab control. To do this, we can make use of control template functionality of WPF. This functionality allows you to modify the rendering of all controls that make use of control templates.

We want to be able to use this control template anywhere, so we need to add a resource dictionary to our project that will contain our control template to reuse it.

Perform the following to add the Dictionary:

  • left mouse click on your project
  • click add
  • pick ‘Resource Dictionary’

Now in this resource dictionary we will add the following XAML code:

    <ControlTemplate x:Key="OfficeTabControl" TargetType="{x:Type TabControl}">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="160" />
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Border Background="#FFE9ECEF" 
                    Grid.Column="0" 
                    BorderBrush="LightGray" 
                    BorderThickness="1" 
                    SnapsToDevicePixels="True" />
            <StackPanel IsItemsHost="True"
                        Grid.Column="0"
                        Margin="0,0,-1,0" 
                        SnapsToDevicePixels="True" />
            <ContentPresenter 
                Content="{TemplateBinding SelectedContent}" 
                Grid.Column="1" 
                Margin="15,0,0,0" />
        </Grid>
    </ControlTemplate>

This will create a control template with the name OfficeTabControl with a grid inside. This grid is divided in 2 columns. We want one for the tabs and one for the actual content inside the tab. The left side of the grid contains a border containing just a gray background and a light gray border line. Above(after in code) this in the same column is a StackPanel containing a property IsItemsHost set to true. This property will indicate that generated items (the tabs) will be placed in this panel. In the second column is a ContentPresenter. This is a placeholder for the content that is defined inside the tab.

Now let’s let our TabControl use our new style, set the Template property to the control template:

    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="OfficeTab.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <TabControl Name="tabSteps" Template="{StaticResource OfficeTabControl}">

To do this, you will need to add the resource dictionary to your window resources. Then set the template to use our control template we’ve just created. When you run the application now, you already see a bit of the structure we want.

image

Now we need to modify the rendering of the Tab control item, this is the tab on the page, which is now on the left side. The rendering of this control can be modified by changing the control template the control. Above the Grid of the control template in the resource dictionary, we will add the following XAML:

<ControlTemplate x:Key="OfficeTabControl" TargetType="{x:Type TabControl}">
    <ControlTemplate.Resources>
        <Style TargetType="{x:Type TabItem}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TabItem}">
                        <Grid SnapsToDevicePixels="True">
                            <ContentPresenter 
                                Name="buttonText"
                                Margin="15,0,5,0" 
                                TextBlock.FontFamily="Calibri" 
                                TextBlock.FontSize="12pt" 
                                TextBlock.Foreground="Black" 
                                Content="{TemplateBinding Header}"
                                VerticalAlignment="Center"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ControlTemplate.Resources>

When we run the application now, we see that we removed the button look from the tabs:

image

Now let’s start adding more style to it. To do this we will make use of visual states.

Visual states can be seen as a method to improve the overlap between the developer (that works in code) and the designer, which designs the layout for a given state. The developer can share certain states, for example mouse over and the designer can create a look for that.

The visual state templates can be added within the Grid. We can set the Normal state and the MouseOver state, to add the mouse over effect. To do this, we need to create a border that contains the background and the visual look of that state.

We add this style by creating 2 borders, one for the gray line on the right side and one for the background color and the light blue top and bottom borders.

<Border Name="hoverShape"
        Height="40"
        Margin="0,0,1,0" 
        SnapsToDevicePixels="True" 
        BorderThickness="0,0,1,0" 
        BorderBrush="LightGray">
    <Border BorderBrush="#FFA1B7EA"
            BorderThickness="0,1" 
            Background="#FFE5EEF9" 
            Height="40" 
            SnapsToDevicePixels="True" />
</Border>

After that we will create the storyboards for the visual states. One for the normal state, which will animate the hoverShape opacity to zero. And one for the mouse over state, which will animate the hoverShape opacity to 1.

<Grid SnapsToDevicePixels="True">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup Name="CommonStates">
            <VisualState Name="MouseOver">
                <Storyboard>
                    <DoubleAnimation 
                        Storyboard.TargetName="hoverShape" 
                        Storyboard.TargetProperty="Opacity" 
                        To="1" 
                        Duration="0:0:.1"/>
                </Storyboard>
            </VisualState>
            <VisualState Name="Normal">
                <Storyboard>
                    <DoubleAnimation 
                        Storyboard.TargetName="hoverShape" 
                        Storyboard.TargetProperty="Opacity" 
                        To="0"
                        Duration="0:0:.1"/>
                </Storyboard>
            </VisualState>
        </VisualStateGroup>

If we start the application now, it will look like below.

image

Time to add the blue selected item bar. Below the hoverShape we will add another border called buttonShape, this allows us to add a 2 pixel darker blue border on the top and bottom of the blue shape.

(You can skip this step) Create a screenshot of the shape you want and open Expression Blend, with the pen tool, create a path that follows the shape you want, see the black line below. Go to, view, xaml, and there you will see your path, the data property contains the values that represent the shape.

image

You can for now just copy the code sample below, this also contains the correct gradient and properties, but I’ve just added the above to show how you can do it yourself.

Your XAML code should now looks like below:

<Border 
    Name="buttonShape" 
    Opacity="0" 
    BorderBrush="#FF0343A6" 
    BorderThickness="0,2" 
    Height="40"
    SnapsToDevicePixels="True">
    <Path 
        Data="M214,108 L346,108 346.125,118.125 337.75,126.125 346.375,134 346.375,143.875 214.25,144.25 z" 
        SnapsToDevicePixels="True" 
        Stretch="Fill"
        Height="40">
        <Path.Fill>
            <RadialGradientBrush GradientOrigin="0.2,0.5" RadiusX="0.8" RadiusY="0.8">
                <GradientStop Color="#FF5FA3F6" Offset="0" />
                <GradientStop Color="#FF0C55B9" Offset="1" />
            </RadialGradientBrush>
        </Path.Fill>
    </Path>
</Border>

When you run the application now, nothing is different yet. That’s because we still need to define the visual states for the selected tab.

When adding the code below, you will add the visual state group SelectionStates and add the behavior/storyboards for the selected and unselected state. As you can see we are again modifying the opacity of shapes to create the effects. To get the text color white, I’ve added the color animation. For some reason this gives an error in the designer, because it is unable to identify the TextBlock, I don’t know why this is yet. I am not a WPF expert, but maybe someone out there knows why this is or how to solve it Smile

<VisualStateGroup Name="SelectionStates">
    <VisualState Name="Selected">
        <Storyboard>
            <DoubleAnimation 
                Storyboard.TargetName="buttonShape" Storyboard.TargetProperty="Opacity" 
                To="1" Duration="0:0:.3"/>
            <DoubleAnimation 
                Storyboard.TargetName="hoverShape" Storyboard.TargetProperty="Opacity" 
                To="0" Duration="0:0:.1"/>
            <ColorAnimation 
                Storyboard.TargetName="buttonText" 
                Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)" 
                To="White" Duration="0:0:.1" />
        </Storyboard>
    </VisualState>
    <VisualState Name="Unselected">
        <Storyboard>
            <DoubleAnimation 
                Storyboard.TargetName="buttonShape" 
                Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:.1"/>
            <DoubleAnimation 
                Storyboard.TargetName="hoverShape" 
                Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:.1"/>
        </Storyboard>
    </VisualState>
</VisualStateGroup>

When we are running the application now, we see it get’s closer to the end result:

image

Still there is one problem, we need to hide the background that is still visible below the arrow. We can do this by adding a white shape below it and add the opacity change to the storyboards for the selected and unselected states.

<VisualStateGroup Name="SelectionStates">
    <VisualState Name="Selected">
        <Storyboard>
            <DoubleAnimation 
                Storyboard.TargetName="buttonBackgroundShape" 
                Storyboard.TargetProperty="Opacity" To="1" Duration="0"/>
        </Storyboard>
    </VisualState>
    <VisualState Name="Unselected">
        <Storyboard>
            <DoubleAnimation 
                Storyboard.TargetName="buttonBackgroundShape" 
                Storyboard.TargetProperty="Opacity" To="0" Duration="0"/>
        </Storyboard>
    </VisualState>
</VisualStateGroup>

When we run the application now, we can see the end result:

image

Have fun. The source for the style can be found here: OfficeTab.xaml (8.37 kb)


Categories: .NET
Permalink | Comments (0) | Post RSSRSS comment feed

Logging with dynamic objects in .NET 4.0 (part 2-n) - user interaction logging

In my previous blog post, you where able to see the starting point of a logging solution I am trying to build. In this blog post we will step into logging the user interaction of the end-user. Sometimes it’s hard to discover how the end-user was able to produce a certain situation/bug. You walk to the desk of the end-user to ask what they did, but they are unable to reproduce their steps. They lost their work, and you want to do something to stop that from happening again.

In this blog post we will look at the basic concept I created for logging the interaction of the end-user with our application. It still needs some polishing, but I just want to get the idea out, and later on improve it, to become a better solution.

I created a very basic application, with 4 buttons and 2 list boxes. The end-users is able to press any of the buttons and drag and drop items from the left list box to the right list box. The submit button will submit it to somewhere. The case: there is a weird kind of bug on our application, but we are unable to get our hands on it. It feels like something that happens at random, and we want to solve the issue. Each time the end-users reports back a list of steps to reproduce the bug, it's almost equal, but still different each time, and each time we are unable to reproduce it.

The application:

image

The xaml if the main window:

    
<Grid>
    <StackPanel Name="stack">
        <Button>TestA</Button>
        <Button Name="btnTestB">TestB</Button>
        <Button Click="Button_Click2" Name="btnTestC">TestC</Button>
        <StackPanel Orientation="Horizontal" Height="220">
            <ListBox Name="lstboxSource"
                        PreviewMouseLeftButtonDown="lstboxSource_PreviewMouseLeftButtonDown" 
                        Margin="12" Width="215"
                        DisplayMemberPath="Name"
                        ScrollViewer.VerticalScrollBarVisibility="Visible" />
            <ListBox Name="lstboxDest" 
                        Drop="lstboxDest_Drop" 
                        AllowDrop="True" 
                        Margin="12" Width="215"
                        DisplayMemberPath="Name"
                        ScrollViewer.VerticalScrollBarVisibility="Visible"/>
        </StackPanel>
        <Button Name="btnSubmit">Submit</Button>
    </StackPanel>
</Grid>

 

Let’s start: To discover what the user did, we want to log the following interaction:

  • Clicking button TestA, TestB, or TestC
  • Dropping of items in the right list box

We can do this by adding logging code to all these controls, but that solution isn’t great. If this would be a bigger application, than that might take a few hours or more to do. After we are done solving the issue it would take ages to remove it again. So I want some way to do this, with the minimal amount of effort.

To get to a solution quickly, I just (for now) assume your application only has one window that you want to trace user interactions on. If you got multiple windows, then you need to implement the same process multiple times. Next to that, I assume you are using a WPF Application (The current solution can, but for now will not, work in a windows forms or web application).

Ok, let’s start. What we want is an easy way to listen to the interaction of the end user within the application. Most of the interactions done by the end-user are performed by interaction with the controls (button, list box,etc.), which fire events. So we need some way to easily attach to those events.

With this idea, I first created the basic structure of how I wanted to define the logging. Below is the example of this:

When the MainWindow is loaded, I want to get all it’s child objects recursive, and add a logging action to the Click event of all of the child objects that are of the type Button. If there is a child object with the name btnSubmit than I want to also listen to the Click event with the handler actionClearLog.

I don’t really like the BindAllOf<ListBox, DragEventArgs> method, because it’s less fluent, but for now it’s the most generic way to define different event handler arguments.

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    GetAllChildrenRecursive(this)
        .BindAllOf<Button>("Click", actionLogClick)
        .BindAllOf<ListBox, DragEventArgs>("Drop", actionLogDrop)
        .Bind("btnSubmit", "Click", actionClearLog);

}

 

The first thing to do is get all child objects (recursive), this is done with an inline function:

// Find all the child dependency objects recursive
Func> GetAllChildrenRecursive = null;
GetAllChildrenRecursive = @do =>
{
    List doList = new List();
    doList.Add(@do);
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(@do); i++)
    {
        doList.AddRange(GetAllChildrenRecursive(VisualTreeHelper.GetChild(@do, i)));
    }
    return doList;
};

 

The BindAllOf<Type> and Bind() methods are extension methods on the IEnumerable<DependencyObject>, to keep the syntax as fluent as possible. I like this more than adding a list of custom objects as filter or definition. The downside is that it will cost more resources to walk the list for each definition.

The extension methods walk the list of DependencyObjects and add the given action as event handler for the given event.

public static IEnumerable BindAllOf(
    this IEnumerable doList, 
    string eventName, 
    Action action)
{
    return BindAllOf(doList, eventName, action);
}

public static IEnumerable BindAllOf(
    this IEnumerable doList, 
    string eventName, 
    Action action)
{
    foreach (var item in doList)
    {
        if (item.GetType() != typeof(Type))
        {
            continue;
        }

        foreach (var @event in item.GetType().GetEvents(
                BindingFlags.Instance |
                BindingFlags.Static |
                BindingFlags.Public |
                BindingFlags.FlattenHierarchy))
        {
            if (@event.Name.ToLowerInvariant() == eventName.ToLowerInvariant())
            {
                @event.AddEventHandler(item, Delegate.CreateDelegate(@event.EventHandlerType, action.Method));
            }
        }
    }

    return doList;
}

 

The bind method for the Submit button, is almost the same, only compares on the name of the element:

public static IEnumerable Bind(
    this IEnumerable doList, 
    string instanceName, 
    string eventName, 
    Action action)
{
    foreach (var item in doList)
    {
        var obj = item as FrameworkElement;
        if (obj == null || obj.Name.ToLowerInvariant() != instanceName.ToLowerInvariant())
        {
            continue;
        }

        foreach (var @event in item.GetType().GetEvents(
                BindingFlags.Instance |
                BindingFlags.Static |
                BindingFlags.Public |
                BindingFlags.FlattenHierarchy))
        {
            if (@event.Name.ToLowerInvariant() == eventName.ToLowerInvariant())
            {
                @event.AddEventHandler(item, Delegate.CreateDelegate(@event.EventHandlerType, action.Method));
            }
        }
    }
    return doList;
}

 

Now we got everything in place, let’s look again at the syntax:

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    GetAllChildrenRecursive(this)
        .BindAllOf<Button>("Click", actionLogClick)
        .BindAllOf<ListBox, DragEventArgs>("Drop", actionLogDrop)
        .Bind("btnSubmit", "Click", actionClearLog);

}

 

At this point we are still missing the action parameters. These are the handler functions to handle the logging actions. In this application the btnSubmit will submit the settings to somewhere, and when that is done I want to clear out the reproducing steps. I just assume that process returns to its initial state and that it’s time to clear the list of steps to reproduce. I don’t want to see all the thing the user did that day (for now). Next to that I want to log the dropping of items on the list boxes, because I assume there is something wrong there. So let’s take a look at the actions:

// The logging actions
Action actionLogClick = (snd, args) =>
{
    Logger.Log.TraceMessage("user interaction", 
        string.Format("{0}The event '{1}' fired on type {2} with the name: {3}",
            DateTime.Now.ToString("hh:mm:ss.fff tt"),
            args.RoutedEvent.Name,
            snd.GetType().Name,
            (snd as FrameworkElement).Name));
};
Action actionLogDrop = (snd, args) =>
{
    dynamic clonedObject = new DynamicClone(args.Data.GetData(typeof(Product)));
    Logger.Log.TraceMessage("user interaction", 
            string.Format(
                "{0} Dropped the a object on the {1} with the name: {2}",
                DateTime.Now.ToString("hh:mm:ss.fff tt"),
                snd.GetType().Name,
                (snd as FrameworkElement).Name),
            clonedObject >> ToFormat.Xml);
};
Action actionClearLog = (snd, args) =>
{
    Console.WriteLine("+-- Clear log --+");
}; 

 

I am using the logger and DynamicClone object from my previous blog post. The actions are pretty simple and just log information. The Drop action will get the object Product (the list box is bound to a collection of Product objects) and transform it to xml, because we want to know what the properties of the object are that the user dropped on the list box. For now, the actionClearLog will just output the clear log text to my console. (The Logger is still outputting logging information to the console prompt)

At this point we should have setup the actions and bound them to all the events and they should write out logging information to the console prompt, let’s see if it works I don't know smile. I will launch the application and click and drag around:

image

What we can see from the log now, is:

  • I clicked a Button that didn’t have a name set (see xaml above, button had no name!)
  • I clicked a Button with the name btnTestC
  • I clicked a Button with the name btnTestB
  • I Dragged the product with the name ‘cc’ from the left to the right box
  • And pressed the Submit button

Yeah! Everything seems to work! Smile

Now it’s time to polish this concept and I think I need to improve it, to easily replay the actions of the end-users, because as a developer I don’t like to follow and endless list of steps to reproduce each time. On one of my next blog posts I will dive deeper into this.

Read the previous part of this series over here:


Categories: .NET
Permalink | Comments (0) | Post RSSRSS comment feed

A Fluent syntax Guard method to perform (pre condition) contracts

Update 11-01-2010: I forgot to include the full source code & I've added compiler conditions to the full source code.
This will make sure the throwing of the GuardException and or gathering of trace information will never get into your production code.

When you accept the fact that all software contains bugs, then you are able to look at ways to minimize bugs. One of those ways is defining contracts for methods. In this blog post I will look at creating pre condition contracts for methods.

With the release of .NET 4, the Contract class was introduced in the namespace System.Diagnostics.Contracts, which allows you to, for example write Contract.Requires(object != null) to implement a pre condition method contracts; This is one way of defining contracts, which currently also integrates very well with tools like Microsoft Pex. Before the contract class there where a lot of different ways people would implement pre condition contracts. In this blog post I will show you another (different) way, which is more fluent and is easier to read. (One downside is that it might be less compatible with Microsoft Pex at the moment).

To understand the syntax and the concept of pre condition contracts that we are going to build in this blog post, its essential to understand the story below:

Once upon a time, there was a very friendly and proud guard standing in front of the castle, he was guarding the castle door with his weapon of choice. Friendly and politely as he was, he pointed his weapon of choice towards anyone that didn’t fit to the rules defined by the king and would say “I am sorry, but you are unable to enter the castle, because..”.

The guard in the story above, will not let any ill people pass, because the king doesn’t want any disease between his safe castle walls. The king instructs the guard to get his illness sword out and tell them to walk away, because the king doesn’t wants ill people inside his walls. This way, he keeps the diseases out and everyone is safe.

When looking at the pre condition method contracts, you are that king. You decide what the rules(conditions) are to enter and which sword (Exception) the Guard should throw at any person (object) that doesn’t fit the condition required. Your castle; is the current method to enter.

Now it might be fun to read a programming concept converted to middle age history story, but its important to understand this part deeply. If you don’t define the rules correctly, than the guard will not do it’s job correctly. If the king didn’t made a rule to keep thief's out, then the guard would just let them in. I hope this makes it clear that you are responsible for thinking good and deep about the rules that are required to keep the disease outside of your method. If you don’t trust the people the guard let’s in, then make sure the guard doesn’t let them in (.. the next time).

When using pre and post condition contracts, you are able to define the requirements of the method and describe in some way what it should do. When looking only at the ill people, the guard would take care of the incoming people by a given set of rules, the doctor would take care of making sure the people would leave the castle walls healthy by a checkup(checklist). As long as the guard didn’t had more rules to allow or disallow people and the doctor would not let people out less healthy then his checklist defines, then this process could continue forever. A salesman could move from castle to castle and back to sell his goods. So when you require no more rules, and promise to return no less, than the requirements of the method will stay the same. This important to realize, because it will determinate the stability of your method.

Enough explaining, let’s build the guard class. The syntax will look like the following code snippet:

Guard
    .With
    .Against(country == null)
    .Say("The parameter country cannot be null");

 

There is the guard, he will guard this method with a ArgumentNullException against the instance country being null, and he will say “The parameter country cannot be null”; You will always only use the Guard method calls on the beginning of a method, not in the middle of it. Because the guard is guarding in front of the castle, not from his house inside the secure walls.

To be able to use this syntax, we need to define a class called Guard, with an Inner class called With<>, this class contains the method Against. If the condition given is false, the the guard will let you in and return null. In the else statement it will return a instance of the Guard object (covered later on), this allows the Extension method Say to be called after the method Against is called.

[DebuggerStepThrough]
public class Guard
{
    [DebuggerStepThrough]
    public static class With where E : Exception, new()
    {
        public static Guard Against(bool condition)
        {
            if (!condition)
            {
                return null;
            }

 

The Say extension method will just look to see if the guard is null (it already let the person in, the guard doesn’t need to say anything), and throw the exception to say something.

One of the biggest problems with this usage is that the last method in the chain throws the exception, while the Against method already contains the rule. You might forget to let the guard actually say something, and then no Exception is thrown, while you assume it is. To me it’s just a general rule to always say why you don’t allow this user to enter, because our guard is nice and friendly. To handle this case where you forget to let the guard say something, we will throw an GuardException. This is a little hard to do, since the guard method doesn’t know if a say method is called, after it’s done walking the code inside the method!

I’ve solved this, with a solution that is not 100% perfect, but I think it will hit you in the face in most cases (if you forget to add the Say method call). First let’s continue a bit, on the Guard method, the else statement:

else
{
    StackTrace trace = new StackTrace(Thread.CurrentThread, true);
    StackFrame frame = trace.GetFrame(1);

    return new Guard { 
        ExceptionType = typeof(E), 
        Handled = false,
                        
        FileName =  frame.GetFileName(),
        Method = frame.GetMethod().Name,
        LineNumber = frame.GetFileLineNumber(),
        ColumnNumber = frame.GetFileColumnNumber()                   
    };
}

 

I retrieve some StrackTrace information to determinate where in the code, the method Against is called, this is used later on. I return an instance of the Guard class and set the type of exception to throw.

The Say method, will always throw the Exception, because we are now at the point where the Guard has his sword in his hand and is about to make his statement.

[DebuggerStepThrough]
public static class GuardExtensions
{
    public static void Say(this Guard guard, string message, params string[] args)
    {
        if (guard == null) return;
        guard.Handled = true;

        ExceptionUtil.Throw(message, guard.ExceptionType, args);
    }
}

 

The ExceptionUtil class is just a class to allow throwing exceptions from one place.

The method that get’s called looks like this:

[DebuggerStepThrough()]
public static void Throw(string message, Type exceptionType, params object[] args)
{
    // workaround for bad .NET framework implementation, message argument should always be first argument.
    Exception exception;
    if (exceptionType == typeof(ArgumentNullException) && args != null && args.Length == 1)
    {
            exception = (Exception)Activator.CreateInstance(exceptionType, args[0], message);
    }
    else
    {
        exception = (Exception)Activator.CreateInstance(exceptionType, string.Format(message, args));
    }
    throw exception;
}

 

We’ve now got everything working, let’s get back to handling the case in where you forget to add the Say method. As can be seen in the code samples above, the say method set’s the Boolean Handled to true on the Guard instance. This instance is only created when calling the Against method and the condition is true, when it’s false it will just return null. So if you forget to add the Say method the Handled property will stay false.

We already know that we can’t look forward in time, to find which extension methods it might call. And I don’t want to set a timer object on the Guard object to determinate if the Say method (or some event) is called, but what I can do is make use of the destructor of the object, which gets called when the garbage collector runs. So as soon as the instance gets destroyed, it will check if the handled boolean is true, if this object had a call from the extension method Say. I agree that this is an event that you can’t really control, but it’s just to protect you from using it wrong, so I am ok with that. I’ve didn’t see it go bad yet…

~Guard()
{
    if (!Handled)
    {
        ExceptionUtil.Throw("The Guard has nothing to say at file {0}, method {1}, line {2}, column {3}",
            typeof(GuardException), FileName, Method, LineNumber, ColumnNumber);
    }
}

 

When for example you add the following code:

Guard
    .With
    .Against(1 == 6);

 

It will throw the following exception when the garbage collection starts, to show you how dumb you are Winking smile

image

And that’s the end of it, I hope you’ve enjoyed this post and it was understandable, the full code is attached to this post, see below.

I will probably later on blog about a method to perform the post condition method contract.

Guard.cs (4.50 kb)


Permalink | Comments (0) | Post RSSRSS comment feed

Logging with dynamic objects in .NET 4.0 (part 1-n)

Often, you reach the point where you need a way to monitor your applications once they are deployed to a production server or to the end user. This can be done by using one of the many logging frameworks, or just by using the build-in trace class in the System.Diagnostics namespace. While most of these frameworks work perfectly fine, they do add an extra dependency on external code that you don’t have control over. If you ever want to swap out the framework with a different framework, because you don’t like the direction it goes, then you might be stuck with a lot of specific method calls or code that doesn’t work well with the new framework.

I have been playing around with the idea of creating something that will abstract away this dependencies and return to a dependency on my own code, which I can control. I came up with the interface below, which is as close to the basics as I could get it and still allows the more advanced scenarios. If my application is only dependent on the interface below, then the logging framework is abstracted away and I can easily switch logging frameworks by just changing the class that implements the ILogger interface. This class can then for example be injected into the objects by using dependency injection. The interface contracts below define what my logger should do. It might be that a framework I pick does less, and for example if I need to throw away the category information or find a different way of logging the categories (by reformatting the message to contain the category).

public interface ILogger
{
    void DebugMessage(string category, string message, params object[] values);
    void TraceMessage(string category, string message, params object[] values);
    void Warning(string category, string message, params object[] values);      
    void Error(string category, string message, params object[] values);
    void Fatal(string category, string message, params object[] values);
}

 

This interface defines 5 methods, where each method requires a category, message, and an optional set of objects named values. This array of objects allows you to send extra data to the logger, which I will cover later on.

The implementation for now:

public class Logger : ILogger
{
    private static ILogger _logger = null;
    public static ILogger Log
    {
        get
        {
            if (_logger == null)
            {
                lock (typeof(ILogger))
                {
                    if (_logger == null)
                    {
                        _logger = IoC.Container.Get();
                    }
                }
            }
            return _logger;
        }
    }

 

 

The Logger class contains a static property named Log that contains the instance that implements the interface ILogger that I will use. I am using a container around my dependency injection framework, so the “IoC.Container.Get<ILogger>()” will return back the instance that I bound to the interface ILogger during initialization of the application (If you don’t know anything about dependency injection, just read it as “_logger = new Logger()” for now, that’s ok). I will just implement the logging container in the logger class, because I currently have no intent to extend it to multiple ways of logging and this keeps it simple.

For this example I’ve just implemented it to write messages to console.out:

public void DebugMessage(string category, string message, params object[] values)
{
    Guard.With
        .Against(category == null)
        .Say("The category cannot be null");
    Guard.With
        .Against(message == null)
        .Say("The message cannot be null");
    Guard.With
        .Against(String.IsNullOrWhiteSpace(message))
        .Say("The message cannot be an empty string");

    Console.WriteLine(string.Format("DEBUG ({0}): {1}", category, message));
    // TODO: Show values..
}

 

 

So when in code I use:

Logger.Log.DebugMessage(
    "system",
    string.Format("Starting up the application at {0}", DateTime.Now.ToLongTimeString()));

 

 

It will write to the console prompt:

DEBUG (system): Starting up the application at 12:12:12

Sending debug and trace messages is often not enough. While at first you might think, yes I got it, the process hangs here and that’s because this value is negative or something like that. While testing this on your machine it might be that it will never be negative, because the end user performs certain tasks that you don’t or the production server has another setup. So only having trace messages, mostly means that you don’t have enough information to actually do something about the problem. One option is to write out the missing information, but I don’t want to write a zillion log messages to get each property visible that I think I might need. This will cost a lot of time to write and will just generate a lot of clutter in the log.

The optional objects array solves this, by allowing you to log the state of objects during the sending of the trace messages. Be aware that this will costs extra resources of the enviroinment, so only place it on objects that you assume to help you out. Now you are able to store the state of the objects that are relevant to the trace message on the local machine of the user or send them out to a database and reference them back to the trace message. This works quite perfectly, but sadly it doesn’t work that great when we got objects that are not xml serializable, because you want some way to send or store them.

To solve this issue, I needed some other way of casting the objects to a readable format that can be processed in some way, I don’t want to look at 400 files, because there might be something different in the property of a certain object. While xml serialization is good for this, I don’t actually need it, because I don’t really care about the de-serialization of the xml. I can just run XPath queries against  the plain xml, that’s fine.

After playing for a while I figured out a solution that uses the DynamicObject that is new in .NET 4.0. When you inherit this class you get a dynamic instance that allows you to do fun things. Below is the example of how this works.

First of all, I’ve created the trace message method. It’s just writing its output all to the console prompt, just to keep this example simple as shown below.

public void TraceMessage(string category, string message, params object[] values)
{
    // Method contracts
    Guard.With
        .Against(category == null)
        .Say("The category cannot be null");
    Guard.With
        .Against(message == null)
        .Say("The message cannot be null");
    Guard.With
        .Against(String.IsNullOrWhiteSpace(message))
        .Say("The message cannot be an empty string");

    // Write the trace line
    Console.WriteLine(string.Format("TRACE ({0}): {1}", category, message));

    // Write out the objects
    Console.WriteLine("--[ Objects ]---------------------------------------------------");
    if (values != null)
    {
        foreach (var value in values)
        {
            if (value == null)
            {
                continue;
            }

            Console.WriteLine(value.ToString());
            Console.WriteLine("-----------------------------------------------------------");
        }
    }
}

 

 

The above allows me to send objects and get them printed out to the console prompt. This way I don’t have to worry about how it’s stored for now and I can just see everything quickly in the console prompt. While this is not handy later on, for now it is okay, because I will only have a few logging messages.

So let’s start writing an console prompt test application, I start the console application by just writing the current time to the debug log.

static void Main(string[] args)
{
    Logger.Log.DebugMessage(
        "system",
        string.Format("Starting up the application at {0}", DateTime.Now.ToLongTimeString()));

 

 

Then I request some user input and we will create an object from that.

In this case a timespan, this was just for testing, because a timespan cannot be xml serialized ;-)

// Get the input from the user
Console.WriteLine("How much time do you need to walk around the world? (in hours)");
int hours = 0;
int.TryParse(Console.ReadLine(), out hours);

// Create the object
TimeSpan t = new TimeSpan(hours, 0, 0);

 

 

So now we have the timespan object and want to perform some logging. In this case this might be a little odd, but just imagine a more complex scenario. It’s time to check if we need to send a trace message. Let’s check if the total hours is less than a day (No one can walk that fast). And if so, create an instance of the class I wrote that inherits from the DynamicObject named DynamicClone.

// Trace the result, because it seems the user is trying something odd
if (t.Days < 1)
{
    dynamic clonedObject = new DynamicClone(t);

 

 

When calling the constructor you supply an object to clone. The DynamicClone object will take care of cloning all the properties on the supplied object. This will mean you will end up with the following object:

image

Ok, let’s start the fun. If you enter you can walk around the world in a day, then I assume you are drunk. So I want some way to store that, without sending another log message. Instead of assuming the end user is drunk, just imagine you want to store some extra data to the object.

For example: if it’s an object accessing a file, you might want to store if the file is still accessible at the time of writing the log message, the file size, or something else. So I’ve just going to add my own property to the object named Message, with the following code:

clonedObject.Message = "We got another drunk participant...";

 

 

As you might see in the above image, the property “Message” doesn’t exist yet! It will be created as soon as I set it, sort of on the fly.

I’ve also added some example code that creates an array and stores the user input, just to demonstrate it. The WhatDrinksDidTheUserOrder get’s filled with a list of the logical drives that exist on the machine, so for example: “C:\”, “D:\”.

// for the demo only, probaly not what you want in a real app
if (hours < 10)
{
    Console.WriteLine(string.Format("Why do you think you would be able to do this in {0} hours?", hours));
    clonedObject.UserMessage = Console.ReadLine();
    clonedObject.WhatDrinksDidTheUserOrder = Directory.GetLogicalDrives();
}

 

 

At this time we have the properties of the TimeStamp and the properties Message, UserMessage, and the collection WhatDrinksDidTheUserOrder. Once again to remind you, those properties didn’t need to be defined in the class, since this is a dynamic object.

It’s time to send the message to the trace log:

// Log the message to the trace logger
Logger.Log.TraceMessage(
    "user interaction",
    "Created the timespan given by the user",
    clonedObject >> ToFormat.Xml);

 

 

The first part is just the category and message string, while the second part converts the dynamic object to xml.

I don’t know if this is the most understandable syntax, but it looks the most fancy ;-).

Maybe, just a method call is clearer, but I wanted to play around a bit. The current syntax makes it look more like the dos prompt “dir > dirlisting.txt”. I didn’t use the single > because that might be confused with the well-known greater than comparison sign.

Let’s look at the command prompt to see what happens:

image

So currently you get a mix of the actual application and the logging information. Just to remove any confusion, if the logging was done to a file, the console should have only said:

image

As you can see in the highlights the debug messages where displayed on the screen, and the xml data was displayed containing all the properties of the Timespan object, the object that is normally not xml serializable, extended with the Message, UserMessage and WhatDrinksDidTheUserOrder properties that where added later on and didn’t belong to the Timespan object.

Below is the xml formatted and better readable:

image

If this doesn’t sound any useful at all, then it might help to say that we now used the Timespan object,

but could have also used the current http context or something like that, which is a lot bigger.

This is the end of my first blog post and I hope you enjoyed it Smile

Now it’s time to cleanup code and improve the xml serialization of more complex objects, resolve circular references, and more.

In the following posts of this series I will cover those and at the end when it’s done share the code somewhere.

Have fun!


Categories: .NET
Permalink | Comments (0) | Post RSSRSS comment feed