hypnocode delusions from a sleepless mind…

5Dec/11Off

Convention Based Settings with Unity

Over the summer, I read a post by Chad Myers discussing easy configuration in FubuCore. At the time I thought this was a really nice idea, but forgot about it as I was more into an upcoming vacation to Iceland. Then last week I was reminded of Chad's post when I came across Josh Bush's blog post taking the easy configuration idea and implementing it with Autofac. If you want further details on this easy configuration idea I'll let you go read either Chad's or Josh's post, but the overall view goes something like this.

Many applications take dependencies on external configuration settings, either from a config file, database or some other source. You end up littering your code with ConfigurationManager calls all over or wrapping everything behind a class to hide the details. Instead, what if you injected your classes with a simple POCO object and your container of choice would populate the properties of your object when it gets resolved.

Josh's implementation of this idea was for Autofac. If you haven't been able to tell from some of my prior posts, I use Unity at work, so I thought it would be nice to see if I could do something similar for it. I will admit, the core of my implementation comes from Josh's code base. I didn't see any need to reinvent the wheel on it and instead spend my time trying to figure out how to wire this up in Unity.

I'll be honest, I haven't done much more with Unity other then the necessary registering and resolving of objects, so I dug around a bit to figure out the best way to go about this. I finally decided that creating an extension of the Unity container was the easiest way to do it. Here is the extension that I came up with.

public class SettingsProviderExtension : UnityContainerExtension
{
   protected override void Initialize()
   {
      Container.RegisterType<ISettingsFactory, SettingsFactory>("DefaultSettingsFactory", new ContainerControlledLifetimeManager());
      Container.RegisterType<IEnumerable<ISettingsProvider>, ISettingsProvider[]>();

      Context.Strategies.Add(new BuildUpSettingsStrategy(), UnityBuildStage.Initialization);
   }
}

internal class BuildUpSettingsStrategy : BuilderStrategy
{
   public override void PreBuildUp(IBuilderContext context)
   {
      if (context.Existing != null
            && context.Existing.GetType().IsClass 
            && context.Existing.GetType().Name.EndsWith("Settings")) {
         var settingsFactory = GetSettingsFactory(context);
         settingsFactory.BuildUp(context.Existing);
      }
   }

   private static ISettingsFactory GetSettingsFactory(IBuilderContext context)
   {
      var factory = context.NewBuildUp("DefaultSettingsFactory");
      if (factory == null) {
         throw new InvalidOperationException("No instance of ISettingsFactory available.");
      }

      return factory;
   }
}

