Category Archives: Uncategorized

Java Memory Model

Some resources about the Java Memory Model:

Exposing a WCF Data Service via the Azure AppFabric Service Bus

 

The How

 

The following excerpt shows how to expose a WCF Data Service via the Azure AppFabric Service Bus, using a self-hosted ServiceHost.

 

using(var host = new DataServiceHost(
                     typeof(PersonsDataService), new Uri[0])){
  host.AddServiceEndpoint(
    typeof (IRequestHandler),
      new WebHttpRelayBinding(
            EndToEndWebHttpSecurityMode.Transport, 
            RelayClientAuthenticationType.None),
      “https://my-namespace.servicebus.windows.net/pds)
    .WithServiceBusTransportCredentials();
 
    host.Open();
    Console.WriteLine("host is opened, press any key to exit");
    Console.ReadKey();
}

where

  • PersonsDataService is the data service to be exposed;
class PersonsDataService : DataService<MyDataModel>{
    public static void InitializeService(
                           IDataServiceConfiguration config) {
    }
}

 

  • IRequestHandler is the WCF Data Services generic service contract (see below);
  • WebHttpRelayBinding is the Azure AppFabric Service Bus binding for the “web programming model”.
  • and WithServiceBusTransportCredentials is an extension method for configuring the service bus transport credentials
public static ServiceEndpoint WithServiceBusTransportCredentials(this ServiceEndpoint edp)        {
    ConfigureTransportCredentials(edp);
    return edp;
}
public static void 
ConfigureTransportCredentials(ServiceEndpoint edp) {
    var tcred = new TransportClientEndpointBehavior();
    tcred.CredentialType = 
            TransportClientCredentialType.SharedSecret;
    tcred.Credentials.SharedSecret.IssuerName = IssuerName;
    tcred.Credentials.SharedSecret.IssuerSecret = SharedSecret;
    edp.Behaviors.Add(tcred);
}

 

 

The Why

WCF Architecture

The Windows Communication Architecture is based on two layers:

  • The Channel Model Layer is a stack of channels that operate on messages, composed by
    • Zero or more protocol channels, implementing protocols such as WS-Security.
    • One transport channel that send or receives the messages from the transport medium (e.g. TCP, pipes). This transport channel uses a message encoder/decoder to translate between the messages handled by the protocol channels and the transport’s byte streams.
  • The Service Model Layer is responsible for the translation between messages and service method calls.

image

 

WCF Data Services

WCF Data Services are layered on top of the WCF Service Model:

image

[ServiceContract]
public interface IRequestHandler {    
    [OperationContract, 
     WebInvoke(UriTemplate = "*", Method = "*")]
    Message ProcessRequestForMessage(Stream messageBody);
}
[AspNetCompatibilityRequirements(
    RequirementsMode = 
        AspNetCompatibilityRequirementsMode.Allowed), 
 ServiceBehavior(
     InstanceContextMode = InstanceContextMode.PerCall)
]
public class DataService<T> : IRequestHandler, IDataService {
    ...
    public Message ProcessRequestForMessage(Stream messageBody){...}
    ...
}

 

Azure AppFabric Service Bus

The Azure AppFabric SDK contains several bindings to expose and consume services via the service bus, namely the WebHttpRelayBinding that uses the Web HTTP programming model. This binding defines a channel stack with a RelayHttpTransportChannelListener that opens a TCP connection to the services bus and listens to messages relayed by it.

image

 

Since the Service Bus bindings extend the channel layer and the WCF Data Services are layered on top of the Service Model Layer, their composition is straightforward.

ACM article by B. Stroustrup

The January 2010 edition of Communications of ACM contains an interesting article by Bjarne Stroustrup, named “What Should We Teach New Software Developers? Why?

Many professors will object: "I don’t have the time to program!" However, I think that professors who teach students who want to become software professionals will have to make time and their institutions must find ways to reward them for programming. The ultimate goal of CS is to help produce better systems. Would you trust someone who had not seen a patient for years to teach surgery? What would you think of a piano teacher who never touched the keyboard? A CS education must bring a student beyond the necessary book learning to a mastery of its application in complete systems and an appreciation of aesthetics in code.

Recommended reading for this holiday season.

P.S.: Another related articleby Bjarne Stroustrup: Programming in an undergraduate CS curriculum, WCCCE’09, May 2009

This leads to the question of what to teach first: the theoretical basis or the craft? Since there is no way a student can appreciate the problems of writing correct software or maintaining large code bases without having programming experience, we have to start by writing code. Only through trying to write code and debugging it do people get to appreciate the magnitude of difficulty in producing correct software. Furthermore, only by facing the problems of evolving an existing code base do people appreciate the value of clean design, supporting tools, and testing. Long lectures on software engineering to people with a weak software background are at best ineffective and at worst instill a dislike for programming as a low-level activity unworthy of serious attention (“a mere implementation detail”) …

JAXB Fluent API

Two weeks ago I taught a short session on C# 3.0 and LINQ, including LINQ to XML. One of the things that I really admire in this technology is the functional construction of XML elements.

Last week I started using JAXB to construct and consume XAdES digital signatures. One of the aspects that I immediately disliked was the way to build the object trees, using the classes generated by the binding compiler (XJC). Each of these classes has a parameterless constructor and a set of setter and getter methods to assign and retrieve each of the properties. Unfortunately the setter methods have void as the return type, meaning that an object initialization requires multiple statements. When building a deeply nested hierarchy, this implies code like the one showed below, where the tree is built in reverse order (from leafs to root).

   1: Person alice = new Person();

   2: alice.setName("Alice");

   3:  

   4: Person bob = new Person();

   5: bob.setName("Bob");

   6:  

   7: Person carol = new Person();

   8: carol.setName("Carol");

   9: carol.setFirstChild(alice);

  10: carol.setSecondChild(bob);

I find this code very unpleasant to write, namely when I’m familiar with better idioms, so I immediately started thinking in a way to solve this.

Fortunately, I found the XJC Fluent API Plugin, which extends the classes generated by the binding compiler with extra methods called “withXXX”. These methods are similar to the setter methods with the important difference that they return the instance on which they were called, allowing for method chaining. Using this, the above initialization code becomes

   1: Person carol = new Person().withName("Carol")

   2:     .withFirstChild(new Person().withName("Alice"))

   3:     .withSecondChild(new Person().withName("Bob"));

Notice that the code structure now follows the element structure (from root to leafs). This makes it easier to read and also to write, since the IDE’s auto-completion feature can be used to “guide” the method chaining.

Some remarks regarding this plugin:

Using _ as an extension method

In C#, as in many other languages, “_” is a valid identifier (as reminded to me by Erik Meijer on a C9 Lecture)

Recently, I used this knowledge to create the following extension method:

    public static class StringExt {

        public static XElement _(this string s,

                            params object[] objs) {

            return new XElement(s, objs);

        }

    }

Why? To enable this coding style

            "html"._(

                "body"._(

                    "table"._(

                        "tr"._(

                            from colName in colNames

                            select "th"._(colName)),

                        from e in seq

                        select "tr"._(

                            from f in colFuncs

                            select "td"._( f(e))))))

            .Save(name);           

The above fragment creates an HTML document containing a table, where:

  • IEnumerable<T> seq is a sequence of elements, where each element corresponds to a table row.
  • List<string> colNames is a sequence of column names
  • Linked<Func<T, string>> colFuncs is a sequence of functions, where each function is used to project one sequence element (e) into a column cell.

Without extension methods, this fragment would be written as:

    new XElement("html",

         new XElement("body",

            new XElement("table",

                new XElement("tr",

                    from colName in colNames

                    select new XElement("th", colName)),

                from e in seq

                select new XElement("tr",

                    from f in colFuncs

                    select new XElement("td", f(e))))))

    .Save(name);

More “noisier”, on my opinion.