Archive for June 2010

Windows Azure Tools for Microsoft Visual Studio 1.2 (June 2010)

I am very happy Microsoft updated the Azure Tools to have full integration with Visual Studio. It is extremely easy to set up, just a few clicks to create a certificate and upload it. The process is all guided and it took me around 30 seconds. After the certificate has been uploaded you can deploy from Visual Studio with a neat status bar.

There are some other neat features like IntelliTrace and others that are now available.

Here is a link to the latest release: Windows Azure Tools for Microsoft Visual Studio 1.2 (June 2010)

Complete control over XML in WCF

Sometimes it is needed to have complete control over how WCF manipulates the data being returned. By default, WCF serializes objects and returns them as XML. Sadly, there is not much control on how to create templates over how objects will be serialized (flat structure, hierarchical, etc). In many cases this does not matter. A few weeks ago I stumbled for the first time when I need 100% control over how the XML was formated and being sent.

To send custom formated XML use the message envelope and not the string datatype. If the envelope is not used, it will add extra meta content.

Here is how it can be done:

public Message GetMessage(string xml)
{
    XmlDocument x = new XmlDocument();

    //This is very important as it will VALIDATE the XML. Saved my butt a few times.
    x.LoadXml(xml);

    XmlElementBodyWriter writer = new XmlElementBodyWriter(x.DocumentElement);

    Message msg = Message.CreateMessage(MessageVersion.None,
                OperationContext.Current.OutgoingMessageHeaders.Action, writer);

    return msg;
}

public class XmlElementBodyWriter : BodyWriter
{
    XmlElement xmlElement;

    public XmlElementBodyWriter(XmlElement xmlElement)
                : base(true)
    {
         this.xmlElement = xmlElement;
    }

    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
         xmlElement.WriteTo(writer);
    }
 }

Also a little warning, the string passed in should be formated and already encoded in the format you want. This can make a huge difference specially when internationalization is involved.

Value Objects in F#

Value Objects are objects that can be shared across different parts of a program. This can have great benefits in performance. Because  the objects are shared it is very important for value objects to be immutable. If value objects are not immutable then any part of the program can change the values and all the other parts can do calculation with erroneous data.

One of my goals was to make immutable objects in F# to take advantage of parallelization and automatic compiler optimizations:


type City(Name:string, X: float, Y:float) =

member t.Name = Name

member t.X = X

member t.Y = Y

type NeighborCities(city1:string, city2:string) =

member x.fromCity = city1

member x.toCity = city2

Objects created in this manner in F# are immutable. Even when they are accessed in other projects outside their definition, their members are read-only. This was specially helpful on the distributed traveling salesman problem I built last year.

Testing F#

F# is very cool. By combining the regular iterative features of the other .NET languages with an Ocaml syntax variant, F# is extremely flexible and powerful.

Here is a simple loop:

 for i in 0..loopSize do

Here is another example for reading in contents from a file, making an object city and returning a list of cities:


let ReadFile (s:string) = match s with
    | null -> raise (ApplicationException "Please provide a non-empty string for the filename!!")
    | s ->
    let cityList = new ResizeArray<CityDef.City>() in
    let rec ReadFile (r:StreamReader) =
        if not r.EndOfStream then
            cityList.Add(ParseCityString(r.ReadLine()))
            ReadFile r
        r.Close()
    let r = new StreamReader(s) in
    ReadFile r
    cityList

F# has powerful features because it has a lot of high order functions on top of the usual map, filter and reduce. The extra high order functions (such as iter, fold, scan, skip, skipWhile, sum, take, takeWhile, truncate, unfold, windowed, zip, zip3, etc.) make it easy to compound complex tasks.

The next example is a little snippet that returns a dictionary distances between cities for a small distributed traveling salesman problem I did last year to test F# on a software engineering class.


let squared x = x*x

let CompareNeighbors = {
    new System.Collections.Generic.IEqualityComparer<CityDef.NeighborCities> with
    member x.Equals(a,b) =  (String.Compare(a.fromCity, b.fromCity) = 0 ) && ( String.Compare(a.toCity, b.toCity) = 0 )
    member x.GetHashCode(a) = a.toCity.GetHashCode() }

let Distance (distanceDic : Dictionary<CityDef.NeighborCities, double>, i: CityDef.City, j: CityDef.City ) =
    let x2 = squared (i.X - j.X)
    let y2 = squared ( i.Y - j.Y)
    let total = sqrt( x2  +  y2)
    let n = new CityDef.NeighborCities(city1 = i.Name, city2 = j.Name)
    distanceDic.Add(n, total)

type DistanceDictionary() =
    interface Infrastructure.IDistanceCalculator with
        member this.DistanceDictionary (genericListOfCities:ResizeArray<CityDef.City>)  =
            let dic = new Dictionary<CityDef.NeighborCities, double>(CompareNeighbors)
            Seq.iter(fun z -> Seq.iter(fun x->Distance(dic, z, x)) genericListOfCities) genericListOfCities
            dic

Also it is nice being able to use interfaces with F# in the simple format of “interface Infrastructure.IDistanceCalculator with”.

As a little tip, for applying something to a list that does not require a new collection, it is important to avoid using the higher order function map. Map should only be used if a new list with a different set of values is expected because it creates a new list. In this case, map was not necessary and iter was the choice.

VS2010 Productivity Power Tools

I am currently testing the VS2010 Productivity Power Tools.  They are amazing!

Some of the best features (in my opinion) are related to code formating.

For example – spacing:

By pressing ctrl+alt+] on the following code:

this.PartitionKey = userAccount;
this.RowKey = username;
this.token = token;
this.secret = secret;

it became


this.PartitionKey = userAccount;
this.RowKey       = username;
this.token        = token;
this.secret       = secret;

Click here to download them.

Dynamic Azure Web Services URLs

I am currently building a lot of web services for Azure. Since URLs change a lot in development and deployment environments I needed to be able to have those services URLs updated dynamically. The easiest way I found is using handlers and:


HttpContext.Current.Request.Headers["Host"];

This way none of the URLs get hard-coded and deployment is extremely easy. This also brings a lot of neat options for Intercloud communication, but that is for another post.

Synergy and Visual Studio

Currently I am running a windows 7 machine, ubuntu test server and a perosnal macbook pro at my desk . All of them are being controlled by one pair of mice and keyboard which is why  I am a big fan of synergy. The only issue that I was experiencing is that most times visual studio was trapping my mouse and not letting me move it to the next screen.  The trick is to start synergy under the administration account, it solved all problems.