The extension starts by registering a SettingsFactory which is used to look through a collection of ISettingsProvider types (the implementation of these types comes straight from Josh's code base). I have no idea if this is okay to do inside of an extension or not, but it seems to work. You can always move it out and register it on your own if you wish, especially if you change the implementation of it up. Then I add a new BuildUpSettingsStrategy to Unity that will run at the initialization stage. This stage occurs after the object being resolved has been created. The new strategy looks at the class being resolved, checks to see if it is an actual class type and if the type name ends with "Settings", and if it matches all of these it will set the properties of the class using the SettingsFactory we registered in the container.

To use this, you just need to setup your POCO settings class and register this extension with the container.

public class WorkerSettings
{
   public string Server { get; set; }
   public int Port { get; set; }
}

public class Worker
{
   private readonly WorkerSettings _settings;

   public Worker(WorkerSettings settings)
   {
      _settings = settings;
   }

   public void DoWork()
   {
      Console.WriteLine("Connecting to {0}:{1}", _settings.Server, _settings.Port);
   }
}

class Program
{
   static void Main(string[] args)
   {
      IUnityContainer container = new UnityContainer();
      container
         .AddNewExtension<SettingsProviderExtension>()
         .RegisterType<ISettingsProvider, AppSettingsProvider>("AppSettingsProvider", new ContainerControlledLifetimeManager());

      container.Resolve<Worker>().DoWork();
   }
}

This will pull configuration information from the app.config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
      <add key="WorkerSettings.Server" value="example.com" />
      <add key="WorkerSettings.Port" value="81" />
   </appSettings>
</configuration>

I put this entire project up on github (mainly as an excuse to play with git, I know, I'm late to the game) along with a trivial demo application so if you want to take a look at the source, it's up there. Next, maybe I'll look at putting together a NuGet package as an excuse for creating my first NuGet package.

Filed under: dev, unity No Comments
10Aug/11Off

XDT Transformations and XML Namespaces Addendum

In this post I outlined a way to get XDT transformations to work when a node has a namespace assigned to it. I've had hit and miss success using this method and found a more reliable solution here. In short, add the namespace to your transformation file and use it when "finding" the target node. Something along the lines of:

<configuration
      xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"
      xmlns:ioc="http://schemas.microsoft.com/practices/2010/unity">
   <ioc:unity xdt:Transform="Remove" />
</configuration>

This seems to be a more reliable method.

Filed under: dev No Comments
11Feb/11Off

WPF RadioButtonList With Access Key On Items

I am not going to rehash how to go about creating a RadioButtonList control in WPF. If you need that you can google and find several links such as these that discuss the issue.

One issue that each of these has is if you need to specify an access key value for the radio buttons in the list, then the control breaks down. When using the access key to select a radio button, the previously selected radio button was not being deselected. Many of the examples out there show how to create the RadioButtonList using a style defined for a ListBox and explicitly setting the ItemContainerStyle to something similar to this

<Setter Property="ItemContainerStyle">
   <Setter.Value>
      <Style TargetType="{x:Type ListBoxItem}" >
         <Setter Property="Margin" Value="2" />
         <Setter Property="Template">
            <Setter.Value>
               <ControlTemplate TargetType="{x:Type ListBoxItem}">
                  <Border BorderThickness="0" Background="Transparent">
                     <RadioButton Focusable="False" IsHitTestVisible="False"
                                  IsChecked="{TemplateBinding IsSelected}">
                        <ContentPresenter />
                     </RadioButton>
                  </Border>
               </ControlTemplate>
            </Setter.Value>
         </Setter>
      </Style>
   </Setter.Value>
</Setter>

This issue is when using the access key defined on the radio button label, it doesn't do anything with the ListBox control that you are using as a wrapper around the whole thing. The easiest method I found was to define a GroupName on the RadioButton control.

                     <RadioButton Focusable="True" FocusVisualStyle="{x:Null}" IsHitTestVisible="False"
                                  GroupName="{Binding Path=Name, RelativeSource={RelativeSource AncestorType={x:Type local:RadioButtonList}}}" 
                                  IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}, Mode=TwoWay}">
                        <ContentPresenter />
                     </RadioButton>

As you can see from my example, I bound the GroupName property to the Name property of my overall control. This means I have to be sure to name my parent ListBox control so that thing will work which isn't a problem for me in my scenarios.

You will also notice that I changed the binding express for the IsChecked property. I noticed that the IsSelected property of the ListBoxItem wasn't changing when using the TemplateBinding option. Apparently Mode=TwoWay isn't an option with TemplateBinding, so I switched it over to a regular Binding and everything seems to be working fine.

With these changes, I now have a RadioButtonList that works when using access keys to select your value.

Filed under: wpf No Comments
21Jan/11Off

WPF ListView Styling Based On Other Rows

Disclaimer: There may be a better way to do this, but this is a way I found that worked out for me and I thought I'd post in case anyone else was trying to do this as well.

I was displaying data in a ListView and I was wanting to style a column in the row based on values found in previous rows. I was looking for something like the image to the right where the first row with a date was normal, but each subsequent row displayed the date in a faded color.

