October 2008 Archives

To my surprise, I heard in Ray Ozzie's keynote this morning that Microsoft is building a Remote Monitoring Service (RMS) using System Center and their new cloud-based service platform, Azure. They'll use a SCOM as the local, on-premises agent that will relay alerts into the cloud where a bunch of compute nodes will process the event streams and make it available via the Web in report, dashboard, and scorecard form.

Why would I raise an eyebrow at this? It's a straight forward thing to do and an obvious way to sell an existing product to a wider array of customers. I found it surprising because I pitched a similar idea at my old company at the beginning of the year using their NMS as the local agent and AWS as the service platform. I discussed it with my boss and he said that companies weren't ready to put their data in the cloud, that they were too concerned about the security ramifications of such an architecture. I didn't disagree with him that many companies wouldn't trust us to manage their data in the cloud, so I dropped it.

Now that Microsoft is providing such a solution, however, I think that companies will be more likely to accept such a notion. I think that companies want a RMS and would like to outsource their network management needs, but haven't trusted the providers of such services. Now, with the 900 lb gorilla selling it, I'm sure many companies will farm out this non-core-competency.

And this, my friends, is the big deal about Azure: it will begin the mainstream adaptation of cloud computing.

A couple of weeks ago, I blogged about a problem I was having that took more time to solve then expected; it was a task that I thought would be fast but turned out not to be. I jokingly described it as the sort that costs you time you would have otherwise spent on a coffee break. Well, unfortunately, I ran into another such dilemma this week, so I thought I would collect the descriptions of these time sinks into an ongoing series which I'll call Coffee Breaks. In it, I'll present the time consuming problems that I bump into, and how I solved them. To kick it off, I give you the second in this new series:

This week, I needed to write a unit test that would isolate a LINQ to SQL DataContext, allowing me to call the methods that mapped my stored procedures and return known data instead of information in a database. This would allow me to test my data access logic without having to establish a connection to a back-end server. To separate my DataContext, I wanted to use TypeMock Isolator 5.1. This seemly simple problem ended up taking a while to solve because A) I'm new to TypeMock Isolator and wasn't familiar with its API, and B) because the SPROC wrappers returned an ISingleResult<T> which I couldn't simply replace with an array or something.

Learning a new library just takes time. While learning Typemock's and applying it to this problem, however, I ran into a couple of obstacles that protracted the effort and eventually cost me my coffee break (so to speak). The issues where these:

  • In order to substitute my known list of results for those returned by the SPROC wrapper method, I had to create a dynamic mock and figure out how to inject my data into it.
  • If I tried to swap in an array when GetEnumerable was called on the dynamic mock, I kept getting a StackOverflowException when executed inside Resharper's test runner.

To elaborate a bit, let me begin by showing the DataContext definition that was generated when I drug the stored procedure from the Server Explorer to the ORM designer:

    1 public partial class MyGoodDataContext : DataContext

    2 {

    3     [Function(Name = "dbo.MyGoodStoredProcedure")]

    4     public ISingleResult<MyGoodStoredProcedureResult> MyGoodStoredProcedure()

    5     {

    6         IExecuteResult result = this.ExecuteMethodCall(this,

    7             ((MethodInfo)(MethodInfo.GetCurrentMethod())));

    8         return ((ISingleResult<MyGoodStoredProcedureResult>)(result.ReturnValue));

    9     }

   10 }

Given this, I had to figure out a way to replace ISingleResult<T> with some object that contained my test data. The only concrete implementation of ISingleResult<T> in the .NET framework is internal, so I tried to create a fake one and replace the original one with my test double using TypeMock Isolator's SwapNextInstance method like this:

var fake = Isolate.Fake.Instance<ISingleResult<MyGoodStoredProcedureResult>>();


This produced a run-time error telling me to use the MockObject method on the MockManager class to create a dynamic mock instead (perfect error message BTW!).

After some fiddling, I figured out this class's API, and the necessity to initialize it via attributes or by an explicate call to its Init method. Afterward, I was able to create a dynamic mock object of type IResultSet<T>. Now I had to somehow cause my canned info to be returned when this object was enumerated. To this end, I replaced the return value of the mock object's GetEnumerable method with my data like this:

results.ExpectAndReturn("GetEnumerator", expected.GetEnumerator(), 1);

At first, the variable "expected" was an anonymous array of MyGoodStoredProcedureResult objects. However, every time that I enumerated this collection in the code under test, a StackOverflowException was through and my test runner would crash. I replaced it with a object of type List, and it worked (bug I reckon).

