Archive for January, 2009

WCF + Azure October 2008 SDK = Time to upgrade

Around the beginning of January, 2009, I began my experimentation with Azure. This meant installing the October 2008 SDK. Being a WCF geek, I tried writing a service a few minutes after I got Hello World working. Complete FAIL. No matter what binding I tried, I would get a message about having issues with config not allowing partially trusted assemblies. I tried all sorts of things to get the service working, and I eventually got something going by writing custom ServiceHostFactory (no config) that also stripped out the multiple HTTP endpoints appearing when the web site tried to create the service. Not exactly a happy experience. On January 14, a new version dropped. Now, I am reduced to using the basicHttpBinding, but I don’t need to use the custom ServiceHostFactory to diagnose things.

Leave a comment

Need a favicon.ico?

I needed a favicon.ico file for a web site I’m working on. I had the image that I wanted to use and needed a quick and dirty way to generate the correct icon file. Keep in mind, I’m a developer with limited artistic skills. After trying some icon editors (FAIL), I found a site that claims to make an icon based on a file you upload. Seemed to easy, but it was exactly what I needed. This is a great tool at a perfect price: It took my Twitter image:


and gave me a favicon.ico: favicon

Leave a comment

The Benefits of Positive Logic

This article discusses a coding practice that I discovered while an undergrad a while back, maybe 1994. After doing some code reviews recently, I am reminded that this particular practice still needs more publicity. When writing code, a developer typically likes to worry about edge cases first, then handles the normal case. This practice has some benefits: the cases you worry about most get handled early. And, this practice creates maintenance nightmares. This practice has a some detrimental effects:

  • Code readability is reduced
  • Precious cycles are wasted on the uncommon cases
  • Code complexity frequently increases

People remember and read positives easily. They have more issues with negatives. Consider the following C# code:

    1 FileStream fs = null;

    2 const string filename = "someFile.txt";

    3 if (!File.Exists(filename))

    4 {

    5     fs = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite);

    6 }

    7 else

    8 {

    9     File.Delete(filename);

   10    fs = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite);

   11 }

Consider what happened when a developer wrote the code above. They thought, "OK, if this file does not exist, then I can create it. However, if the file does exist, I want to make sure I start with a clean slate, so I’ll delete the file, then create it." The code above is confusing. The thoughts are equally confusing. While I wish this code were an anomaly, it isn’t. This is something I see on a regular basis: in support forums, in code that didn’t have time for a proper review, and elsewhere. Consider what would have happened if the developer had chosen to use positive logic instead of negative:

    1 FileStream fs = null;

    2 const string filename = "someFile.txt";

    3 if (File.Exists(filename))

    4 {

    5     File.Delete(filename);

    6 }

    7 fs = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite);

Here, the code is more readable and the intent is clearer: if the file exists, delete it. Then, open the file for read/write. Note that the code is now smaller and maintenance is easier too.

Here is another example, this one a PowerShell script from TechNet magazine. Here, we have an example where readability is diminished thanks to negative logic. Line 15 just bugs me. Read the code:

1. function Get-WmiInventory {
2.  param (
3.  $wmiclass = "Win32_OperatingSystem"
4.  )
6.   $ErrorActionPreference = "SilentlyContinue"
7.   $computer = $_
8.   trap {
9.    $computer | out-file c:errors.txt -append
10.    set-variable skip ($true) -scope 1
11.    continue
12.   }
13.   $skip = $false
14.   $wmi = Get-WmiObject -class $wmiclass -computer $computer -ea stop
15.   if (-not $skip) {
16.    foreach ($obj in $wmi) {
17.     $obj | Add-Member NoteProperty ComputerName $computer
18.     write $obj
19.    }
20.   }
21.  }
22. } 

OK: If I should not skip then I should do work. With a little better naming, we could make this all more readable. How about this instead:

1. function Get-WmiInventory {
2.  param (
3.  $wmiclass = "Win32_OperatingSystem"
4.  )
6.   $ErrorActionPreference = "SilentlyContinue"
7.   $computer = $_
8.   trap {
9.    $computer | out-file c:errors.txt -append
10.    set-variable shouldWriteComputerInfo ($false) -scope 1
11.    continue
12.   }
13.   $shouldWriteComputerInfo = $true
14.   $wmi = Get-WmiObject -class $wmiclass -computer $computer -ea stop
15.   if ($shouldWriteComputerInfo) {
16.    foreach ($obj in $wmi) {
17.     $obj | Add-Member NoteProperty ComputerName $computer
18.     write $obj
19.    }
20.   }
21.  }
22. } 

