Anything related to the .NET framework
06 Jan 2009

Tripping over logs: A story of Unity - Part 1

Welcome to the first part in my series on using Unity, which is a Dependency Injection or Inversion of Control tool/framework/thing from the p&p group. It’s a big and (over) complicated topic so if what I have just said means nothing, fear not for it will all make sense soon. I have broken this into a series to make it easier to digest. What I am going to do is look at a practical approach to using Unity, I will not be going into DI or IoC those topics as people smarter than me have done a much better job (part 6 has links). If you want the theory look somewhere else, if you want to get running with Unity this is for you.

This is a multi-part series as such here is the series guide in case you are looking for the rest of the series:

The Problem

A few years back I was developing an enterprise solution for a bank which integrated MSCRM into a number of systems, and so I needed to make sure I did logging (that’s what enterprise apps have, right?). Initially I had a simple “write to text file” logging system, which worked fine on my machine (if you can see what the problem is in that sentence you been developing too long). That is until we started testing and we ramped up the usage and I hit concurrency and locking issues. That prompted me to rip out all the logging and use the logging within System.Diagnostics.Trace as it seemed like it would work better, and it did for a long time. At some point I was pulled back to project (I left it for a long time) and needed to change the logging to use the p&p Enterprise Library logging. It was only at this point did I stop calling the System.Diagnostics.Trace code directly in each place for logging and start calling a custom method. This is what it sort of looked liked, excepted I had lots more parameters on the logging (level of message, source component etc…) and we logged every time something changed not just entry and exit:

public void DoSomething()
{
    LogThis("Do Something Start");
     ...
    LogThis("Do Something End");
}

When I changed it out I did some number crunching and realised that 40% of all the lines of code was these calls to logging! I remember thinking that was well done and how proud I was of my logging skills. Now days I look back at that as ridiculous. Not the fact I did logging, just how much code was spent on it and how tightly bound it was. So how could I do it better now days, well through a principal called Dependency Injection and an implementation of it called Unity (from the p&p team in their Enterprise Library).

Note: I am using the example of logging as the problem to solve, but really DI can be used for anything.

I must admit that Unity though is anything but simple, it is one of the hardest things I have had to learn in a while. What made it tough was understanding the documentation which enables you to learn Unity, but you need to understand Unity first to understand the documentation, talk about catch 22. It’s odd because the other blocks in EntLib are easy to get up and running but with Unity the samples are confusing and the help more so. In the end, some search kung fu + luck + patience seems to be what is needed to get through it. That said I feel a simple series of blog posts may help others out, which is what this is ;)

Starting Block

A special note is that this series is HEAVY with code and makes the articles look long, but actually I am repeating the code each time so you can compare the changes easily.

So lets start with a simple application as our base which will make it clear what we have and what we will change to get Unity working. As those who attend any of my sessions know I love console apps so I’ve whipped up a simple on that writes to the screen. The code looks like this:

using System;
 
namespace BigSystem
{
    class Program
    {
        static void DoSomething(string Username)
        {
            Console.WriteLine("Hello {0}", Username);
        }
 
        static void Main(string[] args)
        {
            DoSomething("Robert");
            Console.ReadKey();
        }
    }
}

And the solution like this (note the references - super clean):

image

Now using my “Enterprise Skills” from earlier, we add some logging like so:

static void LogThis(string Message)
{
    System.Diagnostics.Debug.WriteLine(String.Format("{0}: {1}", DateTime.Now, Message));
}
 
static void DoSomething(string Username)
{
    LogThis("DoSomething Called with Username Parameter set to:" + Username);
    Console.WriteLine("Hello {0}", Username);
    LogThis("DoSomething Completed");
}
 
static void Main(string[] args)
{
    LogThis("Application started");
    DoSomething("Robert");
    Console.ReadKey();
    LogThis("Application Completed");
}

