Working on Dexter

Print Content | More

I’m not writing many posts in the last days and the main reason is I’ve actively joined the development of Dexter a new open source blog engine written in ASP.NET MVC, you can find it on Codeplex at this link: http://dexterblogengine.codeplex.com/

When my friend Andrea Balducci, talked to me about this project I was so excited I decided to give it a try...and it was good (there’s always room for improvement, but it was good!).

I do love Wordpress, it’s a great product and works very well, why working on another blog engine then? well the answer is short: I’m a developer and I don’t know how to put my hands on the WP engine...simply cause I hate php and never spent more than a couple of hours trying to learn it.

With Dexter is all another story...C#, ASP.NET MVC, NHibernate, Castle etc etc I feel home and (even better) I have the freedom to make experiments on the core engine too.

Since I joined I focused on looking at the implementation and adding the features I needed first. So what I was working on the past days:

  • Improve the import engine to support Wordpress (I’m very close to fix all that I need), you can see a live version of my blog using Dexter at this link: http://dexter.primordialcode.com/
  • Adding a better support for Windows Live Writer improving the different Metaweblog APIs support.
    I just added the hierarchical visualization of category (no more flattening out) and the ability to post the tags related to each post using WLW (no more need to add them at the body of the message).

Here’s a screenshot of the thing:

DexterLive

What I’m working on now:

  • Adding the ability to tie a single Post to more than a single category.
  • Improving the import routines.

All the changes are actually in my private Branch and will be merged to the main trunk once all the developers have reviewed them.



Asp net mvc, Blog engine, Dexter

2 comments

Passing JSON serialized objects to a WCF service with jQuery

Print Content | More

You can find a lot of posts on the web on the subject, why writing another one then? Simply because despite all the documentation I’ve already found on the web, while trying to put it in action I’ve spent a couple of hours in making that work, so I’ll use this post to recap all the action I made as a reference guide for my future implementations.

The scenario is: we have a WCF service that is able to accept call to methods with complex parameters (like Messages object in a simple web chat project) and we want to be able to use those methods with jQuery with the minimal impact on the service implementation.

WCF Service setup

We consider a very simple implementation, you don’t have to use any ‘strange’ or unusual attribute here:

The message class we are sending back and forth:

/// <summary>
/// a single message in a conversation
/// </summary>
[DataContract]
public class Message : Entity<int>
{
    /// <summary>
    /// the nickname of who is sending the message
    /// </summary>
    [DataMember]
    public virtual string Sender { get; set; }
 
    /// <summary>
    /// this will be assigned when the object get persisted into the storage, not before
    /// once assigned it's likely to not be modified again
    /// </summary>
    [DataMember]
    public virtual DateTime Timestamp { get; set; }
 
    [DataMember]
    public virtual string Text { get; set; }
}

A test service implementation

/// <summary>
/// service used to serialize/desierialize the data in JSon for JQuery
/// </summary>
[ServiceContract]
public interface IChatService
{
    /// <summary>
    /// return a simple message
    /// </summary>
    /// <returns></returns>
    [OperationContract]
    Message TestMessage();
 
    /// <summary>
    /// a test function that takes a message and returns it modified
    /// </summary>
    /// <param name="msg"></param>
    /// <returns></returns>
    [OperationContract]
    Message TestMessageModify(Message msg);
 
    /// <summary>
    /// a test function that get multiple parameters and return a message
    /// modified
    /// </summary>
    /// <param name="msg"></param>
    /// <param name="id"></param>
    /// <returns></returns>
    [OperationContract]
    Message TestMessageModifyWithSuppliedContent(Message msg, int id);
}
[AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed )]
public class ChatService : IChatService
{
    public Message TestMessage()
    {
        return new Message() { Id = 1, Sender = "Test", Text = "1 - Text message.", Timestamp = DateTime.Now };
    }
 
    public Message TestMessageModify(Message msg)
    {
        msg.Text = "2 - Modified message";
        msg.Timestamp = DateTime.Now;
        return msg;
    }
 
    public Message TestMessageModifyWithSuppliedContent(Message msg, int id)
    {
        msg.Text = "3 - Second parameter passed: " + id;
        msg.Timestamp = DateTime.Now;
        return msg;
    }
}

The only thing needed is the ‘AspNetCompatibilityRequirements’ attribute.

All the magic is done in the WCF configuration section:

   1: <system.serviceModel>
   2:     <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
   3:     <services>
   4:         <service name="RemoteAssistance.Services.Impl.ChatService"
   5:                  behaviorConfiguration="DebugJSonBehavior">
   6:             <endpoint address="" 
   7:                       binding="webHttpBinding" 
   8:                       behaviorConfiguration="DebugJSonBehavior"
   9:                       contract="RemoteAssistance.Services.IChatService">
  10:                 <identity>
  11:                     <dns value="localhost" />
  12:                 </identity>
  13:             </endpoint>
  14:             <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  15:         </service>
  16:     </services>
  17:     <behaviors>
  18:         <endpointBehaviors>
  19:             <behavior name="DebugJSonBehavior">
  20:                 <enableWebScript />
  21:             </behavior>
  22:         </endpointBehaviors>
  23:         <serviceBehaviors>
  24:             <behavior name="DebugJSonBehavior">
  25:                 <serviceMetadata httpGetEnabled="true" />
  26:                 <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true" />
  27:             </behavior>
  28:         </serviceBehaviors>
  29:     </behaviors>
  30: </system.serviceModel>

