Hi, today I am going to explain how to set up two SSL sites for development. If the solution you are developing requires to be distributed to more than one website and they require https, the default configuration of IIS might not be enough. You might still want to setup your development machine as close to the production environment as possible.

Remarks: SSL runs by default in the 443 port, but differently to plain http, the hostname you are hitting the request against is not known until the message is decrypted. The approach we are going to go through uses different IP addresses for different sites, so IIS can differentiate the requests and send them to the appropriate web application.

First, we will need to add as many IP addresses as https sites we will need. To don’t mess with the network you are connected to and to do not depend upon it, we will add a fake network adapter that is provided with Windows itself: the Microsoft Loopback Network adapter.

To get the two https sites in your machine, we will go through the following steps:

  • SSL Certificates to use for your sites (see my other post on how to create them)
  • Adding a fake network adapter
  • Adding IP addresses
  • Install the SSL Certificates
  • Set the right permissions for IIS on the certificates’ private keys
  • Set up IIS

Sample configuration

During the instructions described below I will use the following sample configuration:

Installing the loopback adapter

Go to the Device Manager, right click in the root device and then click Add legacy hardware.

Click Next, then select Install the hardware that I manually select from a list, then click Next.

Select Network adapters and click Next.

In the list from the left select Microsoft, then in the list from the right select Microsoft Loopback Adapter and click Next twice.

Setting up the IP addresses

1. Go to Network connections, find the adapter that uses the loopback adapter.

 

2. Right click on it, then click Properties. Select only Internet Protocol version 4 (TCP /IPv4). Click Internet Protocol version 4 (TCP /IPv4) and then click Properties.

3. Click Use the following IP addresses, then click Advanced.

4. In the IP addresses frame click Add… and type an IP address that you’re sure it doesn’t overlap with your network. For this sample use 20.0.0.1 and 255.255.255.0 as subnet mask.

5. Repeat step 4 with another IP address for another https site that you need to host as many times as needed. For this sample use 20.0.0.2 and 255.255.255.0 as subnet mask.

Adding DNS entries

1. Open in a text editor (like Notepad) the file %SYSTEM32%\Drivers\etc\hosts.

2. Append the following entries for this sample:

20.0.0.1 site1
20.0.0.2 site2

3. Save the file.

Installing the certificates

1. Open an instance of the Management Console. This can be done by running mmc.

2. Click File, then click Add/Remove Snap-in….

3. Select Certificates in the list from the left. Then click Add.

4. Click Computer account, then click Next.

5. Click Local computer, then click Finish.

6. Click Ok to close the Add or Remove Snap-in window.

7. Double-click Certificates (Local Computer) in the list from the left.

8. Double-click Personal.

9. Click Certificates in the list from the left.

10. Click the Actions menu, then click All tasks, then click Import….

11. Click Next. Then input the path to the .pfx certificate file. Click Next again.

Remarks: If you don’t have one you can generate it following the steps described here.

12. Type the password of the .pfx file. Click Mark key as exportable. Then click Next twice, then click Finish.

13. Select the recently installed certificate from the list on the center.

14. Click the Actions menu. Click All tasks then click Manage Private Keys….

15. Click Add…

16. Make sure that the location selected is your local computer (this might be different by default if your computer pertains to a Domain).

17. Type NETWORK SERVICE (or the user with which IIS runs). Then click Ok.

18. Click Ok to close the permissions window.

19. Repeat the steps 10 to 18 for installing the second certificate.

Configuring IIS

  1. Open the Internet Information Services (IIS) Manager. This can be done by running inetmgr.

1. Right click the Sites node and then click Add Web Site…

2. Set the following data for this sample:

Binding type: https

IP address: 20.0.0.1

SSL certificate: site1

Then click Ok.

Remarks: The physical path I am pointing to contains an html with the name of the site for testing purposes.

4. Repeat the step 3 with the data for the second site. For this sample:

Binding type: https

IP address: 20.0.0.2