It wasn't jumping out at me on how to do this so I did what every good programmer does and hit up Google for an answer. Unfortunately I couldn't come up with a good search query to find what I was looking for (it had to be me, Google can find anything). Eventually I did stumble upon a post showing how to use a converter with the ListViewItem for something completely unrelated which gave me an idea for a starting point to do what I wanted (sorry, I didn't save the link).

The key was doing this with a IMultiValueConverter which takes an array of items to use to in the conversion process. The following is the code for the converter that I am using.

public class DateColorConverter : IMultiValueConverter
{
   private readonly SolidColorBrush _newDateBrush = new SolidColorBrush(Colors.Black);
   private readonly SolidColorBrush _sameDateBrush = new SolidColorBrush(Colors.LightGray);

   public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
   {
      ListViewItem item = values[0] as ListViewItem;
      ListView list = values[1] as ListView;

      int index = list.Items.IndexOf(item.Content);
      if (index == 0) {
         return _newDateBrush;
      }

      DateTime rowDate = (DateTime)((DataRowView)item.Content).Row[0];
      DateTime previousDate = (DateTime)((DataRowView)list.Items[index - 1]).Row[0];

      return (rowDate == previousDate) ? _sameDateBrush : _newDateBrush;
   }

   public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
   {
      throw new NotImplementedException();
   }
}

First, I get the objects I passed in to the Convert method. I'll show the XAML for this a bit further on, but the ListViewItem is the row being display and the ListView is obviously the ListView displaying the objects. Once I have those items and seeing that I'm not on the first row of the ListView, I grab the date value from the underlying data. This will depend on your underlying data type you are binding to the ListView and in this instance I have bound it to a DataView. Since I know the index position of the current item, I can grab the previous row from the ListView to get the date value. Then just compare and return the appropriate value.

The XAML for setting up the binding on this column looks like the following.

<GridViewColumn Header="Converted" Width="80">
   <GridViewColumn.CellTemplate>
      <DataTemplate>
         <TextBlock Text="{Binding converted, StringFormat={}{0:d}}">
            <TextBlock.Foreground>
               <MultiBinding Converter="{StaticResource DateColorConverter}">
                  <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}" />
                  <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ListView}}" />
               </MultiBinding>
            </TextBlock.Foreground>
         </TextBlock>
      </DataTemplate>
   </GridViewColumn.CellTemplate>
</GridViewColumn>

That's all there was to it.

Filed under: general, wpf No Comments
13Sep/10Off

Forwarding Requests On To Another EndPoint In Agatha

First off, if you don't know what Agatha is, it is an open source library implementing the Request/Response service layer on top of WCF. If you want to know more about it, I suggest you head over to the project's site and read up on the series of blog posts by Davy Brion that discusses the library and its usage.

When I found out about this library, it was exactly what I was looking for. Since the early days of .NET with ASMX web services and remoting, I've been doing something similar except I was passing messages around in XML form. I was never fully happy with that solution, but with time constraints that I had to work with, I could never spend the time to come up with something better. The solution has worked well enough in the couple of projects that it was used in and we've seen no reason to upgrade.

I'm now working on upgrading a project and adding a bunch of new functionality. We are moving over to WCF for our communications but I didn't want to go the same route with our messaging if I could help it. That is about when the posts regarding Agatha started showing up in Google Reader and I knew I had my answer.

The one wrinkle that we have is that I'm forced into a 3 physical tier architecture. The web server that would be receiving the requests has no access to anything that can complete the request and basically just forwards the call onto the app servers running in the background. Basically the web server ends up acting as both the client and the server. I'm not going to get into the debate on whether this architecture is good, bad, overkill as the decision for it was never in my hands to make. It is what I have to work with though.

This is where Agatha (and WCF) really helped out. In my old kludgy method, the sitting on the web server was nothing but glue, taking the ASMX call and forwarding it on to the app servers over the remoting service then doing the same with the replies going in the opposite directions. With Agatha, instead of this glue code to do the work, all I really need to do is implement a custom IRequestProcessor that forwards on the request to the app server.

public class PassThruRequestProcessor : Disposable, IRequestProcessor
{
   private readonly ServiceLayerConfiguration serviceLayerConfiguration;
   private readonly ICacheManager cacheManager;

   protected override void DisposeManagedResources() { }

   public PassThruRequestProcessor(
                  ServiceLayerConfiguration serviceLayerConfiguration, 
                  ICacheManager cacheManager)
   {
      this.serviceLayerConfiguration = serviceLayerConfiguration;
      this.cacheManager = cacheManager;
   }

   protected virtual void BeforeProcessing(IEnumerable<Request> requests) { }

   protected virtual void AfterProcessing(
                   IEnumerable<Request> requests, 
                   IEnumerable<Response> responses) { }

   public Response[] Process(params Request[] requests)
   {
      if (requests == null) return null;
      var responses = new List<Response>(requests.Length);

      BeforeProcessing(requests);

      try {
         var requestDispatcher = IoC.Container.Resolve<IRequestDispatcher>();
         requestDispatcher.Add(requests);

         responses.AddRange(requestDispatcher.Responses);
      }
      catch (Exception e) {
         // handle the error
      }

      AfterProcessing(requests, responses);

      return responses.ToArray();
   }