To activate JSON serialization and deserialization for an end point we have to supply some information:

  • in line 7 we set the binding to ‘webHttpBinding’, this is the main actor the inject the JSON DataContract Serializer into the WCF stack.
  • in line 8 we set a specific endpoint behavior for this end point
  • lines 18-22 enable the endpoint behavior that makes it possible to consume the service from ASP.NET AJAX web pages.

Consuming the web service is the real ‘tricky’ point, calling a function without parameter is extremely easy, you can use code like this:

   1: $(document).ready(function() {
   2:     $.ajax({
   3:         type: "POST",
   4:         url: "http://localhost:58829/ChatService.svc/TestMessage",
   5:         data: "{}",
   6:         contentType: "application/json; charset=utf-8",
   7:         dataType: "json",
   8:         success: function(data) {
   9:             //debugger;
  10:             alert(data.d.Text);
  11:         },
  12:         error: function(XMLHttpRequest, textStatus, errorThrown) {
  13:                 debugger;
  14:            alert("Error Occured!");
  15:         }
  16:     });
  17: });

Things get a bit ‘complicated’ when you actually have to pass parameters (special tanks here go to my fellow Alkampfer for helping me find the solution). To pass a parameter successfully you have to supply as the data argument (line 5) a string that is the JSON representation of a JS object which properties matches the parameter name of the function you are calling, the parameters’ values are the actual values that will be sent to the server. If the parameter itself is a complex object (that is a class) you need to supply the JSON representation of the object, Let’s use an example to clarify:

if we want to call the TestMessageModify(Message msg) function we need to supply ad data parameter a JS object made like this:

   1: var msg2 = { "msg": { "Id": "2", "Sender": "Webpage", "Text": "Sended Text"} };

We’re defining an object that contains a ‘msg’ property (same name of the function parameter) which in turn contains another object (defined by the same properties that our Message object have, to allow JSON deserialization to work). What we need to pass to the ‘data’ argument of the function call is the string representation of object:

'{"msg":{"Id":"2","Sender":"Webpage","Text":"Sended Text"}}'

To have the JSON representation of JavaScript object we can use an external library like this one: http://www.JSON.org/json2.js

So, to call TestMessageModify(Message msg) and TestMessageModifyWithSuppliedContent(Message msg, int id), we can use the following code:

var msg2 = { "msg": { "Id": "2", "Sender": "Webpage", "Text": "Sended Text"} };
 
$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "http://localhost:58829/ChatService.svc/TestMessageModify",
        data: JSON.stringify(msg2),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            alert(data.d.Text);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            debugger;
            alert("Error Occured!");
        }
    });
});
 
var msg3 = { "msg": { "Id": "2", "Sender": "Webpage", "Text": "Sended Text"}, "id" : "1" };
 
$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "http://localhost:58829/ChatService.svc/TestMessageModifyWithSuppliedContent",
        data: JSON.stringify(msg3),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            alert(data.d.Text);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            debugger;
            alert("Error Occured!");
        }
    });
});

It ended up being a quite long post for something that should have been much more simple.

Javascript, Jquery, Json, Wcf, Wcf service

7 comments

Castle Windsor enabling XML configuration files in Silverlight

Print Content | More

When a version of Castle Windsor able to run in Silverlight was released I started to play with it, basically because I have a lot of code that use it inside my line of business infrastructure framework. I’m working on a WPF/Silverlight solution and I’ve developed a framework that work in both the environments.

One of the biggest thing I miss in every ‘Silverlight-enables’ IoC system I tried is the ability to read and parse XML configuration files.

The current release does not allow Silverlight to parse XML configuration file, because all the parser is based on classes that are in the System.Xml namespace and that weren’t included in the Silverlight runtime.

The good news is Silverlight has a very good support for Linq To Xml, so I decided to do a ‘test of feasibility’ and switched the current implementation from using the XmlDom to Linq To Xml.

