Singluarity RDK 2.0 has been released!!! You can find it as usual @ http://www.codeplex.com/singularity

I want to share with you some pieces of code that you can use to achieve a more flexible design on your applications. What you can achieve with this is that your WCF service instances are built taking advantage of Dependency Injection by using the Unity Application Block (from Microsoft P&P).

Setting up the sample

I will be using a sample project (called DoppleBock) which you can run in your machine and see how it works. Note that to be able to experiment with the whole solution you will need:

To run the solution tests:

  •  
    • Microsoft Visual Studio 2008 Professional (or higher version)
    • Moq (assemblies provided in the solution)

Do you have the products? Download the DoppleBock sample from my SkyDrive and let’s start!

Add Unity to your project

Once you installed Unity, its assemblies will be registered in the GAC (Global Assembly Cache). The references that your host projects will need to contain will be the following:

Unity reference assemblies

Unity has containers that holds the type-mapping and parameter resolution configuration and the instances of the resolved types that it will take care of during the objects lifetime. There are two ways of configure these containers, but I will explain about the configuration file configuration via. This method for configuring the containers is more flexible when you work with Web applications, since it lets you to reconfigure the dependency resolution without recompiling the published website.

First, you will need to add the Unity configuration section, so it can be recognized by the application. Add this mapping to the host configuration file. This is taken from our sample, you can find this in the DoppleBock.Services.Host/web.config file.

Unity Application Block configuration section type mapping

Talking with interfaces

One of the possible Dependency Injection resolving methods that Unity allows you to use is the constructor injection. The sample solution (DoppleBock) uses interface implementation resolution in two moments:

  • When the Website logic needs to resolve a service client
  • When the services needs to resolve a data access layer repository

 

By default, WCF doesn’t provide a way to use service types without parameter-less constructors, but our sample provides you a way to accomplish this that I will explain later in this post.

You can find a service implementation class that contains the following constructor:

Service constructor

 

The service host configuration file (DoppleBock.Services.Host/web.config) contains the type mapping definition that tells Unity how to resolve this type in run-time.

Unity type mapping

The ‘external’ lifetime manager tells Unity to maintain weak references with the object instances, so if the instance has been collected by the garbage collector a new one will be resolved.

Also, I am telling to Unity that DoppleBock.Data.SqlProjectsRepository has to be constructed with a System.String connectionString parameter that will contain certain value.

Let WCF inject

If you take a look to the system.serviceModel configuration section of our services host configuration file (DoppleBock.Services.Host/web.config), it contains a behavior extension element. This element register a <unity /> tag that you can add to a service behavior.

system.serviceModel configuration section

This <unity /> tag can also recieve additional parameters:

  • unityConfigurationSectionPath: If you placed your Unity configuration section in a different path than “unity”, you can set your path through this attribute
  • containerName: Unity name-less constructor is the default, but if you want to use a named one for the services with this behavior you can set its name here.

Its implementation basically replaces the service IInstanceFactory by our own instance factory that resolves the services instances through Unity. If you want to take a look at its code you can find its in the Unity.ServiceModel project.

Unity.ServiceModel project 

Next time: Unity & friends: The MVC application side

I plan to write another post about how I am using the injection in MVC. If you browse the sample code, the controllers are also created through injection, so I expect to be able to clarify how this is being done in the next post, which means… add me to your feeds, and let me know your feedback! Thanks!

To sign, encrypt, decrypt or verify your Security Tokens, you will need certificates. Here I will explain how to create a certificate that can be used for this purpose. The command prompt shown below has been started from the Visual Studio Command Prompt, as it lets you access to these commands from any working directory. If you don’t have Visual Studio you can get this tools from the Windows SDK also.

Lets create a self-signed certificate, issued by localhost for itself.

image

Switch Meaning
-r Create a self-signed certificate.
-sky exchange The type of the subject key is intended to be used for exchange.
-a sha1 The algorithm that will be used to sign messages with this certificate will be SHA1.
-n CN=localhost Set the certificate subject name. At least one CN= must be set (various can be set). This should be the same as the network name of the host that will use it.

CN means Canonical Name.

