Month: October 2007

Securing a WCF service with Certificates

For a client and server to talk securely with message level encryption, they both require certificates to encrypt and decrypt messages from the other. Those certificates need to be produced and installed on each machine. This post shows how that can be done, and what settings are required to work with the certificates. Thanks to Mitch Denny, who wrote a very good post on the use of certificates, which helped a lot more than some of the official documentation. This post assumes that you’re using Juval Lowy of IDesign’s ServiceModelEx extensions for WCF. If you’re not, you should really consider these additions – they add declarative security and better validation amongst many other enhancements.

First you need to create a certificate for both the client and the server. Most examples demonstrate the scenario on a single machine thus glossing over the fact that in that situation you only need the one certificate. It obscures the real process of certificate exchange which I’ll show here.

The following is a little script (called setupcert.cmd) that will create a new certificate using makecert.exe, will add it to the ‘My’ cert store on the location machine hive of the registry. It will then export that cert for use on the other machine.

set CERT_NAME=%1
certmgr.exe -del -r LocalMachine -s My -c -n %CERT_NAME%
makecert.exe -sr LocalMachine -ss MY -a sha1 -n CN=%CERT_NAME% -sky exchange -pe
certmgr.exe /put /c /r LocalMachine /n %CERT_NAME% /s my %CERT_NAME%.publickey.cer

You pass one parameter to the script, which is the common name you want to give to the certificate. For instance, you could call it “ServerSide” or “ClientSide”.

Run the script on the client side.

setupcert ClientSide

You should now have a file in the current directory called ClientSide.publickey.cer. Copy this file over to the server side. You are now be able to install the client side cert on the server side.

Double click on the client side cert file. You should get a warning about the unknown provenance of the cert.

image

Click the Open button. Then click on the ‘Install Certificate…’ button.

image

You should now be running the certificate install wizard (or equivalent).

image

Click Next. On the next page select to place the certificate in the store of your choice. A dialog box appears with the cert stores available. Check the ‘Show Physical Stores’ checkbox like so. Click OK to proceed.

image

You will now get the confirmation window.

image

Click Finish to complete the import. If all goes well you get this.

image 

At this stage we have a certificate installed on the client side called ClientSide. This certificate was copied to the server side and installed in the LocalMachine trusted people store. Now the reverse has to be done. Go to the server side and invoke the script from there.

setupcert ServerSide

copy ServerSide.publickey.cer to the client side, and from there you should repeat the import procedure outlined above. The certificates should now be configured. To confirm that, open mmc.exe and add a certificates snap-in for the local machine. On the client side you should see the ClientSide certificate in the personal certificates store.

image

In the Trusted People certificates you should see the server side certificate.

image

The reverse should be true for the Server side certificate stores.

Configuring the service endpoints

The client side proxy needs to reference its certificate like so.

ServiceProxy proxy = new ServiceProxy();
SecurityHelper.SecureProxy<IMyService>(proxy, "ClientSide");

And it can reference the server side certificate via the configuration settings.

        <endpoint 
          address="http://nitrogen:8001/MyService" 
          binding="wsHttpBinding" 
          contract="SandlNtSvc.IMyService">
          <identity>
            <dns value="ServerSide" />
          </identity>
        </endpoint>

The server side references its certificate via its security behavior attribute.

    [SecurityBehavior(ServiceSecurity.Anonymous, "ServerSide")] 
    public class MyService : IMyService
    {

That’s all the configuration needed for the service and proxy to talk to each other.

PS. remember to delete any cert files left lying around!

Announcing LinqToRdf 0.3 and LinqToRdf Designer 0.3

The third release of LinqToRdf has been uploaded to GoogleCode. Go to the project web site for links to the latest release.

LinqToRdf Changes:
– support for SPARQL type casting
– numerous bug fixes
– better support for identity projections
– more SPARQL relational operators
– latest versions of SemWeb & SPARQL Engine, incorporating recent bug
fixes and enhancements of each of them

I have also released a new graphical designer to auto-generate C# entity models as well as N3 ontology specifications from UML-like designs. This new download is an extension to Visual Studio 2008 beta 2, and should make working with LinqToRdf easier for those who are not that familiar with the W3 Semantic Web specifications.

Please let me know how you get on with them.

Semantic Web Visual Designer for Visual Studio .NET

Just posting a quick update about progress with LinqToRdf and a side-project I’m working on to create a visual design tool to allow you to do visual editing of ontologies in Visual Studio .NET 2008. Since I’m a very creative person, I’ve decided to call it LinqToRdfDesigner. :-)