   public void ProcessOneWayRequests(params OneWayRequest[] requests)
   {
      if (requests == null) return;

      BeforeProcessing(requests);

      try {
         var requestDispatcher = IoC.Container.Resolve<IRequestDispatcher>();
         requestDispatcher.Send(requests);
      }
      catch (Exception e) {
         // handle the error
      }

      AfterProcessing(requests, null);
   }
}

You'll have to remember to configure Agatha on the web server for both client and server configurations and on the service layer configuration you assign the RequestProcessorImplementation property to your custom IRequestProcessor implementation before initializing it.

var config = new ServiceLayerConfiguration();
config.RequestProcessorImplementation = typeof(PassThruRequestProcessor);
config.Initialize();

And that is it. Now I have my request from the client, passing through the web server to the app server and back and not much work was needed in order to do accomplish it.

Filed under: dev, wcf No Comments
10Sep/10Off

XDT Transformations and XML Namespaces

ASP.NET 4.0 added XDT Transformations for the web.config file which can help have the config file setup for your dev environment but transform it for staging or production environments. I think this is a nice step, however, it would have been even better if it could have been applied to project types other than ASP.NET projects. Luckily Denis Gladkikh has packaged things up into a command line tool that you can use in your builds. His post about the Config TransformationTool (ctt) came along at just the right time as I was putting together the production build of my current project.

However, one thing that is missing from the documentation about using the XDT Trasnformations is what to do if the element in your config file has a namespace. If you read my prior post on configuring Unity, then you might realize we may have some unity configurations in our dev environment we may not want to push to a production build. So you might find something similar to the following in our app.config files.

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
   <container>
      ...
   </container>
</unity>

When using the XDT Transformations the following will not remove the <unity /> node because of the namespace on the node.

<unity xdt:Transform="Remove" />

I searched the documentation and Google for a way to remove a node with a namespace on it. Finally I decided to stop and think for myself and realized that maybe using the XPath option with the Locator attribute might be the answer. So I decided to try the following:

<unity
   xdt:Transform="Remove"
   xdt:Locator="XPath(/configuration/*[namespace-uri()='http://schemas...'])"
/>

And sure enough, the node was now being removed in our production builds. You may have to monkey around with the xpath expression to get it just right, but then again my xpath-fu is not as strong as some peoples.

While putting this post together, I just noticed that and update was pushed for the cct that added the ability to specify parameters with the transformations. Not sure it is something I'll need, but it is nice to have options.

Filed under: dev No Comments
7Sep/10Off

Unity Configuration Tricks

Okay, not so much tricks, but just a single trick. I'm not going to get into the whole debate on which dependency injection container is better. I've played around with several in the past. My employer has standardized on using Unity for deployable projects (they go with the Microsoft tool sets and I'm in no position to change that), so this is the container I know best.

One of the things we do is configure Unity at run-time, either directly or through auto registration depending on the size of the project. However, during development, I like to take advantage of the face that if you register two classes to the same interface, Unity uses a last one registered wins strategry. So something like:

container.RegisterType<IService, ServiceOneImpl>();
container.RegisterType<IService, ServiceTwoImpl>();

would always return to you the ServiceTwoImpl instance what you ask the container for IService. Now, doing this in code is not ideal. Instead I register everything in code like normal and then once setup, I take advantage of the registration through the config file:

container.RegisterType<IService, ProductionServiceImpl>();

UnityConfigurationSection section =
   (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
if ((section != null) && (section.Containers.Count > 0)) {
   section.Configure(container);
}

Now I can override production values at runtime by specifying them within the config file. This has helped by letting me and others work on new things within the production application without touching the main code for the application. It has also helped a time or two to figure out a few "works fine on every machine but this one" scenarios as we can toss in a specially instrumented version of a class and see more of what is going on.

Its no substitute for TDD, but has provided us with a helpful way of doing things more than once in the past.

If you are worried about releasing this in a production application, then you can always through an #ifdef around the config file loading and only do so on DEBUG builds of your code.

Filed under: dev, unity No Comments