-sv localhost.pvk Where we store the private key file. If this file does not exists, a new one will be created.
localhost.cer The name of the output file (our certificate).

A dialog will appear where it will ask us for a password to secure the private key file. If we don’t want to enter a password, we can simply click ‘None’.

image

Now, we will convert our standard X.509 certificate into a SPC (Software Publisher Certificate). With real certificates, the SPC must be get from a valid CA (Certification Authority) such as Verisign. In order to do this, we will call the cert2spc tool.

This SPC file will be used in our next and last step to generate the PFX (Personal Information Exchange) file. This PFX file will contain our certificate and its private key, ready to be imported on our target machine. This will be done by the pvk2pfx command as shown below.

image

Now we are ready to import the certificate (CER file) or the certificate plus its private key (PFX file).

Notes

  • In case that you want to generate a certificate for another host, simply replace ‘localhost’ in every place it is mentioned in this steps.
  • There are several certificate repositories. If we are going to use this certificate to decrypt or sign, it should be stored in the ‘Personal’ repository (its alias for commands is ‘My’).
  • As this is a self-signed certificate (signed by itself), to make a computer trust in its certification path, it should also be imported in the ‘Trusted root Certification Authorities’ repository (the CER file, as we only need the public key to validate signing).
  • Remember that to use a internet-exposed STS you will need to get (buy) a valid certificate from a root authority. But for development or internal network or your domain you can create your own certificates.

I found a workaround to improve the Ajax Control Toolkit Autocomplete Extender look.

clip_image002

By default, Autocomplete shows a list of texts, but we were looking for something a little more fancy, showing also a description (or any custom HTML).

Some things had to be done:

· Customize server response

· Re-render the dropdown list

· Hook the item selection event

Customize serialization

Autocomplete behavior has some kind of support for key/value pairs, and not only to standard string arrays, but not in the way I expected it to do.

I expected that a System.Web.UI.Pair[] had to be return, but instead, it had to be an array of Json objects similar to the System.Web.UI.Pair.

I took advantage of the DataContractJsonSerializer to make it work with Autocomplete extender.

clip_image003

Sending some data

The .First property is taken as the text to be displayed in the list and the .Second field is taken as the Value to set into the textbox (Autocomplete target).

clip_image004

Re-rendering the dropdown list

clip_image005

clip_image006

As Autocomplete behavior encodes the text to display to HTML, so it can be displayed correctly, here is a little workaround to that feature, which is an obstacle for our approach:

clip_image007

Set the OnClientShowing property of the extender to the following JS function:

function acItemShowing (sender, args)
{
var c = sender.get_completionList ();

if (c.childNodes.length > 0)
{
for(var i = 0; i <c.childNodes.length; i++)
{
c.childNodes[i].innerHTML =  c.childNodes[i].firstChild.nodeValue;
}
}
}

This function will make the display values to be shown as HTML.

Retrieving the selected value

As the value of the selected item was in the root element, but it is not present in the element which fired the selection event (one of the tags of the elements that we re-rendered), we need to retrieve that value.

By hooking a custom function on the OnItemSelected we can retrieve that value form the parent element.

clip_image008

function acItemSelected (sender, args)
{
var item = args.get_item ();
var cl = sender.get_completionList ();

while (item != null && item.parentNode != cl)
{
item = item.parentNode;
}

args = new AjaxControlToolkit.AutoCompleteItemEventArgs(item, item._value, item._value);
sender.get_element().value = args.get_value ();
}

Known issues

After this modifications, something has been missed for Internet Explorer, items won’t highlight correctly when hovering the items. Even thus, when clicking or selecting the element by keyboard will work ok. I hope to be able to fix this later.

Thanks,

Diego

I want to share with you an HtmlHelper extension method that I created to render a tree. It takes advantage of lamda expressions, so you can feel more comfortable when using it. It is not binded to any interface or class for the node type.

How using it looks like

For this example, I use as node class a type NodeViewData that holds some properties such as a string Caption, a Guid Id, and a List<NodeViewData>Children.

We will construct a simple tree, from a list of NodeViewData. This tree will be indented according to the depth, and with some simple Javascript we will show a message with its Id when clicking it.