Here, readability goes up because I can now see exactly why we DO go into the loop instead of seeing why we do NOT.

If you write negative logic, do a pass after writing things to fix up the code. Do that pass immediately. I frequently write code like:

if (not X){

160; Do A


else {

    Do B


I immediately turn around and rewrite this code as:

if (X){

    Do B


else {

    Do A


I have found that I can read this kind of code long after writing it and remember what I meant. I have difficulty doing the same thing with negative logic paths.

Leave a comment

NHibernate at the Lake County .NET User Group (Jan 29)


January Meeting: NHibernate

January 29, 2009 6:30-9:00 PM PM


We’ll be introducing NHibernate from the ground up.
The problem of O/R Impedance Mismatching.
The benefits of utilizing a transparent object persistance framework such as NHibernate.
How to get started with NHibernate with an example class library and the mapping files required for NHibernate.
Some best practices regarding persisting and retrieving objects along with code examples.

BIO: Robert Dusek

I began programming in various incarnations of BASIC at a young age, but began my career in IT Operations as a network administrator. About 4 years ago, I stumbled onto .NET in order to solve various development tasks that my employer needed, eventually choosing to transition into C# Software Development full-time. I currently work with Hudson at GFX International building client-facing applications using MVC.Net and NHibernate. Recently Hudson and I along with Ricardo Borges have taken over as maintainers for Ayende’s NHibernate Query Analyzer.

BIO: Hudson Akridge
My early career was as a Database Developer, turning my attention towards .NET the last 3 years. I currently work at GFX Int. as a Corporate Dev writing both internal and external production applications relating to Manufacturing and Client management processes utilizing Alt.NET technologies such as MVC.NET and NHibernate.

Street: 19351 West Washington Street
City: Grayslake
Country: USA
State: Illinois



Campus map


Leave a comment

Misunderstood: Add Service Reference

Every so often, I get into a discussion about whether Add Service Reference is required in an application if the application owns both the service and one consumer. The short answer is No. But, you probably want to know Why? To understand that, we need to look at what Add Service Reference actually does and why you can do the same for yourself.

For the purposes of our discussion, the work actually being done by the service is unimportant. Let us assume the following interface:

    1 using System.ServiceModel;


    3 namespace BlogWCF

    4 {

    5     [ServiceContract]

    6     public interface ISimpleService

    7     {

    8         [OperationContract]

    9         string SayHello(string name);

   10     }

   11 }

The implementation of the interface is then

    1 namespace BlogWCF

    2 {

    3     public class SimpleService : ISimpleService

    4     {

    5         public string SayHello(string name)

    6         {

    7             return string.Format("Hello, {0}", name);

    8         }

    9     }

   10 }

So, nothing terribly complex going on. To be able to discover information about this service, we will also add a metadata endpoint (the configuration is at the end of this article). With the metadata endpoint exposed, we can point Add Service Reference at the endpoint and generate a consumer. Add Service Reference does not necessarily know that the other endpoint is implemented in Java, .NET, or some other language. It generates a bunch of bookkeeping files so that the client can be regenerated at will. If you click on Show All Files in your VS project, you will see many files under the reference you just added.

  • configuration.svcinfo: Contains a snapshot of the configuration generated for the client service endpoint for the local (app|web).config 
  • configuration91.svcinfo: For each property in config, contains an XPath to the setting and the original value stored in config.
  • *.wsdl: Copies of the WSDL files exposed by the WSDL endpoint.
  • *.xsd: Copies of any schema files exposed by the WSDL endpoint.
  • Reference.svcmap: Pointer to the service and pointers to any svcinfo, wsdl, and xsd files in the project. This file also stores any special settings selected by the user from when the ServiceReference was first generated. All of this is used when the user chooses to regenerate the reference.
  • Reference.(cs|vb): Contains a WCF compatible interface of the contract, a client channel capable of communicating with the contract, and a proxy class that can be instantiated.

All these files are needed to create and refresh a client when you do not control the client. When you do control the client, none of this is needed. You can share the configured binding in between the client and the service. However, you must put the service contract on an interface– that’s the only real requirement. If your client and service are in different binaries, I would recommend putting the Service and Data contracts into yet another class library that can be referenced from the service and the consumer. This reduces the coupling of the interface its implementation. Furthermore, you need to define the WCF contract on an interface, not on the implementation class. WCF cannot construct a client implementation based on a class definition. This is due to a number of details associated with how the CLR allows code to intercept method calls. The general rule is that you can intercept method calls on interfaces but not on classes.

To consume the service, WCF needs to know the address, the binding, and the contract, nothing more. WCF class libraries know nothing of the .svcmap file and its cohorts. Using this mechanism, we then talk to the service using code that many of us have seen before. If you own the service implementation, none of this is necessary. Instead, you can use stuff you know to create the client on your own. I’m going to show you some code that I have for a console application. This code will work no matter the context (Web, service, Windows app). The code shows three variations: reading the ServiceEndpoint from the ServiceHost, running the client from pure code, or reading the client from configuration. This is just a demonstration of what is possible.

    1 using System;

    2 using System.ServiceModel;


    4 namespace BlogWCF

    5 {

    6     class Program

    7     {

    8         static void Main(string[] args)

    9         {

   10             using (ServiceHost host = new ServiceHost(typeof(SimpleService)))

   11             {

   12                 host.Open();

   13                 Console.WriteLine("Service opened");


   15                 // Using the service description

   16                 using (ChannelFactory<ISimpleService> client = new

   17                     ChannelFactory<ISimpleService>(host.Description.Endpoints[0]))

   18                 {

   19                     ISimpleService channel = client.CreateChannel();

   20                     Console.WriteLine(channel.SayHello("Service Description"));

   21                 }


   23                 // Using stuff we know from config.

   24                 using (ChannelFactory<ISimpleService> client = new

   25                     ChannelFactory<ISimpleService>(new WSHttpBinding(),

   26                     new EndpointAddress("http://localhost:8731/Design_Time_Addresses/BlogWCF/SimpleService/&quot;)))

   27                 {

   28                     ISimpleService channel = client.CreateChannel();

   29                     Console.WriteLine(channel.SayHello("Binding"));

   30                 }

   31                 // Using a client in config.

   32                 using (ChannelFactory<ISimpleService> client = new

   33                     ChannelFactory<ISimpleService>("SampleClient"))

   34                 {

   35                     ISimpleService channel = client.CreateChannel();

   36                     Console.WriteLine(channel.SayHello("config"));

#160;                }

   38                 Console.ReadLine();

   39             }

   40         }

   41     }

   42 }

Config for the service:

    1 <?xml version="1.0" encoding="utf-8" ?>

    2 <configuration>

    3     <system.serviceModel>

    4         <client>

    5             <remove contract="IMetadataExchange" name="sb" />

    6             <endpoint address="" binding="netTcpRelayBinding" bindingConfiguration="metadataExchangeRelayBinding"

    7                 contract="IMetadataExchange" name="sb" />

    8             <endpoint address="http://localhost:8731/Design_Time_Addresses/BlogWCF/SimpleService/"

    9                 binding="wsHttpBinding" bindingConfiguration="" contract="BlogWCF.ISimpleService"

   10                 name="SampleClient" />

   11         </client>

   12         <behaviors>

   13             <serviceBehaviors>

   14                 <behavior name="BlogWCF.SimpleServiceBehavior">

   15                     <serviceMetadata httpGetEnabled="true" />

   16                 </behavior>

   17             </serviceBehaviors>

   18         </behaviors>

   19         <services>

   20             <service behaviorConfiguration="BlogWCF.SimpleServiceBehavior"

   21                 name="BlogWCF.SimpleService">

   22                 <endpoint address="" binding="wsHttpBinding" contract="BlogWCF.ISimpleService">

   23                     <identity>

   24                         <dns value="localhost" />

   25                     </identity>

   26                 </endpoint>

   27                 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

   28                 <host>

   29                     <baseAddresses>

   30                         <add baseAddress="http://localhost:8731/Design_Time_Addresses/BlogWCF/SimpleService/" />

   31                     </baseAddresses>

   32                 </host>

   33             </service>

   34         </services>

   35     </system.serviceModel>

   36 </configuration>

Leave a comment

F# assembly level attributes, AssemblyInfo.fs, and do()

The project for this weekend is to create something that I can share with the rest of the web allowing one to create Web projects with F#. Part of doing this the right way is to include that handy dandy litany of assembly level attributes indicating things like assembly name, version, description, configuration, company, etc. In a C# project, this information appears in AssemblyInfo.cs. For my F# project, I figured that AssemblyInfo.fs is as good a place as any to start. So, how do you do this? Like in C#, assembly level attributes occur at file scope and have the word assembly: in front of the attribute. They wind up going into a file like so:


[<assembly: AssemblyVersion("")>]

[<assembly: AssemblyFileVersion("")>]


Now, AssemblyInfo.fs wasn’t going to have any types, and this frustrated the F# compiler a bit. After some tweaks, it coughed up a hint to use do(). So, I went ahead and put in:



open System.Reflection

open System.Runtime.CompilerServices

open System.Runtime.InteropServices

[<assembly: AssemblyVersion("")>]

[<assembly: AssemblyFileVersion("")>]


What is that do for? Looking at the spec, this is something called a do binds an expression and asserts that expression is equal to unit. Here, I’m binding to an empty tuple, so the dimension in unit. This is sufficient for the compiler to be happy and allow the attributes to be evaluated and added to the assembly at compile time.

Leave a comment

F# does a WCF Service

I spent a large portion of my career working with WS-*/SOAP. So, once I understood how F# attributes worked, I thought it would be cool to see if I could write a WCF service. Nothing complex– I just wanted to see if I could get HelloWorld up and running. Given that one can get a class running as a service with the right config and .svc file, this seemed like an easy task. First, I’ll present the solution, then I’ll talk about a couple of issues I ran into along the way to the solution. In F#, one adds attributes by placing a [<Attribute>] before the type or member. For WCF, we need the ServiceContractAttribute and OperationContractAttribute on the type and any exposed functions. The HelloWorld service can be written like this:


    1 #light


    3 namespace Service

    4     open System.ServiceModel


    6     [<ServiceContract>]

    7     type MyContract =

    8            new() = {}

    9            [<OperationContract>]

   10            member x.HelloWorld(name: string)= “Hello, “ + name


Following the path most folks take, hosting in IIS, we next write a .svc file with the following content:

<%@ ServiceHost Service=”Service.MyContract”  %>

This just tells the ServiceHostFactory to instantiate an object of type Service.MyContract whenever a request comes in. Finally, we go into web.config and add the following markup:


    1     <system.serviceModel>

    2         <behaviors>

    3             <serviceBehaviors>

    4                 <behavior name=SimpleService.SimpleServiceBehavior>

    5                     <serviceMetadata httpGetEnabled=true/>

    6                     <serviceDebug includeExceptionDetailInFaults=false/>

    7                 </behavior>

    8             </serviceBehaviors>

    9         </behaviors>

   10         <services>

   11             <service behaviorConfiguration=SimpleService.SimpleServiceBehavior name=Service.MyContract>

   12                 <endpoint address=“” binding=wsHttpBinding contract=Service.MyContract>

   13                     <identity>

   14                         <dns value=localhost/>

   15                     </identity>

   16                 </endpoint>

   17                 <endpoint address=mex binding=mexHttpBinding contract=IMetadataExchange/>

   18             </service>

   19         </services>

   20     </system.serviceModel>

Finally, I wrote a client application in C#, using Add Service Reference in VS2008 to generate the client code.


    1 class Program

    2 {

    3     static void Main(string[] args)

    4     {

    5         using (ServiceReference1.MyContractClient client = new SimpleClient.ServiceReference1.MyContractClient())

    6         {

    7             Console.WriteLine(client.HelloWorld(“Scott”));

    8         }

    9     }

   10 }

And it all worked just fine. I know– it’s all .NET and that’s the way things should work. I’m most impressed by the terseness of F#.

OK, so what did I learn while doing this? First off, F# does NOT create a default, empty constructor for classes. WCF barked at me when I tried to access the SVC file, stating that it couldn’t create the object because the object lacked a default constructor. So, I dug into the F# spec and learned that a default, do nothing constructor looks like


           new() = {}

I also tried doing this in the traditional way, with an interface definition first and then an implementation of the interface. That didn’t work so well. In F#, the interface looks like this:



    type IMyContract =


            abstract HelloWorld : string -> string


That little bit on HelloWorld states that the input is a single string that yields a string. The input parameter does not have a name, and that’s a problem. No name means no name, null, in F#. When System.ServiceModel does its reflection thing to figure out what the name of the parameter in the message should be, it sees a null and throws up its hands. I was able to name the parameter only when applying the attributes on the named parameter in the implementation. So, I ditched the interface. Maybe I missed something that would allow me to name the parameter, but I’m not too sure what it could be. For now, I’ll assume that this was a legitimate issue. I’ll update this post if I learn otherwise.

Leave a comment


Get every new post delivered to your Inbox.