Right, so that code is not bad. It works which makes the (imaginary) customer is happy. This code is not good either, because if we want to change anything it’s a big issue, likely “solved” by a find and replace. A better route would be to take the logging out and define it in a separate class that inherits from an interface. This means when we create the class we can change that one place and all the code is effected.  So that would look like this:

class Program
{
    static ILogger logger = new DebugLogger();
 
    static void DoSomething(string Username)
    {
        logger.LogThis("DoSomething Called with Username Parameter set to:" + Username);
        Console.WriteLine("Hello {0}", Username);
        logger.LogThis("DoSomething Completed");
    }
 
    static void Main(string[] args)
    {
        logger.LogThis("Application started");
        DoSomething("Robert");
        Console.ReadKey();
        logger.LogThis("Application Completed");
    }
}
 
public interface ILogger
{
    void LogThis(string Message);
}
 
public class DebugLogger : ILogger
{
    public void LogThis(string Message)
    {
        System.Diagnostics.Debug.WriteLine(String.Format("{0}: {1}", DateTime.Now, Message));
    }
}

Note the constructor for logger and the interface and class below. The reason this is powerful is if I wanted to change this to output to the console I could spin up a new class, and just change the constructor for logger, as in below:

class Program
{
    static ILogger logger = new ConsoleLogger();
 
    static void DoSomething(string Username)
    {
        logger.LogThis("DoSomething Called with Username Parameter set to:" + Username);
        Console.WriteLine("Hello {0}", Username);
        logger.LogThis("DoSomething Completed");
    }
 
    static void Main(string[] args)
    {
        logger.LogThis("Application started");
        DoSomething("Robert");
        Console.ReadKey();
        logger.LogThis("Application Completed");
    }
}
 
public interface ILogger
{
    void LogThis(string Message);
}
 
public class DebugLogger : ILogger
{
    public void LogThis(string Message)
    {
        System.Diagnostics.Debug.WriteLine(String.Format("{0}: {1}", DateTime.Now, Message));
    }
}
 
public class ConsoleLogger : ILogger
{
    public void LogThis(string Message)
    {
        Console.WriteLine("{0}: {1}", DateTime.Now, Message);
    }
}

This is great, except to change the type of logger I need to change the code. Wouldn’t it be better to

  1. Be able to specify in a configuration file what should be used?
  2. Instead of instantiating a logger (like with the constructor), I could have a bag where code could reach into and ask for a logger?

This is what Unity provides at a basic level and we will implement in the next post, but trust me it goes much further and becomes much more powerful.

19 Dec 2008

.NET 3.5 SP 1 GDR is Out

The .NET 3.5 SP 1 GDR (General Distribution Release), basically the patch for the bugs in .NET 3.5 SP 1, is now out! Details of the patch are/will be available at KB959209

17 Dec 2008

The Cat(.NET) is out of the bag

Those who know me as a developer, and those who attended the boot camp I ran for the last two weeks, have an idea that I  like analysis tools (in the boot camp I present a session on my favorite 7 tools, 3 of them are analysis tools). That said I have been following a team at Microsoft for ages who have been building a tool called CAT.NET, which is another static analysis tool. This one focuses on analyzing code for security issues. I looks good, but it really doesn’t blow me away.

What’s the first thing you do when you get a new tool? Run it against your own code and then the Microsoft code ;) No where could I get this code to ever give me a security issue – which is either a good or bad thing. When it’s done it provides a report in HTML and XML which is boring as hell:

Clipboard02

The report on System.Web.Services.dll

To see a problem I looked at the rules, which are defined in XML, to actually force an issue.  I decided to take a stab at the process command execution rule, with the amazingly complex code like this:

image

This produced a nice report like this:

image

That said during one of my tests with it I did get a different result, a nice crash when checking System.Data.dll

image

StackOverflowException in the security application.