The designer uses Microsoft’s DSL tools system to produce attractive visual designs:

image

So far, I’ve got it producing N3 notation from models, like so:

@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . 
@prefix daml: <http://www.daml.org/2001/03/daml+oil#> . 
@prefix log: <http://www.w3.org/2000/10/swap/log#> . 
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . 
@prefix owl:  <http://www.w3.org/2002/07/owl#> . 
@prefix xsdt: <http://www.w3.org/2001/XMLSchema#>. 
@prefix : <http://aabs.purl.org/ontologies/2007/04/music#> .  

:Item a owl:Class . 
:Title a owl:Class . 
:name 
    rdfs:domain :Title; 
    rdfs:range :string. 
:Book a owl:Class ; 
    rdfs:subClassOf :Item . 
:Member a owl:Class . 
:Library a owl:Class . 
:catalog 
    rdfs:domain :Library; 
    rdfs:range :Title. 
:stockItem 
    rdfs:domain :Library; 
    rdfs:range :Item. 
:member 
    rdfs:domain :Library; 
    rdfs:range :Member. 
:Loan a owl:Class . 
:commenced 
    rdfs:domain :Loan; 
    rdfs:range :DateTime. 
:Reservation a owl:Class . 
:made 
    rdfs:domain :Reservation; 
    rdfs:range :DateTime.

Not all of the relationships are complete yet, but it shouldn’t be too hard. Next step is to produce the C# entity model as well. This should have the nice side benefit that the ontology and the object model are always kept in sync. Eventually, it will expand to include more of the OWL specification than can currently be easily modeled in object oriented languages like C#.

So, what do you think? Would you be more inclined to use semantic web tools if the steps needed to get started were already familiar to you, and you didn’t need to go too deeply into the W3C standards? Would you be willing to pay for it? how much would you be willing to pay? Please respond to this with your thoughts.

Silverlight HtmlElement wrappers

I’ve been glancing at the HtmlElement class in Silverlight today. It’s a nice system, but it’s clearly a work in progress. Everything I’ve said in the past about lumping all of your object model into a single class applies to this. The thing that irritated me was that it wouldn’t have been hard for the Silverlight 1.1 team to make the developer experience more palatable even if they were using the one class under the hood.

private void Test1()
{
  HtmlDocument document = HtmlPage.Document;
  document.GetElementByID("Submit1").AttachEvent("onclick",
    (object obj, EventArgs args) =>
      {
        Text1.SetAttribute("value", (++counter).ToString());
        Text1.SetStyleAttribute("color", "blue");
      }
    );
}

Not a lot you can say about this other than “Where’s the classes, dude?“. It wouldn’t have been hard, to give us something like this:

private void Test1()
{
  HtmlDocument document = HtmlPage.Document;
  document.GetElementByID("Submit1").AttachEvent("onclick",
    (object obj, EventArgs args) =>
      {
      Text1.Text = (++counter).ToString();
      Text1.Style["color"] = "blue";
      }
    );
}

Don’t believe me? Well, here’s a wrapper around an HtmlElement that refers to an input element of type text.

public class TextBox : HtmlElement
{
  HtmlElement elem;
  public TextBox(HtmlElement elem)
  {
    this.elem = elem;
    Style = new StyleSet(elem);
  }
  public string Text
  {
    get
    {
      return elem.GetAttribute("value");
    }
    set
    {
      elem.SetAttribute("value", value.ToString());
    }
  }
  public StyleSet Style
  {
    get;
    set;
  }
}

This class uses a StyleSet class that provides an indexer into the styles of the HtmlElement:

public class StyleSet
{
  private HtmlElement Element{get;set;}
  public StyleSet(HtmlElement elem)
  {
    Element = elem;
  }
  public string this[string key]
  {
    get
    {
      return Element.GetStyleAttribute(key);
    }
    set
    {
      Element.SetStyleAttribute(key, value);
    }
  }
}

As you can see, this is pretty simple stuff. All I need to do is provide a conversion when I want to get to the element in my code behind:

public TextBox Text1
{
  get
  {
    HtmlDocument document = HtmlPage.Document;
    return new TextBox(document.GetElementByID("Text1"));
  }
}

This wraps the HtmlElement in a TextBox instance, and from there on you can access it in way that appeals to programmers.

Lambda Functions for Design By Contract

This is sadly not one of those blog posts where I show you what I have managed to achieve. Instead it’s one where I ask you if you have a solution for what I am after.