With those issues resolved, I was able to fake my DataContext and isolate it from the database using this unit test:

    1 [Test, VerifyMocks, Isolated]

    2 public void Test()

    3 {

    4     // Arrange

    5     var dataContext = Isolate.Fake.Instance<MyGoodDataContext>(Members.ReturnRecursiveFakes);

    6     var results = MockManager.MockObject<ISingleResult<MyGoodStoredProcedureResult>>();

    7     var expected = GetExpectedResults();


    9     results.ExpectAndReturn("GetEnumerator", expected.GetEnumerator(), 1);

   10     Isolate.SwapNextInstance<MyGoodDataContext>().With(dataContext);

   11     Isolate.WhenCalled(() => dataContext.MyGoodStoredProcedure()).WillReturn(results.Object);


   13     // Act

   14     var actual = MyGoodRepository.MethodThatInTurnCallsMyGoodStoredProcedure();


   16     // Assert

   17     for (var i = 0; i < actual.Count; i++)

   18         Assert.That(actual[i], Is.EqualTo(expected[i]));

   19 }

Problem solved, but not before coffee time was over :-(

The other day, I bumped into a blog that mentioned a CSS framework called 960 Grid System. I haven't been doing as much Web development in recent years as I used to, but the name caught by eye even though it wasn't clear from the blog post what it was exactly. My teething son woke me up tonight, and I couldn't get back to sleep. So, I thought I'd check it out.

I guess the idea goes back to the kindergarten exercise of copying an original piece of artwork by drawing horizontal and vertical lines through it and replicating the contents of each square to a derived work. Now that we're all grown up though, we do this by starting with a Web design created in Photoshop, enabling a layer that overlays a grid, and marking up the design in HTML and CSS to match the graphic designer's original — one square at a time.

I found this tutorial to be very help in figuring out what this framework and its alternatives are all about. I learned from reading it and other articles, that there are a number of competing CSS-based grid frameworks including

among others. I've used YUI a lot in the past, so I would be inclined to start with that one, but it is purportedly bloated and not as lightweight as some might prefer.

Regardless of which framework is used, just a cursory look shows that making CSS-based layouts is a whole lot easier now than the last time I tried. With these toolkits available nowadays, you can be sure that my next Web site will be laid out using one of them.

There is a lot of new stuff coming down the pike that WCF developers will want to be aware of. Here's a shortlist that I've put together from various corners of the Net:

Programming WCF Services 2nd ed.

Juval Lowy's book on WCF that we've all read will be updated in November according to O'Reilly's Upcoming Title list. I wonder if he'll revise his stance on message contracts in the new edition.

Learning WCF 2nd ed.

Michele Leroux Bustamante was recently interviewed on .NET Rocks, and she said in that conversation that a new edition of her book is in the works. It isn't yes listed as an upcoming title on the publisher's site though.

New Edition of WCF Security Guidance

According to this roadmap document on MSDN, a new edition of the WCF Security Guidance e-book is due out next month. This strikes me as odd since the one that currently available on CodePlex is only two months old. I've posted a question on the community's forum to get some clarification, but haven't received a response yet.

Enterprise Library 4.1 and Unity 1.2

At the end of July, the entlib team started working on version 4.1 which would integrate Unity more deeply into the toolkit among other things. According to this roadmap and this page on MSDN, the work should be wrapping up this month.

Oslo CTP

Next week at PDC, Microsoft will let us see the first beta of Oslo. I don't know if the beta will be made available only to PDC attendees with a CTP to follow thereafter (kinda like they did with .NET way back in the day) or if the bits will be broadly available from the outset. If I find out more specifics, I'll update this post.

I'm sure there are other noteworthy, WCF-related releases coming soon. If you're aware of any, please post a comment.

This week I need to do something relatively simple that should have taken no time but ended up taking the better part of a morning: I needed to write an XSLT template that transformed a node value using a regular expression. I learned that XSLT 2 supports regular expressions; however, there is no support for XSLT 2 in .NET 3.5. So, I added an extension function to my template that the XPath engine could use to apply the regular expression substitution. Using this custom function required me to qualify it with a namespace prefix. This introduced a problem because I was creating the template dynamically at run-time using LINQ to XML. This technology tries to hide all namespace-related tasks from you (which is helpful in some applications), so I struggled to find a way to add the namespace and the corresponding prefix to the XDocument that I was building up in memory. Eventually, I ended up with something along these lines:

    1 class Program

    2 {

    3     static void Main()

    4     {

    5         var outputXml = new StringBuilder();

    6         var inputXml = @"<r><phoneNumber>555-555-5555</phoneNumber><o>Foo</o></r>";          

    7         var transform = new XslCompiledTransform();

    8         var templates = GetTemplates();

    9         var stylesheet =                                                                  

   10             new XDocument(new XElement(xsltNs + "stylesheet",

   11                 new XAttribute("version", "1.0"),

   12                 new XAttribute(XNamespace.Xmlns + extNsPrefix, extNs),                      

   13                 templates));


   15         using (var reader = stylesheet.CreateReader())

   16             transform.Load(reader);


   18         using (var reader = XmlReader.Create(new StringReader(inputXml)))

   19         using (var writer = XmlWriter.Create(outputXml))

   20         {

   21             var arguments = new XsltArgumentList();


   23             arguments.AddExtensionObject(extNs.ToString(), new XPathExtensions());          

   24             transform.Transform(reader, arguments, writer);                                  

   25         }


   27         Trace.WriteLine(outputXml);

   28     }


   30     private static IEnumerable<XElement> GetTemplates()

   31     {

   32         var templates = new List<XElement>();

   33         var pattern = "\\d";

   34         var replacement = "X";

   35         var matchValue = "//phoneNumber/text()";


   37         templates.Add(XElement.Parse(

   38             @"<template match='@*|node()' xmlns='http://www.w3.org/1999/XSL/Transform'>

   39               <copy>

   40                 <apply-templates select='@*|node()'/>

   41               </copy>

   42             </template>"));

   43         templates.Add(

   44             new XElement(xsltNs + "template",

   45                 new XAttribute("match", matchValue),

   46                 new XElement(xsltNs + "value-of",

   47                     new XAttribute("select", string.Format("{0}:Replace(., '{1}', '{2}')",

   48                         extNsPrefix, pattern, replacement)))));


   50         return templates;

   51     }


   53     private class XPathExtensions

   54     {

   55         public static string Replace(string input, string pattern, string replacement)

   56         {

   57             return Regex.Replace(input, pattern, replacement);

   58         }

   59     }


   61     private static readonly XNamespace xsltNs = "http://www.w3.org/1999/XSL/Transform";

   62     private static readonly XNamespace extNs = "urn:foo";

   63     private const string extNsPrefix = "ext";

   64 }

This code isn't advanced, but there are a few details that can take a bit of time to figure out. So you're able to implement this sort of thing before your morning slips away and you miss your coffeebreak, I'll hightlight them here:

  • The XSLT stylesheet is created dynamically at run-time using LINQ to XML.

  • The subclass, XPathExtensions, has a public, static method called Replace that applies a regex to a given string and returns the result.

  • This class's method is made available to the XSLT engine by associating the namespace, urn:foo, with an instance of my XPathExtensions nested class and passed to the XslCompiledTransform object's Transform methods on lines 21 - 24.

  • The namespace and the prefix (ext) are explicitly added to the XSLT document that is created with LINQ to XML by adding the XAttribute on line 12.

  • This extension is called in the select statement on line 48 by prefixing the XPath function with ext and specifying the name of the public, static method that is in the XPathExtensions object that was passed into the engine via the XsltArgumentList.

(Of all these details, the one that took me the longest to figure out was how to explicitly add a namespace with a given prefix when using LINQ to XML.)

I hope this helps you solve your programming problems, and that you enjoy your coffee break!

What a day for news! Today marked the the passing of the $700B dollar bailout for Wall Street (at least as far as the senate is concerned) and more details about what Microsoft's Oslo initiative will entail, specifically the new Windows application server nicknamed "Dublin". As reported on Microsoft's Web site, Dublin is "a set of enhanced Windows Server capabilities" or, in other words, new roles that you will be able to add to Windows Server. These new features will help with "deployment, configuration, management, and scalability."

With the $700B dollar deal and Dublin stealing all the headlines, you may not have noticed a new piece of info from Amazon out today: their Elastic Compute Cloud, EC2, will support Windows Server this fall! If you don't know what EC2 is, basically, it's a ton of VMs that can be controlled via Web services which Bezos charges you for on an as-use basis. This is really exciting news.

Initially, I imagined that Oslo would provide a way to graphically design Web services (a la WSSF), thus bringing Web service development to the masses in much the same way that Microsoft brought GUI programming to a broader base by lowering the technical bar with Visual Basic. I supposed that the "D" modeling language was needed to represent messages, data contracts, service interfaces, etc. However, it seems that "D" is for data, and will be about modeling business-specific concepts not services. I also had a hunch that Oslo would be launched around the time that Microsoft would be rolling out something akin to EC2. With the research initiative being invested into BizTalk Services and SQL Server Data Services (SSDS), I imagined that news of some virtualization platform like EC2 from Redmond would soon be plastered across RSS readers everywhere. It may very well be, however, with the long delay of Hyper-V Live Migration in Windows Server and the failed acquisition of Yahoo! earlier this year (which would have given Microsoft a bunch of new data centers on which to host this "MS EC2"), it looks like this might not be in the cards for Oslo either.

Because the scope of Oslo may not be as grand as I previously envisioned, this announcement from Amazon is even more intriguing. This means that many innovative, creative individuals and companies can utilize Oslo, Dublin, and EC2 to get a leg up in the marketplace before Microsoft's PaaS offering is rolled out — and it will be rolled out, if not with the initial release of Oslo, then with a subsequent one. Can you imagine: You're in your cube using Visual Studio "10" (or "11" or "12") to design some complicated service in a graphical manner, you click the publish button, it's uploaded to Microsoft's compute cloud, and you have a service that is hosted on a bunch of VMs that are dynamically started and stopped based on demand, paying only for what you use!

So, keep your eye on Norway, Ireland, and the rest of good old Europe, use the bits from PDC to come up with new, innovative service-oriented architectures without limiting yourself to the server machines you can afford, and host them in Amazon's arsenal of Windows Server and Dublin (hopefully) virtual machines.