But none of the above is the reason why it does not blow me away, it doesn’t blow me away because it’s another tool that is actually not needed. Looking at the files and code (thanks to reflector) this could have easily been built into FXCop and made that a better solution overall. It is in beta still, so hopefully this is an indication of a tool that has been grown in the dark and now that the light of the public the team will start to understand real world scenarios.

image

If you needed an indication of the beta status of this tool, check out how many NotImplementedExceptions are in the code still :(

You can download the bits here: 32 Bit or 64 Bit

08 Dec 2008

Three tweaks and a tip for getting WCF to work with Silverlight

If you create a standard WCF service it does not work with Silverlight, it needs a few tweaks to get it to work. First is that Silverlight only supports connecting to a basicHTTP service and not a wsHTTP service, so you need to enable a second service or change your primary to basicHTTP, you can find out the reasons why by reading: Accessing SOAP Services

Second you need to attribute your class with: [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]. For example:

   1: namespace SilverlightApplication1Web
   2: {
   3:     [ServiceContract(Namespace = "")]
   4:     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
   5:     public class CustomerService
   6:     {
   7:         [OperationContract]
   8:         public int CountUsers()
   9:         {
  10:             return 2;
  11:         }

The third tweak is the biggest: Normally your WCF service and Silverlight application do not sit in the web application (either in Visual Studio or on the server) and due to the security put in place to prevent cross site attacks your service calls will fail. Obviously creating a web application with everything in is a solution, but if you haven’t you must add a security file to the WCF service web application. There are two files you can create in the root of your website, the first one is a crossdomain.xml. Crossdomain.xml is a format created by Macromedia. I do not recommend this one for Silverlight scenarios as Silverlight only supports a subset of the functionality but if you need to deal with Flash based clients then this is the route you must follow. Your other option is the Microsoft way, which is to create a file called clientaccesspolicy.xml. A clientaccesspolicy.xml to allow all methods, from all clients, to all URLS looks like this:

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

That is not normally what you want to do in production because of the security issues, but for early development it can help. Note: You can use BOTH files to get Silverlight and Flash clients to have the best experience. More details on both those files can be found at: http://msdn.microsoft.com/en-us/library/cc197955(VS.95).aspx

The last tip is the usage of WCF in Silverlight. It is still WCF so you are required to open and close your service connection. However since Silverlight makes web calls using async methods you need to chain up commands using events. i.e. you would create a event handler for when the connection is open and then open the connection. In the open event handler you would do the work, and once that completes you close the connection.

 

Clipboard01

Chaining event handlers for getting Silverlight + WCF in code and program flow. 

Special thanks to Herman (the delegator) and Willy for prompting me to write this post… especially since Herman won’t blog on this.

28 Nov 2008

My first love came back - and she now drives a Ferrari!

Seriously I am grinning like mad this morning, because my first development love has returned: DELPHI! Many years ago it stopped being a good choice for work, if you could get any work, but that changed recently with the announcement of Delphi Prism. DP makes use of Visual Studio to host the Delphi language, that’s right all the power and beauty of VS! The language has been enhanced to support all the cool things that C# can do (LINQ, Silverlight)! So that is very cool, and using Oxygene Compiler you can target .NET, Win32, Mono (so you can run on Linux) with full GUI support for GTK#, and Cocoa for OSX (Tiger and Leopard)!

That’s right one fully featured language targeting 4 different platforms (Old Windows (Win32); New Windows (.NET); Linux; Mac OSX) right from within Visual Studio!

In reality though it has just been press announcements and demo’s at PDC so nothing for me to truly base this on… but hopefully soon.

InfoQ has a nice into article on the subject too: http://www.infoq.com/news/2008/11/Delphi-Prism

25 Nov 2008

Deciding what UI technology to use?

Herman, who you may know as “The man without a blog” or “The Delegator” or the guy who works over the partition from me, has released a poster detailing UI interface choices there are and what are the factors involved with choosing that. Very good to have if you trying to decide between Silverlight, Flash, Flex, ASP.NET, WinForms, WPF etc…

Download details available on Willy’s blog.

2

A picture of the poster… it’s much bigger when you download it.

Update 10 Jan 2011 - The link to Willy-Peter's blog no longer works.
05 Sep 2008

Random Tool Musings

This is a little different from my regular scheduled blog posting in that it's kind of a +1 post (I promise I am not becoming one of those blogs) because there is a bunch of things I wanted to speak about but they each don't need their own post.
First off is pptFlex which is an add-on for PowerPoint which provides a DeepZoom (those at the TechEd closing know what I mean) like experience with your slide deck. It's an Office Lab add-in so a prototype that will never see the main stream. After a touch of configuration (select  backdrop, transition between slides, configuring sections) it appears to generate an XPS render of the slides with cool transitions but as XPS doesn't support animation that is the first (and biggest) loss in functionality when compared to normal PowerPoiunt. At the end of the day I doubt it will be shipped, but I think we may see these sort of transitions appearing in Office "13".
In my upcoming post on shrinking a VHD, I briefly mention that I reclaimed the disk space by emptying the SQL log file. That is a bad idea for most systems for many a reason beyond my non SQL guru mind, but if you are interested in how to do it anyway see the following article which is what I used my guidance: http://madhuottapalam.blogspot.com/2008/05/faq-how-to-truncate-and-shrink.html
Lastly there have been updates to some of my favorite tools, first from Microsoft namely StyleCop and FxCop which both are everyone. That’s very positive news especially since FxCop has been a bit stagnent but the news about another favorite tool, Reflector being taken over by RedGate (see here) does worry me. I do not think they will kill it or kill a free version but I am worried about two versions coming out (pay and free) with pay being all the features and new stuff and free being crippled or not getting enhancements. Only time will tell...
09 Jun 2008

The Zen of Hosting: Part 3 - Hosted Messaging and Collaboration Overview

In part 2 I wrote about this technology called Hosted Messaging and Collaboration (HMC) and that it is delivered as a guidance package, but what is a guidance package? Well for HMC it is a package with a number of components in it. First off is that there is a central management and configuration system. This system is made up of engine, based on a COM+ object (?!), a set of web services, and a number of MSI files which get deployed to various other servers and handle interaction with those servers.

Next is web based management console for the system, however the web based management console is a prototype and comes with no official support from Microsoft. The advantage of the web based management console is all the source code is provided so you can either use it as a base for building your own or for samples to build integration into your existing management system. As a side note there are a number of third party management consoles out there, which I would highly recommend looking into if you are reading this for building your own system.

The last part of the package is documents, documents and more documents. The SDK provided goes over all the systems in the engine and how to expand it and is really useful (I’ll cover why in part 5). However more useful than that is the deployment guide which takes you step by step in how to deploy the solution for an sample company. The only piece of documentation I would add to those is the unofficial consolidated deployment guide which is additive to the actual guide but provides details on how to do HMC without the 20+ needed servers you normally need and only use 8!

To deploy HMC you really just step through the guide however it will take a number of days and a lot of diverse skills to get it right (expect to need a .Net developer, an AD expert, an Exchange expert and someone with clustering experience would be bare minimum skills) and you should have a working system which is the same as all others.

Expect severe punishment though for not following the guide word for word. For example we initially tried to have a pure Windows 2008 Server x64 environment despite what the guide said and we were punished. Unfortunately all that work had to be scrapped as HMC did not not work. In the end the call to change the servers to match what the guide said, enabled a semi-normal sleep life again.

Another example of not following the guide to the is that HMC is built on .Net 2.0 RTM, however a fix included in 2.0 SP1 actually breaks HMC. That means you cannot install .Net 3.0 or 3.5 on any key HMC server as they will install the service pack for you and bork HMC :( Patches do exist for this bug but it may be worthwhile to wait for the upcoming 4.5 release of HMC if you are thinking about deploying this anytime soon.

Tags: 

Pages