When I was at university, my professor convinced me that the benefits of design by contract were worth the cost of the implementation. In every language that I have worked with ever since, I have implemented some sort of veneer over the top of the language to enable design by contract. I’ve used all sorts of code generators or AOP systems to do it for me. As you may have seen from my last post, I’ve been on the WCF Masterclass with Juval Lowy, and I’ve been inspired by the pretty extensibility model of WCF to give DBC in C# another stab.

WCF provides class construction behavior that is nicely extensible through the use of attributes. If an attribute, for example, derives from IServiceBehaviour, then WCF will  run a method on the attribute, passing in the object that the attribute was attached to. This gives the attribute (or a helper class that it uses) the opportunity to modify some of the settings for the context of the service. This is a perfect model for me to do the same thing using predicates in a DBC system. First I just need to designate an interface class that marks a derived attribute as worth paying attention to by my class factory. Lets call it IExtensibilityBehaviour. If the class factory spots an attribute on a type it’s trying to dispense, it can provide special behavior for the class such as wrapping it, or running something like PostSharp over it to insert some code to run pre and post condition predicates. here’s an example attribute that I want to attach to a class:

[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
sealed class InvariantPredicateAttribute : Attribute, IExtensibilityBehaviour
{
    Func<object, bool> Predicate { get; set; }
    public InvariantPredicateAttribute(DbcPredicate predicate)
    {
Predicate = predicate; }
    public void Validate(object x)
    {
        if (!Predicate(x)) 
            throw new ApplicationException("Invariant Predicate Failed");
    }
}

The attribute above takes a delegate as a constructor parameter and stores it in the Predicate property. I can then add the attribute to a class like so:

[InvariantPredicate((TestClass x)=>x.FirstName != null)]
public class TestClass
{
    public string FirstName { get; set; }
}

As you can see, I insert a Lambda function as the parameter, which I could then elsewhere invoke like so:

TestClass t = new TestClass()
// Do something with it
foreach (InvariantPredicateAttribute ipa in 
    typeof(TestClass).GetCustomAttributes(
        typeof(InvariantPredicateAttribute), true))
{
     ipa.Validate(t);
}

Sadly, this is where I come to a crashing halt. You can’t do this in C# 3 or less. I get the following:

C:\…\AttributeEx.cs(34,29): error CS1706: Expression cannot contain anonymous methods or lambda expressions

If you read the commentary here, from a year or two ago, it seems to imply that the problem would be solved in future builds of VS.NET. Well, I’m running the latest beta of VS.NET 2008, and it still is a problem. Which is where YOU come in. Can you think of a way for me to get round this? I’ve tried a few ideas, and I just can’t get it to work for one reason or another.

Help. Please.

Lambda Functions in Multi-threaded Development

I’m on one of Juval Lowy’s WCF Masterclass courses at the moment. Needless to say, my mind is buzzing from the fire-hose brain-dump he’s doing on us at the moment. It’s wonderful to see someone so deeply in command of the technology, not to mention daunting at the sheer incline of the learning curve. He’s had some influence on the development of both C# and Visual Studio as well as WCF, so it’s not surprising that he has sprinkled the course with some elegant little language features that joined the dots for me. With 1400 slides in his slide deck, there’s plenty of space for language digressions as well.

One favorite of mine was the use of the new lambda function notation in the course of everyday UI and multithreaded development. Wherever you see a delegate, callback or handler in your normal code you can now make use of a lambda function. Of course this won’t be news to the functional programmers out there, but within a few years there will be more functional code in production environments via C# than ever came from pure functional languages.

[TestMethod]
public static void TestLambdas()
{
  for (int i = 0; i < 300; i++)
  {
    Thread t = new Thread((x) =>
      {
        Thread.CurrentThread.Name = x.ToString();
        Thread.Sleep(r.Next(250, 500));
        Trace.WriteLine(string.Format("Hello from thread {0}",
          Thread.CurrentThread.Name));
      });
    t.Start("T " + i);
  }
  Thread.Sleep(10000);
}

This is nice and clean, and will prevent any nasty proliferation of one line event handlers.

Bush a Holocaust Denier?

Is it a coincidence that in the mid-evening news there was a report that the US was doing everything in its power to broker detente between Turkey and Iraq, and an hour later I heard reports of Bush pushing the House of Representatives not to pass a bill acknowledging the Armenian Massacre?

Given the recent history of US administrations to ‘reclassify’ atrocities as ‘not genocide’  to not be morally obligated, I wouldn’t be surprised.

Turkey warns US over genocide law
News – Middle East – Iraq fears Turkey troop build-up