<%=    Html.HierarchicalRender<NodeViewData> (
// We pass an instance of IEnumerable<NodeViewData>
// so it can iterate over the root nodes
this.ViewData.Model.RootNodes,
// We will use a <br /> as separator between nodes
“<br />”,
// I recieve an HierarchyInformation<NodeViewData> instance
// it contains the Node, the parents of the node,
// and the node order in its trunk
// You specify a delegate (lamda) that returns
// the HTML for the node being processed
h =>
string.Format(
    // This is the basic node format I will use for the sample
    “<a href=\”#\” style=\”margin-left: {0}px\” onclick=\”alert (’{2}’); return false\”>{1}</a>”,
    // I will multiply the node parents count (depth) to indent the node
    h.ReversedParents.Length * 20,
    // We render the HTML for the caption
    Html.Encode (h.Node.Caption),
    // Let’s show the node Id when clicking
    h.Node.Id),
// For a given node (n) let’s pass an expression
// to return a IEnumerable of the same type
// this expression will be used to let the
// HierarchicalRendered iterate over its children
n => n.Children) %>

Get it!

You can download a sample solution from http://cid-9e5d4c3be8afbb19.skydrive.live.com/self.aspx/Posts/SampleMvc.zip

In the HierarchicalRender.cs you can find the HtmlHelper extension method and classes.

Remember to have the namespace of the extension method in your markup to use it!

Glue code

Below I put the HierarchicalRender class (extension method) and the HierarchyInformation class (used for node the nodeFormat delegate).

public static string HierarchicalRender<T>(
    this HtmlHelper helper,
    IEnumerable<T> source,
    string nodeSeparator,
    Expression<Func<HierarchyInformation<T>, string>> nodeFormat,
    Expression<Func<T, IEnumerable<T>>> childEnumerator)
{
    var builder = new StringBuilder();

    HierarchicalRender<T>(
        helper,
        source,
        nodeSeparator,
        nodeFormat.Compile(),
        childEnumerator.Compile(),
        new T[0],
        builder);

    return builder.ToString();
}

private static void HierarchicalRender<T>(
    this HtmlHelper helper,
    IEnumerable<T> source,
    string nodeSeparator,
    Func<HierarchyInformation<T>, string> nodeFormat,
    Func<T, IEnumerable<T>> childEnumerator,
    T[] reversedParents,
    StringBuilder builder)
{
    int order = 0;
    foreach (T node in source)
    {
        if (order > 0)
            builder.Append(nodeSeparator);

        var info = new HierarchyInformation<T>
    {
        Node = node,
        Order = order,
        ReversedParents = reversedParents
    };

        builder.Append(nodeFormat.Invoke(info));

        var children = childEnumerator.Invoke(node).ToList();
        if (children.Count > 0)
        {
            builder.Append(nodeSeparator);

            var reversedParentsWithSelf = reversedParents.ToList();
            reversedParentsWithSelf.Insert(0, node);

            HierarchicalRender<T>(
                helper,
                children,
                nodeSeparator,
                nodeFormat,
                childEnumerator,
                reversedParentsWithSelf.ToArray(),
                builder);
        }

        order++;
    }
}

public class HierarchyInformation<T>
{
    public T Node
    {
        get;
        set;
    }

    public T[] ReversedParents
    {
        get;
        set;
    }

    public int Order
    {
        get;
        set;
    }
}

Thanks, Diego

I found a very useful post about WCF contracts and object references. For those who need to serialize an object graph with cyclic references check out this: http://blogs.msdn.com/sowmy/archive/2006/03/26/561188.aspx

Incorporación al equipo

September 1st, 2007

Soy Diego Pérez y el lunes me incorporo al equipo de Southworks. Estoy agradecido por esta oportunidad única y ansioso por estar desarrollando junto al equipo. Espero que el intercambio de experiencias sea rápidamente fructífero y poder aprender mucho con Southworks.

Reitero mi agradecimiento, y seguiré dando noticias…

¡Pronto zarpa mi nave para nuevas tierras, nos vemos!