I have to admit it was more complex than I thought at start (mainly because I had to understand how the parser was written), here are the steps I followed:

  1. Download the ‘Inversion of control’ portion the Castle Windsor trunk an check the project to find the classes to modify: the good news is: all of them are inside a single folder ‘Castle.Windsor\Configuration\Interpreters’
  2. Start with the .Net solution and replace the usages of the ‘old’ XmlDom classes (XmlDocument, XmlNode, etc...) with the new one from System.Xml.Linq (XDocument, XElement, XNode...). Beware it’s not that easy!
    Both these systems act in slightly and sometime subtle different ways so I had to make ‘heavy’ modifications to all the class of the parser.
  3. Keep modifying and fixing the XmlInterpreter and all the other classes until all the tests for the .Net solution pass. At this stage the major modification were the introduction of a LinqToXmlConfigurationDeserializer to replace the standard one and a LinqExtensions class that contains extensions methods to mimic functionalities present in System.Xml.* classes and not directly exposed by Linq classes.
  4. Open up the Silverlight solution, include the new files and verifies it compiles...here some more minor modification were needed to exclude a couple of portions of code that really aren’t available in Silverlight.
    Good! It compiles!
  5. Let’s see an overview of all the files that were modified:
    CastleSilverlightInterpreters All the files we touched are inside the Configuration/Interpreters folders, no other section was modified.
  6. Let’s create a very simple Silverlight Test Application and check it on the ‘Field of Glory’:
    [TestClass]
    public class Tests
    {
        private string config = "<configuration><components>" +
                                "<component id=\"child\" " +
                                           "service=\"SilverlightTest.Domain.IChild, SilverlightTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" " +
                                           "type=\"SilverlightTest.Domain.Child, SilverlightTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" />" +
                                "<component id=\"parent\" " +
                                           "service=\"SilverlightTest.Domain.IParent, SilverlightTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" " +
                                           "type=\"SilverlightTest.Domain.Parent, SilverlightTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\" />" +
                                "</components></configuration>";
     
        [TestMethod]
        public void ComponentRegistrationString()
        {
            WindsorContainer container = new WindsorContainer(new XmlInterpreter(new StaticContentResource(config)));
            // resolve the object
            IParent p = container.Resolve<IParent>();
            Assert.IsNotNull(p);
            Assert.IsInstanceOfType(p, typeof(Parent));
            Assert.IsNotNull(p.ChildConstructorDependency);
            Assert.IsInstanceOfType(p.ChildConstructorDependency, typeof(Child));
            Assert.IsNotNull(p.ChildProperty);
            Assert.IsInstanceOfType(p.ChildProperty, typeof(Child));
        }
    }

and let’s run it:

CastleSilverlightXmlFileResult

Cool! It works: you can now feed up the configuration even from an XML file to the Silverlight version of Castle Windsor too (you can his file from a database a web service or download it directly..that’s up to you).

What’s left to do: as I said before this whole thing started as an experiment and the code is not clean, not optimized nor checked for memory leaks. Plus actually I modified the parser classes and ‘lost’ the previous implementation (I was lazy and I didn’t wanted to write some new tests...I just reused the old ones :D). Some more work is needed to create a full new implementation (parallel to the old one) and write some additional tests for it.

Actually I see only a potential problem and that is how to deal with configuration file inclusion: we should be able to inject an external handler that tells to the processor how to retrieve the resource (we cannot have access to physical files directly (except for those on the Isolated Storage)...so this feature still need some more thinking.

Plus the actual code it’s not very clean and contains a couple of hacks I’m not very proud of and would like to get rid of :D

I think that a good move can be to create a new ‘Castle.Windsor.Configuration’ project and move the configuration code there.

Here is the full source code of this sample if you want to download and try it, it contains the full trunk portion of the Inversion Of Control section in Castle Windsor:

I will submit this code to the Castle Dev Team and see what they think about it.



Castle windsor, Configuration, File, Silverlight, Xml

4 comments

Castle DynamicProxy - a dirty trick to call invocation Proceed() multiple times in an interceptor

Print Content | More

This is a typical scenario: you have a remote service (a database a web service...anything) which can have connection problems; obviously you don’t want your application to crash the desired behavior can be to retry the operation for a couple of times and then ask the user what to do (with a message box maybe).

Implementing this in Spring.Net is quite easy, here is some ugly code that build up a skeleton for the feature:

[System.CLSCompliant(false)]
public class ExceptionHandlerDaoAroundAdvice : IMethodInterceptor
{
    
    public object Invoke(IMethodInvocation invocation)
    {
        // endless loop to let the user retry the operation in case of db error
        
        int tries = 0;
        while (true) {
            try {
                tries += 1;
                
                object o = invocation.Proceed();
                return o;
            }
            catch (SqlClient.SqlException ex) {
                HandleDbException(ex, tries);
            }
            catch (NHibernate.ADOException ex) {
                HandleDbException(ex, tries);
            }
        }
    }
    
    // log the error and ask user if they want to retry, if not abort program
    private void HandleDbException(Exception ex, int tries)
    {
        // examine the exception and
        // in case of connection problems
        // use your session or connection manager to close any pending connection, thay are not valid anymore;
        if (tries < 4) {
            // let's wait a bit before retry
            Threading.Thread.Sleep(2000);
        }
        else {
            // todo: call here the service that have to ask the user what to do: wait more and retry,
            // contact the network administrator or close the application for example
        }
    }    
}

to wire it to a proxy generated around your object you can write something like:

ProxyFactory factory = new ProxyFactory(YOUROBJECT);
factory.AddAdvice(new ExceptionHandlerDaoAroundAdvice());
return factory.GetProxy();

But since I already use Castle Windsor as my IoC system and DynamicProxy for the lazy loading with NHibernate, in order to reduce the number of assemblies and external library my application uses, inspired by this great series of articles by Krzysztof Kozmic I decided to swap out Spring.Aop and use Castle’s Dynamic proxies.

The first implementation was more or less a plain translation of the code shown above and surprisingly I got an InvalidOperationException for calling invocation.Proceed() multiple times inside the Intercept() method of the interceptor.

To verify this I setup a simple test case with an adhoc interceptor that called invocation.Proceed() multiple times:

public interface ITestClass
{
    void TestMethod();
}
 
public class TestClass : ITestClass
{
    public void TestMethod()
    {
        Console.WriteLine("Test Method Called");
    }
}
 
public class FailingRetryInterceptor : IInterceptor
{
    #region IInterceptor Members
 
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
 
        // we want to call proceed multiple times to simulate maybe something
        // like retrying a connection to a database or a remote service
        // after having informed the user
        
        // let's try to call the proced again, we expect a big time
        // failure here cause the standard implementation does
        // not allow the proceed method to be called multiple times
 
        invocation.Proceed();
    }
 
    #endregion
}
 