SSL certificate: site2

Verifying the sites

Now we are ready to go. Open a web browser and point to https://site1, you should be able to see the first site using the site1 certificate. Then browse to https://site2 and you should see the second site using the site2 certificate.


 

A sample for the following post can be downloaded from here 

Go and use it! it’s simple!

routes.MapRoute<HomeController>(
                "Index",
                "",
                c => c.Index());

or maybe you have parameters on your action, and default values…

routes.MapRoute<HomeController>(
                "Echo",
                "Echo/{echo}",
                c => c.Echo("I am the default value of the echo parameter!"));

You want to use it now? It’s ok, here it is:

You can copy and paste the following classes:

ControllerAction.cs
namespace System.Web.Mvc
{
    using System;
    using System.Linq.Expressions;
    using System.Web.Mvc;
    using System.Web.Routing;

    ///<summary>
    /// Typed controller action that provides a <c ref="RouteValueDictionary">RouteValueDictionary</c> based on the parameters passed.
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    public class ControllerAction<TController>
        where TController : IController
    {
        /// <summary>
        /// Initializes a new instance of the ControllerAction class.
        /// </summary>
        /// <param name="action">The controller action.</param>
        public ControllerAction(Expression<Func<TController, ActionResult>> action)
        {
            this.DefaultValues = new RouteValueDictionary();
            this.DefaultValues.Add("controller", typeof(TController).Name.Remove(typeof(TController).Name.LastIndexOf("Controller")));

            var decorations = (action.Body as MethodCallExpression).Method.GetCustomAttributes(typeof(ActionNameAttribute), true);

            var methodCall = action.Body as MethodCallExpression;

            if (decorations != null && decorations.Length == 1)
            {
                this.DefaultValues.Add("action", (decorations[0] as ActionNameAttribute).Name);
            }
            else
            {
                this.DefaultValues.Add(”action”, methodCall.Method.Name);
            }

            var paremeters = methodCall.Method.GetParameters();

            for (int parameterIndex = 0; parameterIndex < paremeters.Length; parameterIndex++)
            {
                object value = null;
                var argumentExpression = methodCall.Arguments[parameterIndex];

                if (argumentExpression is ConstantExpression)
                {
                    value = (argumentExpression as ConstantExpression).Value;

                    this.DefaultValues.Add(
                        paremeters[parameterIndex].Name,
                        value);
                }
            }
        }

        /// <summary>
        /// Gets the default route values.
        /// </summary>
        /// <value>The default route values.</value>
        public RouteValueDictionary DefaultValues
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the controller name from the default values.
        /// </summary>
        /// <value>The controller name.</value>
        public string Controller
        {
            get
            {
                return this.DefaultValues["controller"] as string;
            }
        }

        /// <summary>
        /// Gets the controller action from the default values.
        /// </summary>
        /// <value>The controller action.</value>
        public string Action
        {
            get
            {
                return this.DefaultValues["action"] as string;
            }
        }
    }
}
RouteCollectionExtensions.cs
namespace System.Web.Mvc
{
    using System;
    using System.Linq.Expressions;
    using System.Web.Mvc;
    using System.Web.Routing;

    /// <summary>
    /// Route collection extension methods class.
    /// </summary>
    public static class RouteCollectionExtensions
    {
        /// <summary>
        /// Adds a typed route into a RouteCollection.
        /// </summary>
        /// <typeparam name="TController">The controller type.</typeparam>
        /// <param name="routes">The route collection to fill in.</param>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="url">The URL for the route.</param>
        /// <param name="action">The controller action.</param>
        public static void MapRoute<TController>(
            this RouteCollection routes,
            string routeName,
            string url,
            Expression<Func<TController, ActionResult>> action)
            where TController : IController
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

            var typedControllerAction = new ControllerAction<TController>(action);

            routes.Add(routeName, new Route(url, typedControllerAction.DefaultValues, new MvcRouteHandler()));
        }
    }
}

Thanks,

             Diego

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!