[TestFixture]
public class InterceptorsTest
{
    readonly ProxyGenerator _generator = new ProxyGenerator();
 
    [Test]
    public void TestFailingRetryInterceptor()
    {
        Assert.Throws(
            typeof (InvalidOperationException),
            () =>
                {
                    ITestClass sut =
                        _generator.CreateInterfaceProxyWithTarget<ITestClass>(new TestClass(),
                                                                              new FailingRetryInterceptor());
                    sut.TestMethod();
                });
 
    }
}

If you run this test it passes, which means we get the InvalidOperationException. This operation is perfectly legal in Spring while it’s not allowed in Castle, to investigate the issue I got the source code for DynamicProxy and looked at the implementation of the Proceed() method inside the AbstractInvocation class:

   1: public void Proceed()
   2: {
   3:     if (interceptors == null)
   4:         // not yet fully initialized? probably, an intercepted method is called while we are being deserialized
   5:     {
   6:         InvokeMethodOnTarget();
   7:         return;
   8:     }
   9:  
  10:     execIndex++;
  11:  
  12:     if (execIndex == interceptors.Length)
  13:     {
  14:         InvokeMethodOnTarget();
  15:     }
  16:     else if (execIndex > interceptors.Length)
  17:     {
  18:         string interceptorsCount;
  19:         if (interceptors.Length > 1)
  20:         {
  21:             interceptorsCount = " each one of " + interceptors.Length + " interceptors";
  22:         }
  23:         else
  24:         {
  25:             interceptorsCount = " interceptor";
  26:         }
  27:  
  28:         var message = "This is a DynamicProxy2 error: invocation.Proceed() has been called more times than expected." +
  29:                       "This usually signifies a bug in the calling code. Make sure that" + interceptorsCount +
  30:                       " selected for this method '" + Method + "'" +
  31:                       "calls invocation.Proceed() at most once.";
  32:         throw new InvalidOperationException(message);
  33:     }
  34:     else
  35:     {
  36:         interceptors[execIndex].Intercept(this);
  37:     }
  38: }

Looking at the implementation is pretty easy to understand why we cannot call the proceed more than one time per interceptor: if we do the we increment the execIndex outside the bound of the interceptors array.

In my application I have full control over which interceptors get injected on each proxy, so a simple hack would be to allow me to reset the ‘execIndex’ variable to -1; doing this way the next time you call invocation.Proceed() from an interceptor the whole chain start from the beginning allowing you to recover and retry the operation.

I don’t like to modify the library code, cause at every update I have to reapply the path again, the Hack here is to use some reflection and write an extension method for the IInvocation interface:

public static class IInvocationExtensions
{
    private static FieldInfo _resetInvocationInterceptorsCall;
 
    public static void Reset(this IInvocation invocation)
    {
        if (_resetInvocationInterceptorsCall == null)
        {
            Type invoc = FindBaseType(invocation.GetType(), typeof(AbstractInvocation));
            if (invoc == null)
                throw new InvalidOperationException("IInvocationExtensions - Cannot find AbstractInvocation as base class.");
            _resetInvocationInterceptorsCall = invoc.GetField("execIndex", BindingFlags.Instance |
                                                                                              BindingFlags.NonPublic);
        }
        // reinitialize the index of execution, so when we call Proceed() again
        // the whole chain of interceptors start again from the first element
        _resetInvocationInterceptorsCall.SetValue(invocation, -1);
    }
 
    private static Type FindBaseType(Type src, Type lookingFor)
    {
        while (!(src == typeof(object)) && (src != lookingFor))
        {
            src = src.BaseType;
        }
        if (src == lookingFor)
            return src;
        return null;
    }
}

We can now update our test and write another interceptor that call the newly created Reset() method to allow us to recover and start the execution again:

public class SuccessRetryInterceptor : IInterceptor
{
    #region IInterceptor Members
 
    private bool firstcall = true;
 
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
 
        if (firstcall)
            {
                firstcall = false;
                // we want to call proceed multiple times to simulate maybe something
                // like retrying a connection to a database or a remote service
                // after having informed the user
 
                // we ask to reset the current call and start it again from the beginning of the
                // interceptors chain
                invocation.Reset();
 
                // let's try to call the proced again, we expect a big failure here cause the standard implementation does
                // not allow the proceed method to be called multiple times
                invocation.Proceed();
 
                // note that in this test we used the firstcall variable to stop the recursive calls
                // of this interceptor.
            }
    }
 
    #endregion
}
 
[TestFixture]
public class InterceptorsTest
{
    readonly ProxyGenerator _generator = new ProxyGenerator();
 
    [Test]
    public void TestSuccessRetryInterceptor()
    {
        Assert.DoesNotThrow(() =>
        {
            ITestClass sut = _generator.CreateInterfaceProxyWithTarget<ITestClass>(new TestClass(), new SuccessRetryInterceptor());
            sut.TestMethod();
        });
 
    }
}

If you execute this test you can see that it passes and that the TestMethod() of the test class gets called two times.

CastleInterceptorsProceed

BEWARE! This is a dangerous technique and you have to be absolutely aware of what you are doing, cause you are executing the whole interceptors’ chain from the beginning..so if some of your interceptors modify the data or perform some advanced operations you have to know exactly what they do in order to not alter/invalidate the data of your application.



Castle windsor, Dynamicproxy, Multiple, Proceed

0 comments

DotNetMarche January Workshop - WPF, MVVM, UI

Print Content | More

If you live in Marche (Italy), get ready and don’t miss the next DotNetMarche workshop! Our local community group is working to setup the event. You can see the actual agenda and register for it at: http://dotnetmarche.org/eventi/Default.aspx?IDevento=33.

We will have an ‘all around’ event on WPF from a basic introduction to some advanced patterns for building application (MVVM and UI composition), plus - for those who last till the end - some nice features like 3D and Naturally User Interfaces.

This time will also be a ‘cross-community’ event, the speakers will be:

The event will take place on January 29; Time is running out, Go sign up now!



Dotnetmarche, Workshop, Wpf

4 comments

Optimizing WMI query performances - avoid the nasty ‘select *’

Print Content | More

These days I’m working to improve the startup time of an application my company develop, using some profiling tool you can easily isolate that functions that are eating up more time during the application startup.

Aside the database connections, I’ve saw that our custom protection and registration system was consuming more or less 3 seconds (it varies each run in the range from 2.5 to 3.5 seconds) to generate a unique hash code for the machine on which the program is installed.

The code internally uses some WMI queries to pickup system and hardware information, the first run was something like this:

WMI_BeforeQueryOptimization

One of the functions that is used to generate part of the hash requires 2.6 seconds to run...which is unacceptable to gather some hardware information.

All those functions basically use some WMI queries to get the data we need the implementation was something like:

   1: Friend Shared Function GetProcessorInfo() As String
   2:       Using query1 As New ManagementObjectSearcher("SELECT * FROM Win32_Processor")
   3:           Using queryCollection1 As ManagementObjectCollection = query1.Get()
   4:               Dim sb As New StringBuilder
   5:               For Each mo As ManagementObject In queryCollection1
   6:                   sb.Append(Convert.ToString(mo("processorid")))
   7:                   sb.Append(Convert.ToString(mo("family")))
   8:                   sb.Append(Convert.ToString(mo("architecture")))
   9:                   sb.Append(Convert.ToString(mo("revision"))) 
  10:                   sb.Append(Convert.ToString(mo("level")))
  11:                   sb.Append(Convert.ToString(mo("stepping")))
  12:                   sb.Append(Convert.ToString(mo("uniqueid")))
  13:                   sb.Append(Convert.ToString(mo("maxclockspeed")))
  14:                   sb.Append(Convert.ToString(mo("manufacturer")))
  15:                   Return sb.ToString
  16:               Next
  17:           End Using
  18:       End Using
  19:   End Function

Here you can see the source of all evil: in line 2 we ask the system to get EVERY information about the Processor and when we start enumeration the ManagementObjectCollection the WMI subsystem start gathering the data and populating the ManagementObject with all the information it can get regarding the Processors...even those we are not interested into. And this slows down everything in a terrible way.

So, the first thing you have to do when dealing with WMI is to reduce to the minimum the information that are returned from each query. I modified all the queries we made to look like:

Using query1 As New ManagementObjectSearcher("SELECT processorid,family,architecture,revision,level,stepping,uniqueid,maxclockspeed,manufacturer FROM Win32_Processor")
        

Running again the profiler on the function we obtain:

WMI_AfterQueryOptimization 

As you can see the execution time was cut in half! and the GetProcessorInfo() function alone passed from 1043ms to 12ms. The only function we wasn’t able to improve specifying the fields to return was the one that deals with the Ethernet interfaces to get their MAC address.



Performance, Select, Wmi

0 comments

Linq to NHibernate: how to query on a property without setter

Print Content | More

Recently I’ve started to play with Linq to NHibernate and I have to say it work pretty well for the scenarios I’m facing. It also helped me to ‘re-learn’ some things on NHibernate I usually forget.

Let’s consider the case in which we have a class that have some properties without setters, the usual way to map them is using the access=’field’ modifier and tell NHibernate to not use the property by the internal field of the implementation; you can then write your HQL queries on that field, here’s an example:

Public Class IDGEN
 
    Private mID As Int64 = -1
    Public Overridable ReadOnly Property ID() As Int64
        Get
            Return mID
        End Get
    End Property
 
    Private mYear As Int16
    Public Overridable ReadOnly Property Year() As Int16
        Get
            Return mYear
        End Get
    End Property
 
End Class

Here is the mapping I was used to have:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="Entities.IDGEN, CommunicationModule" table="tblPROTOCOL_ID_GENERATOR" lazy="false" >
    <id name="mID" column="ID" type="Int64" access="field" unsaved-value="-1">
      <generator class="native" />
    </id>
    <property name="mYear" column="Year" type="Int16" access="field" insert="false" update="false" />
  </class>
</hibernate-mapping>

You see we refer to the internal implementation members and our HQL queries will look like:

select max(id.mID) from IDGEN id where id.mYear = :year

As an experiment I’m porting this code to use Linq to NHibernate, the link query I would like to write is this:

long idgen = Session.Linq<Idgen>().Where(i => i.Year == year).Max(i => i.ID);

You can easily see the problem here: in code I cannot refer to the private mYear or mID fields, so when the query translator tries to parse my expression I get a wonderful exception.

How to make this work ? The answer is simple and built into NHibernate we can use Access and Naming strategies, look at 'Chapter 5.1.9 property' of the NHibernate reference documentation.

There you can see how to tell NHibernate to use the Getter of the properties to retrieve values from the class, and how the internal field is called so it can use that when assigning values to object.

In the end it’s just a matter of writing the right mappings, with something like this:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
  <class name="SID.Gestione.RefertiDocumenti.Neurologia.Entities.Idgen, SID.Gestione.RefertiDocumenti.Neurologia" table="IncrementalNumberGenerator" lazy="false" >
    <id name="ID" column="ID" type="Int64" access="nosetter.pascalcase-m" unsaved-value="-1">
      <generator class="native" />
    </id>
    <property name="Year" column="Year" access="nosetter.pascalcase-m" type="Int16" insert="false" update="false" />
  </class>
</hibernate-mapping>

we are now able to make the former Linq query work.

We now refer to the actual property of the class, we specify we don’t have setter and we use the pascalcase-m notation for the internal fields.

So fixing all your previous mapping that used access=’field’ attribute to a more correct notation you can easily perform Linq queries on all your classes.



Access, Field, Linq, Nhibernate, Nosetter, Setter

0 comments

Silverlight / WCF: fixing the Custom WCF Proxy Generator

Print Content | More

Some days ago I blogged about how you can build your own Custom WCF Proxy generator to extend the classes it generates and add some validation logic (or whatever you like).

Well playing with the MusicStore sample and making some changes to my domain classes there I’ve found a bug in the previous version of the proxy generator, let’s say your domain classes are like these:

[DataContract]
public abstract class DomainObject<TKey>
{
    [DataMember]
    public virtual TKey Id { get; set; }
}
 
[DataContract]
public partial class Album : DomainObject<int>
{
    public Album()
    {
        Tracks = new List<Track>();
    }
 
    //[DataMember]
    //public virtual int Id { get; set; }
 
    [DataMember]
    public virtual string Title { get; set; }
 
    [DataMember]
    public virtual string Author { get; set; }
...

Not only plain objects, like I had before, but you have inheritance from different classes, actually the previous proxy generator was going to extend only the classes that directly inherited from object, so in the proxy generated in the Silverlight project you could find the added code only in the ‘DomainObjectOfInt’ generated class (the base of the hierarchy).

To overcome this issue we have to modify the function FindAllProxyClasses() that identifies the proxy classes to extend, the new behavior will be like this:

protected virtual CodeTypeDeclarationCollection FindAllProxyClasses(CodeCompileUnit compileUnit)
{
   CodeTypeDeclarationCollection result = new CodeTypeDeclarationCollection();
 
   // search for all the proxy class (the one that inherits from ClientBase)
   foreach (CodeNamespace ns in compileUnit.Namespaces)
   {
      foreach (CodeTypeDeclaration type in ns.Types)
      {
         // does this type inherit from ClientBase?
         if (type.IsClass && type.IsPartial)
         {
            foreach (CodeTypeReference baseType in type.BaseTypes)
            {
               // if (baseType.BaseType == "System.Object")
                      // we need to take into account even model classes derived from other classes
               if ((!IsInterface(baseType)) &&
                           (baseType.BaseType != "System.ComponentModel.AsyncCompletedEventArgs") && 
                          (!baseType.BaseType.Contains("System.ServiceModel.ClientBase")))
               {
                  // we have found the proxy!
                  result.Add(type);
                  break;
               }
            }
         }
      }
   }
   return result;
}

This way we exclude from our list all the classes that are: interfaces, derive from AsyncCompletedEventArgs (arguments of async events), derive from ClientBase (the class that actually handles the calls to the web service).

If you ask yourself why I had to write an IsInterface() function to check if a CodeTypeReference is an interface, the answer is: the framework already provides this information...but in an internal member of the class :(.

Here is the full code of the fixed Custom WCF Proxy Generator:

[GuidAttribute("64205D39-7D51-4c6d-8C0F-237E6FE2BD70")]
public class StructuraWcfProxyGenerator : WCFProxyGenerator
{
   protected override void CallCodeGeneratorExtensions(CodeCompileUnit compileUnit)
   {
      //todo: we can implement the mapping of validation attributes using an external xml file placed inside the current project
      //      this way we can use the annotation objects even with wcf services
      //EnvDTE.DTE vs = (EnvDTE.DTE)this.ServiceProvider.GetService(typeof(EnvDTE.DTE));
      //EnvDTE.Project prj = vs.SelectedItems.Item(1).ProjectItem.ContainingProject;
      //System.Diagnostics.Debug.WriteLine(prj.FullName);
 
      base.CallCodeGeneratorExtensions(compileUnit);
 
      // find all classes that inherit from ClientBase (all proxies)
      var proxies = FindAllProxyClasses(compileUnit);
      // add impersonation code to their constructors
      foreach (CodeTypeDeclaration proxy in proxies)
      {
         AddPartialMethods(proxy);
         AddValidationToProperties(proxy);
      }
   }
 
   protected virtual CodeTypeDeclarationCollection FindAllProxyClasses(CodeCompileUnit compileUnit)
   {
      CodeTypeDeclarationCollection result = new CodeTypeDeclarationCollection();
 
      // search for all the proxy class (the one that inherits from ClientBase)
      foreach (CodeNamespace ns in compileUnit.Namespaces)
      {
         foreach (CodeTypeDeclaration type in ns.Types)
         {
            // does this type inherit from ClientBase?
            if (type.IsClass && type.IsPartial)
            {
               foreach (CodeTypeReference baseType in type.BaseTypes)
               {
                  // if (baseType.BaseType == "System.Object")
                         // we need to take into account even model classes derived from other classes
                  if ((!IsInterface(baseType)) &&
                              (baseType.BaseType != "System.ComponentModel.AsyncCompletedEventArgs") && 
                             (!baseType.BaseType.Contains("System.ServiceModel.ClientBase")))
                  {
                     // we have found the proxy!
                     result.Add(type);
                     break;
                  }
               }
            }
         }
      }
      return result;
   }
 
    private static bool IsInterface(CodeTypeReference reference)
    {
        // try to create the type and see if it's an interface
        try
        {
            return Type.GetType(reference.BaseType).IsInterface;
        }
        catch (Exception)
        {
            return false;
        }
    }
 
    protected virtual void AddPartialMethods(CodeTypeDeclaration type)
   {
      IVsSingleFileGenerator ivs = (IVsSingleFileGenerator)this;
      // ugly, but it's the only way I found to identify the language used
      string ext;
      ivs.DefaultExtension(out ext);
      CodeSnippetTypeMember literalMember;
      if (ext.Contains("cs"))
      {
         // csharp
         literalMember = new CodeSnippetTypeMember(
            "partial void ValidateProperty(string propertyName, object value);");
      }
      else
      {
         // vb 
         literalMember = new CodeSnippetTypeMember(
            "Partial Sub ValidateProperty(byval propertyName as String, byval value as Object)");
      }
      type.Members.Add(literalMember);
 
      // the codedom do not support partial methods yet
      //CodeMemberMethod MyMethod = new CodeMemberMethod();
      //MyMethod.Name = "ValidateProperty";
      //MyMethod.ReturnType = new CodeTypeReference("partial void");
      //MyMethod.Attributes = MemberAttributes.ScopeMask;
      //MyMethod.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "propertyName"));
      //MyMethod.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "value"));
      //type.Members.Add(MyMethod);
   }
 
   protected virtual void AddValidationToProperties(CodeTypeDeclaration type)
   {
      foreach (CodeTypeMember member in type.Members)
      {
         CodeMemberProperty ctor = member as CodeMemberProperty;
         if (ctor != null)
         {
            // create a code statement like:
            // this.ValidateProperty("Title", value)
            CodeMethodInvokeExpression method = new CodeMethodInvokeExpression(
                new CodeThisReferenceExpression(),
                "ValidateProperty",
               new CodeExpression[] { 
                  new CodePrimitiveExpression(ctor.Name), 
                  new CodePropertySetValueReferenceExpression() 
               });
 
            // we got a constructor
            ctor.SetStatements.Insert(0, new CodeExpressionStatement(method));
         }
      }
   }
}

You can take this code and replace the old version in my previous post, regenerate your proxies and voila...you have the validation code spammed on all your new proxy class hierarchy.

With some more customization you can easily buildup a code generator that closely resembles the one provided by the new RIA services without any modification to you current up and running WCF services.



Custom, Generator, Proxy, Silverlight, Wcf

3 comments

Last few days to sign up for the 12th DotNetMarche / Community Tour 2009 workshop

Print Content | More
For all my Italian readers (especially all that reside in Marche) these are the last few days to sign up and participate at our last workshop of the year.

To sign-up visit the DotNetMarche website: www.dotnetmarche.org.

The technical sessions will be devoted to the technologies you can use TODAY to write a web application, focusing especially on the UI.

We decided to create our own MusicStore sample and build it ground-up with 3 different technologies: Asp.Net classic / Asp.Net MVC + jQuery / Silverlight 3.

The Silverlight version of MusicStore will also use the following technologies:
  • The server side components will use a SQL Express + NHiberante for the data access layer
  • WCF service / HTTP handler : this is the ‘data provider’ of the application to deal with the database and upload files
  • Silverlight 3 for the UI.
We will focus on some feature related to UI building (and patterns if we have time), I’ll show you how to use:
  • Data binding - for displaying and acquiring data
  • Validation - how you can do preventive validation on the UI
  • Control Temples - to skin and change the appearance of control without touching the code
Here are some screenshots of the working application: MusicStore1 MusicStore2 Why Silverlight 3 and not Silverlight 4 ? well as I said before I wanted to show you how you can resolve some problems related to building business application with the technologies you have today. If you have to write something that MUST work and be deployed to a production environment in the next 3-4 months, you cannot rely on software that is still in beta stage, you cannot ask to your customers to install an alpha or beta version or a core component like the SL runtime.

Dotnetmarche, Silverlight, Workshop

0 comments

Silverlight: how to fix the Silverlight Toolkit templates to add Validation States

Print Content | More

Using the control templates provided by the Silverlight toolkit I just noticed that those style do not support the validation states for displaying validation errors.

Since you have access to the templates adding them is a quite easy - but boring - job. First of we need to open the template of the standard controls and extract the pieces related to data validation display, then we can modify the provided templates inserting these pieces of code back. We can do this so easily because of the nice way the controls skins work in Silverlight and WPF (there are plenty of resources over the net on this subject so I will not dig into that) and thanks to the Visual State Manager that handles the display state changes without any logic to be added to the control, this link from Jesse Liberty gives a clear picture of the thing: Quick overview of Silverlight validation.

In short to modify the - let’s say - the Textbox template you just have to:

  • Look for the VisualStateManage.VisualStateGroups section of the template and add a VisualStateGroup with the following states in it: Valid, InvalidUnfocused, InvalidFocused. All the data validation framewrok relies on the presence of these 3 states do change the appearance of the control:
    <VisualStateGroup x:Name="ValidationStates">
       <VisualState x:Name="Valid"/>
       <VisualState x:Name="InvalidUnfocused">
          <Storyboard>
             <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                <DiscreteObjectKeyFrame KeyTime="0">
                   <DiscreteObjectKeyFrame.Value>
                      <Visibility>Visible</Visibility>
                   </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
             </ObjectAnimationUsingKeyFrames>
          </Storyboard>
       </VisualState>
       <VisualState x:Name="InvalidFocused">
          <Storyboard>
             <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                <DiscreteObjectKeyFrame KeyTime="0">
                   <DiscreteObjectKeyFrame.Value>
                      <Visibility>Visible</Visibility>
                   </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
             </ObjectAnimationUsingKeyFrames>
             <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsOpen">
                <DiscreteObjectKeyFrame KeyTime="0">
                   <DiscreteObjectKeyFrame.Value>
                      <System:Boolean>True</System:Boolean>
                   </DiscreteObjectKeyFrame.Value>
                </DiscreteObjectKeyFrame>
             </ObjectAnimationUsingKeyFrames>
          </Storyboard>
       </VisualState>
    </VisualStateGroup>
  • These states operate on some framework elements (validationErrorElement and validationErrorToolTip) so we have to add those too, so at the end of the control template - just before the closing </Grid> tag - add the following piece of code:
    <Border x:Name="ValidationErrorElement" Visibility="Collapsed" BorderBrush="#FFDB000C" BorderThickness="1" CornerRadius="1">
       <ToolTipService.ToolTip>
          <ToolTip x:Name="validationTooltip" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" Template="{StaticResource ValidationToolTipTemplate}" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}">
             <ToolTip.Triggers>
                <EventTrigger RoutedEvent="Canvas.Loaded">
                   <BeginStoryboard>
                      <Storyboard>
                         <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsHitTestVisible">
                            <DiscreteObjectKeyFrame KeyTime="0">
                               <DiscreteObjectKeyFrame.Value>
                                  <System:Boolean>true</System:Boolean>
                               </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                         </ObjectAnimationUsingKeyFrames>
                      </Storyboard>
                   </BeginStoryboard>
                </EventTrigger>
             </ToolTip.Triggers>
          </ToolTip>
       </ToolTipService.ToolTip>
       <Grid Height="12" HorizontalAlignment="Right" Margin="1,-4,-4,0" VerticalAlignment="Top" Width="12" Background="Transparent">
          <Path Fill="#FFDC000C" Margin="1,3,0,0" Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z"/>
          <Path Fill="#ffffff" Margin="1,3,0,0" Data="M 0,0 L2,0 L 8,6 L8,8"/>
       </Grid>
    </Border>

You must add this after all the other framework element to be sure that when enabled those controls are displayed over any other element that form the template.

This way you have standard way to display the validation error messages in your templated control. Actually you can use these pieces of codes in you own controls to give them the same look and feel. Also rewriting these pieces of code and applying them to the controls you can totally change the way validation error messages are shown.



Silverlight, Style, Template, Toolkit, Validation

1 comments