Attaching the Debugger only in Debug

by Alex Meyer-Gleaves 16 June 2010 - 1:41 AM

I noticed an article on the Infinite Codex blog that demonstrates how to debug CLR Stored Procedures. The example uses a #if preprocessor directive to compile the debugging code only if the DEBUG symbol is defined. Personally, I find using the #if directive makes your code look rather ugly, and accidentally including code inside the directive that you did not intend to becomes a real possibility. My preferred solution is to use the ConditionalAttribute to refactor such code out into a separate method.

Applying ConditionalAttribute to a method indicates to compilers that a call to the method should not be compiled into Microsoft intermediate language (MSIL) unless the conditional compilation symbol that is associated withConditionalAttribute is defined.

Using this approach you can create a helper class that includes methods that should only be called when the DEBUG symbol is defined. When you compile with the RELEASE symbol defined all calls to the methods will simply be excluded from the generated MSIL.

public static class Debugging
{
    [Conditional("DEBUG")]
    public static void Break()
    {
        Debugger.Break();
    }
}

If you run the code below in Debug mode with the debugger attached, a breakpoint will occur immediately after the first Console.WriteLine method call.

class Program
{
    static void Main()
    {
        Console.WriteLine("Before the Debugging.Break() method.");
        Debugging.Break();
        Console.WriteLine("After the Debugging.Break() method.");
        Console.ReadLine();
    }
}

When the debugger is not attached and you compiled in Debug mode, the Visual Studio Just-In-Time Debugger dialog is presented for you to selected a debugger to attach with.

Visual Studio Just-In-Time Debugger Dialog

If you run in Release mode no breakpoint will be hit when the debugger is attached, and the Visual Studio Just-In-Time Debugger dialog will not be presented when you run without the debugger attached.

Tags: ,

Categories: Development Tools | Microsoft .NET

Fault Contract support in WSCF.blue

by Alex Meyer-Gleaves 31 May 2010 - 12:23 AM

Adding support for fault contracts to WSCF.blue has been on my TODO list for quite a while now. It was left behind when the port to WCF was done because ASMX did not have proper support for fault contracts so it was never actually part of WSCF.classic. Back in the old ASMX days you had to manually set the Detail property in the SoapException yourself and then add the fault details to the WSDL by hand.

In WCF your fault messages are declared on your operation using the FaultContractAttribute. When using WSCF.blue you could manually add the fault details to your WSDL and the appropriate FaultContractAttribute would be added to the generated service interface code. The problem was that if you edited your WSDL in the wizard the manually added fault details would be lost. Introducing a manual step like that into your process is something that we all want to avoid. Well, you no longer need to worry about that, because I have now added support for fault contracts to WSCF.blue.

Defining fault messages in your WSDL can be a little different to defining your input and output messages. For example, you can have multiple fault messages for a single operation and the same fault message is often reused for different operations. I decided that the message mapping page of the WSDL Wizard would be a reasonable place to put the configuration for your fault contract.

When you select an operation in the tree control a link label is displayed in the properties pane. Clicking the link will add a new fault message to the operation.

Operation Properties

When you select the fault message in the tree control you can then select a type from your schema to be used as the message body. You must provide a name for the message and that name must be unique to the operation. It does not have to be unique to the entire contract though. This means that you can reuse the same message name for a different operation and only a single message will be added to the WSDL. There is also a link label that allows you to remove the fault message if required.

Fault Message Properties

Lets use the fault message being configured in the screen capture above as an example of how this fits together in regards to the XSD and WSDL. The type for the fault in the XSD is called customFault and is an explicitly named complexType.

<xs:complexType name="customFault">
  <xs:sequence>
    <xs:element name="errorCode" type="xs:string"/>
    <xs:element name="message" type="xs:string"/>
    <xs:element maxOccurs="unbounded" minOccurs="0" name="messages" type="xs:string" />
  </xs:sequence>
</xs:complexType>

The message is then defined as an element with the type set to the customFault type. Do not create your fault type as an anonymous type definition directly under the element for the message. Doing so will result in an error about a missing data type during code generation.

<xs:element name="customFault" type="import:customFault" />

When the type and message schemas are run through the WSDL Wizard, and the fault message is added as shown in the screen capture above, the resulting WSDL will have a new message defined as follows.

<message name="customFaultMessage">
  <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" />
  <part name="fault" element="import0:customFault" />
</message>

The portType will then have the fault defined for the operation.

<operation name="getRestaurants">
  <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" />
  <input message="tns:getRestaurantsIn" />
  <output message="tns:getRestaurantsOut" />
  <fault name="customFaultMessage" message="tns:customFaultMessage" />
</operation>

The binding will also have the fault defined for the matching operation.

<operation name="getRestaurants">
  <soap:operation soapAction="http://www.thinktecture.com:getRestaurantsIn" style="document" />
  <input>
    <soap:body use="literal" />
  </input>
  <output>
    <soap:body use="literal" />
  </output>
  <fault name="customFaultMessage">
    <soap:fault use="literal" name="customFaultMessage" namespace="" />
  </fault>
</operation>

Now when you generate your service code a FaultContractAttribute will be applied to the method on your service interface that declares the operation. Note that the FaultContractAttribute specifies customFault as the type to be used for the message body.

[System.ServiceModel.OperationContractAttribute(Action="http://www.foo.com/:getRestaurantsIn", ReplyAction="*")]
[System.ServiceModel.FaultContractAttribute(typeof(customFault), Action="http://www.foo.com/:getRestaurantsIn", Name="customFault", Namespace="urn:thinktecture-com:demos:restaurantservice:messages:v1")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
getRestaurantsResponse getRestaurants(getRestaurantsRequest request);

There have been a number of requests for fault contract support on the CodePlex forum and I hope that you too will find this helpful. A new V1.0.9 update release is now available on CodePlex for download. Please put this new feature through its paces and report any problems you find on the discussion forum.

Tags: ,

Categories: Web Services | WSCF | Development Tools

Introducing Action Injection with Autofac ASP.NET MVC Integration

by Alex Meyer-Gleaves 16 May 2010 - 2:33 AM

There are currently two main approaches to performing dependency injection, Constructor Injection and Setter Injection. The more popular of the two approaches is Constructor Injection. The dependencies that a type has are made obvious because they must be supplied in order to construct an instance. This also makes it easier for you to ensure that a newly instantiated object is in a valid state. When working with a type the constructor is usually the first thing that you come into contact with.

With Setter Injection, also known as Property Injection, it is much more difficult to tell what the dependencies are when looking at the type from the outside. Setter Injection is most useful when you have no control over the instantiation of the type that requires the dependencies to be injected. This is a common scenario for ASP.NET WebForms where the activation of a Page instance is performed by the runtime. You do not have an opportunity to take over the activation process, and the first chance you have to perform dependency injection is when you are provided with an existing instance of Page. In this case you have no choice but to inject the dependencies into the type via its properties.

ASP.NET MVC has many extensibility points and is very flexible. It provides you with the opportunity to take over the creation of your Controller instances by creating your own factory that implements IControllerFactory, or more commonly by deriving from the DefaultControllerFactory and overriding the GetControllerInstance method. This makes it possible for your controllers to take advantage of Constructor Injection, and is exactly what the Autofac ASP.NET MVC Integration does. When it comes to unit testing your controller classes, it becomes very easy to see what dependencies it has, and to provide mock implementations for those dependencies.

An issue that is often raised in regards to Constructor Injection is what some people like to call Constructor Bloat. This may indicate that you are not following the Single Responsibility Principle and that some refactoring may be in order. The number of constructor parameters that would be considered too many would no doubt vary depending on who you ask. In the case of ASP.NET MVC controllers the number of constructor dependencies is more likely to be higher than for other classes. The level of responsibility for a controller is usual greater than what you would expect for an ordinary internal component. This is the result of mapping an external view of the application (URL based) onto an internal representation (controller based).

It turns out that both Nicholas Blumhardt and I found ourselves shifting some of these dependencies out of the controller’s constructor and into the action methods that actually require them. We were both fairly surprised to find out that the other had independently been doing exactly the same thing, and at this point discussed if there was something wrong with the approach because it seemed that no one else was doing it. Surely all good ideas have already been done so this one must be bad. I personally feel that having dependencies injected into your action method should not feel like a foreign concept because that is exactly what MVC is already doing for you with your existing parameters.

For lack of any official term that I am aware of, Action Injection is what I am calling this particular approach to dependency injection in ASP.NET MVC. The more I play around with this approach the more I like it. Your constructor is provided the dependencies that are shared by all actions in your controller, and each individual action can request any additional dependencies that it needs. Now when writing unit tests for your actions there is no need to provide mock implementations for dependencies that your action will not be interacting with. The end result is less mocks in your unit tests and a clear indication of the action’s actual dependencies.

Nick and I have decided to test out the idea of Action Injection in the Autofac ASP.NET MVC Integration. The changes are only in the source code at the moment and have not yet been included in a release. I mentioned earlier that MVC is very extensible and the process for invoking your action methods is no different. It is possible to replace the default behaviour by creating your own IActionInvoker. The easiest way to do this is by deriving from the AsyncControllerActionInvoker class and overriding the appropriate methods. A controller can be requested to use your custom action invoker by assigning an instance to the controller's ActionInvoker property. The current source includes a registration extension that allows you to register an IActionInvoker instance that will be assigned to a controller as it is activated. There is a default IActionInvoker implementation called ExtensibleActionInvoker that allows dependencies to be injected into your action methods. It can also do Setter Injection on your filters but that is a topic for another post. As the name suggests, you can extend this class and add any additional behaviour that you require. Registering controllers in the HttpApplication start would look something like this.

ContainerBuilder builder = new ContainerBuilder();

builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();
builder.RegisterControllers(Assembly.GetExecutingAssembly()).InjectActionInvoker();

// Register other services.

IContainer container = builder.Build();
_containerProvider = new ContainerProvider(container);

ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(_containerProvider));

I will not go into further detail on the implementation at this point because it may be tweaked a little before being released. Instead, let us look at an example of how we could make our action dependencies clearer using Action Injection. The NotifyController class below has action methods that send the current user a message using different delivery methods.

public class NotifyController
{
    public NotifyController(ILogger logger, 
        IEmailNotifier emailNotifier, 
        ISmsNotifier smsNotifier, 
        IMessengerNotifier messengerNotifier)
    {
        // Implementation.
    }
    
    public ActionResult Email(string message)
    {
        // Implementation.
    }
    
    public ActionResult Sms(string message)
    {
        // Implementation.
    }

    public ActionResult Messenger(string message)
    {
        // Implementation.
    }
}

There are three action methods on this controller and four dependencies that must be provided through the constructor. To unit test any of the action methods all four of the dependencies will need to be mocked. In this controller the ILogger instance is required by all action methods, but the remaining notifier dependencies are each required only by one action method. The controller could be refactored so that it takes the one ILogger dependency through its constructor, and each action could take its particular notifier dependency through a method parameter. Here is an example of how the refactored code would look.

public class NotifyController
{
    public NotifyController(ILogger logger)
    {
        // Implementation.
    }
    
    public ActionResult Email(string message, IEmailNotifier emailNotifier)
    {
        // Implementation.
    }
    
    public ActionResult Sms(string message, ISmsNotifier smsNotifier)
    {
        // Implementation.
    }

    public ActionResult Messenger(string message, IMessengerNotifier messengerNotifier)
    {
        // Implementation.
    }
}

Now when testing the action methods we only ever need to provide two mock services. There is no need to provide additional mock services that will never be used. Assuming we only had one unit test per action and setup our mocks inside each unit test, we would have halved the number of mocks required, taking the total from twelve down to six. That certainly seems like an improvement to me.

I would be interested to know what you think about this idea. Is it totally crazy or could there be something to it? Maybe you too have already been doing this and could share how it has been working out for you.

Tags: ,

Categories: Autofac | Web Development

Making Self-Hosting with Autofac WCF Integration easier

by Alex Meyer-Gleaves 16 May 2010 - 1:48 AM

Thinking about the sample I recently posted for shelf-hosting WCF Services with the Autofac WCF Integration, I decided that the boilerplate code for configuring the Service Behavior could be moved into an extension method on the ServiceHost instead. I have checked in some code that will extend ServiceHostBase with a new method called AddDependencyInjectionBehavior. There are two overloads of the method, one that takes a generic argument for the service contract type, and another that allows you to provide a Type for the service contract in case you are configuring your WCF Services in some sort of latebound manner. Both overloads of the method require an IContainer instance.

host.AddDependencyInjectionBehavior<IEchoService>(container);
host.AddDependencyInjectionBehavior(typeof(IEchoService), container);

As you can see from the updated sample below, the extension method makes the code considerably more concise, and will save you from having to write your own helper method that can be reused with your different WCF Services.

ContainerBuilder builder = new ContainerBuilder();
builder.Register(c => new Logger()).As<ILogger>();
builder.Register(c => new EchoService(c.Resolve<ILogger>())).As<IEchoService>();

using (IContainer container = builder.Build())
{
    Uri address = new Uri("http://localhost:8080/EchoService");
    ServiceHost host = new ServiceHost(typeof(EchoService), address);

    host.AddServiceEndpoint(typeof(IEchoService), new BasicHttpBinding(), string.Empty);

    host.AddDependencyInjectionBehavior<IEchoService>(container);

    host.Description.Behaviors.Add(new ServiceMetadataBehavior {HttpGetEnabled = true, HttpGetUrl = address});
    host.Open();
    
    Console.WriteLine("The host has been opened.");
    Console.ReadLine();

    host.Close();
    Environment.Exit(0);
}

The extension method will be available in the next release of Autofac. If you want to try it out without grabbing the latest Autofac source, the code below should give you a feel for how it works. You do not need to provide the service implementation type to the extension method because it can be retrieved from the ServiceHost instance. The Type instance that you provide in the ServiceHost constructor surfaces as the ServiceHost.Description.ServiceType property and can be used directly in the extension method.

public static class ServiceHostExtensions
{
    public static void AddDependencyInjectionBehavior<T>(this ServiceHostBase serviceHost, IContainer container)
    {
        AddDependencyInjectionBehavior(serviceHost, typeof(T), container);
    }

    public static void AddDependencyInjectionBehavior(this ServiceHostBase serviceHost, Type contractType, IContainer container)
    {
        IComponentRegistration registration;
        if (!container.ComponentRegistry.TryGetRegistration(new TypedService(contractType), out registration))
        {
            string message = string.Format("The service contract type '{0}' has not been registered in the container.", contractType.FullName);
            throw new ArgumentException(message);
        }

        AutofacDependencyInjectionServiceBehavior behavior = new AutofacDependencyInjectionServiceBehavior(
            container, serviceHost.Description.ServiceType, registration);
        serviceHost.Description.Behaviors.Add(behavior);
    }
}

Nothing fancy here but that should make self-hosting a little easier.

Tags: ,

Categories: Autofac | Web Services

Self-Hosting WCF Services with the Autofac WCF Integration

by Alex Meyer-Gleaves 7 May 2010 - 12:14 AM

A question came up recently in the Autofac group about how to use the WCF Integration when self-hosting WCF Services. This post provides a quick demonstration of how to handle the self-hosting scenario and should be enough to get you started. The example is a rather unimaginative web service that echoes back a message.

First declare the interface and implementation for a logger that the WCF Service will take as a dependency in its constructor. This is a simple logger that will log the message sent to the WCF Service out to the console.

public interface ILogger
{
    void Write(string message);
}

public class Logger : ILogger
{
    public void Write(string message)
    {
        Console.WriteLine(message);
    }
}

Next you need to define the contract and implementation for the WCF Service. Nothing interesting here other than our dependency being requested through the constructor of the WCF Service implementation.

[ServiceContract]
public interface IEchoService
{
    [OperationContract]
    string Echo(string message);
}

public class EchoService : IEchoService
{
    private readonly ILogger _logger;

    public EchoService(ILogger logger)
    {
        _logger = logger;
    }

    public string Echo(string message)
    {
        _logger.Write(message);
        return message;
    }
}

Now we can create a Console Application that will configure the container and host our WCF Service.

ContainerBuilder builder = new ContainerBuilder();
builder.Register(c => new Logger()).As<ILogger>();
builder.Register(c => new EchoService(c.Resolve<ILogger>())).As<IEchoService>();

using (IContainer container = builder.Build())
{
    Uri address = new Uri("http://localhost:8080/EchoService");
    ServiceHost host = new ServiceHost(typeof(EchoService), address);
    host.AddServiceEndpoint(typeof(IEchoService), new BasicHttpBinding(), string.Empty);

    IComponentRegistration registration;
    if (!container.ComponentRegistry.TryGetRegistration(new TypedService(typeof(IEchoService)), out registration))
    {
        Console.WriteLine("The service contract has not been registered in the container.");
        Console.ReadLine();
        Environment.Exit(-1);
    }

    host.Description.Behaviors.Add(new AutofacDependencyInjectionServiceBehavior(container, typeof(EchoService), registration));
    host.Description.Behaviors.Add(new ServiceMetadataBehavior {HttpGetEnabled = true, HttpGetUrl = address});
    host.Open();
    
    Console.WriteLine("The host has been opened.");
    Console.ReadLine();

    host.Close();
    Environment.Exit(0);
}

Here we have added an IServiceBehavior called AutofacDependencyInjectionServiceBehavior that will add a custom IInstanceProvider to the DispatchRuntime of each endpoint’s EndpointDispatcher. That is a bit of a mouth full but basically means that Autofac will use the WCF extensibility points to provide WCF Service instances that have their dependencies injected.

In this example the WCF Service is exposed on an endpoint that uses the BasicHttpBinding but you can use any type of endpoint that you like. I have added a ServiceMetadataBehavior in this example that exposes the WSDL for the WCF Service at http://localhost:8080/EchoService?wsdl. You can use this address to create a client proxy and send test messages that are hopefully more creative than my example.

Tags: ,

Categories: Autofac | Web Services

WSCF.blue Roadmap

by Alex Meyer-Gleaves 6 May 2010 - 12:00 AM

image The WSCF.blue team has been discussing the features we should include in the next release. Benjy has done a great job summarising the current roadmap on his blog and is inviting feedback. You might feel that important features are missing, or perhaps that a particular feature is a bad idea, and would take the tool in the wrong direction. I decided that I would share what features are important to me, and put out for consideration and feedback some concerns I have with particular features. It is worth noting at this point that this is not an official roadmap, and is really just a summary of the ideas that we have been throwing around.

Having used WSCF.blue in a team environment, I would certainly put having the ability to permanently persist the settings for a web service in a way that makes them easy to share at the top of my list. Perhaps some sort of project structure that keeps your WDSL and XSD files along with your preferences altogether. There are a number of different options that can be applied when generating your web service code, and it is important that this step be repeated consistently, regardless of the developers familiarity with that particular web service. In regards to the actual options, I would also like to see support for WS-Addressing and fault contracts in the WSDL generation process. Adding these into the contract manually becomes another step that could be forgotten.

The issues noted about T4 templates are primarily concerns that I raised with the team. You get great flexibility with such a technology but it does come at a cost. These templates are not immediately approachable to all developers, especially when you are dealing with a complex model with many possible combinations. There are tools that make developing templates a more pleasant experience, but the mixing of static and dynamic content in such a manner still makes it fairly easy to introduce errors. I worry that it would become difficult to determine if a problem exists within the codebase or has been introduced in a customised template. Being an open source project there is only so much time that can be dedicated to support, so making things simple and reliable feels important. There is of course also the issue of upgrading templates, which forces users to migrate their customisations each time changes are made to the original.

Microsoft has released Feature Builder and it looks like it would be a very good fit for a tool like WSCF.blue. It certainly appears to be a considerable improvement over the Guidance Automation Toolkit (enough said). I would think that if we chose Feature Builder as the primary user experience, we would want to write an Ultimate Feature Extension that takes advantage of the modeling and visualization features that exist in Visual Studio 2010 Ultimate Edition. This is the point that you can start to do some really interesting things with Feature Builder. The problem is of course the requirement to have the most recent and expensive version of Visual Studio. My concern here is that we would make the tool inaccessible to a number of developers, and we really want as many people as possible to use the tool and embrace the contract-first approach.

There are a lot of great ideas on the roadmap and some really interesting technology choices to be made. I would be glad to hear your thoughts on any of these issues and the roadmap in general.

Tags: ,

Categories: Web Services | WSCF | Development Tools

Refactor to the NUnit Fluent API with ReSharper Code Patterns

by Alex Meyer-Gleaves 15 April 2010 - 2:19 AM

ReSharper Logo One of the new features in the recently released ReSharper 5 is Structural Search and Replace. This allows you to perform complex searches on your code, and then make equally complex replacements on the resulting matches. You can read the Introducing ReSharper 5.0: Structural Search and Replace post on the JetBrains blog to quickly bring yourself up to speed.

Solutions are commonly flooded with various code smells that are hard to eliminate right away. ReSharper 5 helps you get rid of them in existing code, but more than that, it allows you to create custom inspections to remove poor coding artifacts on a recurring basis.

Specifically, ReSharper helps configure custom, sharable code patterns, search for them, replace them, include them in code analysis, and even use quick-fixes for regular code maintenance! Building patterns and enforcing good practices has never been this easy. Corporate and team policies, custom frameworks, favorite open source libraries and tools — structured patterns are able to cover them all.

The coolest part of all this is being able to save the Structural Searches and include them alongside the built-in code inspections. NUnit is my preferred unit testing framework and I really like the fluent API it offers for making assertions. This seemed like the perfect opportunity to test out Structural Search by creating some code patterns that would find usages of the regular API and convert them to the new fluent API.

I basically wanted to find assertions that look this this.

object foo = new object();
object nullFoo = null;

Assert.AreEqual(1, 1);
Assert.AreNotEqual(1, 2);
Assert.AreNotSame(1, 2);
Assert.AreSame(foo, foo);
Assert.Contains(1, new List<int> {1, 2, 3});
Assert.False(false);
Assert.Greater(2, 1);
Assert.GreaterOrEqual(2, 1);
Assert.IsAssignableFrom(typeof(int), 1);
Assert.IsNotAssignableFrom(typeof(int), false);
Assert.IsEmpty(new List<int>());
Assert.IsFalse(false);
Assert.IsInstanceOf(typeof(int), 1);
Assert.IsNaN(double.NaN);
Assert.IsNotEmpty(new List<int> {1});
Assert.IsNotInstanceOf(typeof(int), false);
Assert.IsNotNull(foo);
Assert.IsNotNullOrEmpty("Foo");
Assert.IsNull(nullFoo);
Assert.IsNullOrEmpty(string.Empty);
Assert.IsTrue(true);
Assert.Less(1, 2);
Assert.LessOrEqual(1, 2);
Assert.NotNull(new object());
Assert.Null(nullFoo);
Assert.ReferenceEquals(foo, foo);
Assert.True(true);

And make them look like this instead.

object foo = new object();
object nullFoo = null;

Assert.That(1, Is.EqualTo(1));
Assert.That(2, Is.Not.EqualTo(1));
Assert.That(2, Is.Not.SameAs(1));
Assert.That(foo, Is.SameAs(foo));
Assert.That(new List<int> {1, 2, 3}, Contains.Item(1));
Assert.That(false, Is.False);
Assert.That(2, Is.GreaterThan(1));
Assert.That(2, Is.GreaterThanOrEqualTo(1));
Assert.That(1, Is.AssignableFrom<int>());
Assert.That(false, Is.Not.AssignableFrom<int>());
Assert.That(new List<int>(), Is.Empty);
Assert.That(false, Is.False);
Assert.That(1, Is.InstanceOf<int>());
Assert.That(double.NaN, Is.NaN);
Assert.That(new List<int> {1}, Is.Not.Empty);
Assert.That(false, Is.Not.InstanceOf<int>());
Assert.That(foo, Is.Not.Null);
Assert.That("Foo", Is.Not.Null.Or.Empty);
Assert.That(nullFoo, Is.Null);
Assert.That(string.Empty, Is.Null.Or.Empty);
Assert.That(true, Is.True);
Assert.That(1, Is.LessThan(2));
Assert.That(1, Is.LessThanOrEqualTo(2));
Assert.That(new object(), Is.Not.Null);
Assert.That(nullFoo, Is.Null);
Assert.That(foo, Is.SameAs(foo));
Assert.That(true, Is.True);

Nothing particularly difficult in this task other than a fair dose of pounding on the keyboard. After creating the first couple of patterns using the Pattern Catalogue dialog in Visual Studio, I exported the patterns to an XML file and continued my editing from there. Working directly with the XML in your favourite editor will certainly save you some time when making edits to your patterns in bulk. The end result was the list of code patterns below.

Pattern Catalogue

Now ReSharper will include these code patterns into its code inspections, and show the usual visual indicators for the Suggestion severity level.

Visual Indicators

JetBrains have given me yet another reason to love ReSharper. You can find an XML export of the code patterns attached.

NUnit Fluent API Code Patterns.xml (12.61 kb)

Tags: ,

Categories: Development Tools

Autofac 2.0 Podcast

by Alex Meyer-Gleaves 6 April 2010 - 12:47 AM

Make sure you have a listen to Nicholas Blumhardt talking about Autofac 2 on the Talking Shop Down Under podcast.

It's Inversion of Control Time! This week Nick Blumhardt talks about IoC containers in general, the problems with the service locator pattern and why constructor injection is considered a better choice, a little about how MEF and Autofac differ in purpose and a lot about Autofac 2's new features.

Nick was also a guest on .NET Rocks! last year, and that episode is definitely worth listening to as well.

The .NET dudes talk to Nicholas Blumhardt about Autofac, an IoC container that uses lambda expressions in C# 3.0 to create components.

Keep spreading the good word Nick!

Tags:

Categories: Autofac

Framework Design Guidelines Second Edition

by Alex Meyer-Gleaves 6 April 2010 - 12:33 AM

Framework Design Guidelines Second Edition I have just finished reading Framework Design Guidelines Second Edition and must say that I enjoyed the read. The first edition of this book was good enough to find a place on my shelf at the office and the second edition expands and improves upon the first. The many annotations dispersed throughout the book by various experts provide some interesting insight into the challenges they have faced. Best practice is not something that is immediately apparent, and often comes from having made mistakes and seeing how things pan out in the real world. It is very refreshing to see people like Brad Abrams and Krzysztof Cwalina drawing attention to the mistakes they made in designing the .NET Framework in order to help others avoid similar issues.

Brad Abrams: We added a set of controls to ASP.NET late in the ship cycle for V1.0 of the .NET Framework that rendered for mobile devices. Because these controls came from a team in a different division, our immediate reaction was to put them in a different namespace (System.Web.MobileControls). Then, after a couple of reorganizations and .NET Framework versions, we realized a better engineering trade-off was to fold that functionality into the existing controls in System.Web.Controls. In retrospect, we let internal organizational differences affect the public exposure of the APIs, and we came to regret that later. Avoid this type of mistake in your designs.

You can now see in the documentation that every type in the System.Web.UI.MobileControls namespace has been marked as obsolete. Working on a large product with a substantial investment in the underlying framework I can certainly appreciate that you will make mistakes despite your best efforts. Creating guidance that reflects what you have learned from past issues is a great way of limiting the accumulation of future technical debt. When the code you write represents a public API you need to very carefully consider each of your decisions. I too have a laundry list of things that I wish had been done differently, and I think anyone who has worked on a product or framework of a substantial size would as well. It is important to not just dismiss your mistakes, but to highlight them along with a means of avoiding in them in the future, and make sure they everyone on your team can learn from them.

Tags:

Categories: Microsoft .NET

Switching to reCAPTCHA for Comment Spam protection

by Alex Meyer-Gleaves 30 March 2010 - 1:45 AM

reCAPTCHA I recently posted about using CAPTCHA on my blog in an attempt to reduce the amount of comment spam. The implementation I posted about has worked well for me but I decided I would like to switch to reCAPTCHA. Not only is this free CAPTCHA service robust and well tested, it also helps to digitize books, newspapers and old time radio shows. Taking the thousands of hours people spend entering CAPTCHA information each day and utilizing them for an additional purpose is a brilliant idea.

As with the previous solution I was sure that someone would have already done the work to integrate reCAPTCHA with BlogEngine.NET. My assumption was correct and I quickly found a solution in the form of an extension written by Filip Stanek. I followed the simple installation process and had the control appearing in the comment form straight away. After a short period of testing I quickly found a couple of problems. Once the first comment was added all subsequent comments entered resulting in an error that was reported via the callback. The log viewer added to the administration area was also throwing an exception and failing to load.

I tracked both of these problems down to the extension expecting the return value from BlogService.LoadFromDataStore to be a Stream. This method returns an object instance and delegates its work to the currently configured BlogProvider. The BlogProvider.LoadFromDataStore method also returns object, and it turns out that the type of the object returned will be different depending on the provider being used. My data store is a VistaDB.NET database so I am using the DbBlogProvider instead of the default XmlBlogProvider. Unfortunately the DbBlogProvider returns a string and the XmlBlogProvider returns a Stream. There is nothing stopping the next provider that is written from returning yet another type. This no doubt makes life difficult for those writing BlogEngine.NET extensions.

To get the extension working with the DbBlogProvider you will need to make a couple of small changes. In the Recaptcha.cs file, find the code below in the UpdateLog method.

Stream s = (Stream)BlogService.LoadFromDataStore(BlogEngine.Core.DataStore.ExtensionType.Extension, "RecaptchaLog");
List<RecaptchaLogItem> log = new List<RecaptchaLogItem>();
if (s != null)
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<RecaptchaLogItem>));
    log = (List<RecaptchaLogItem>)serializer.Deserialize(s);
    s.Close();
}
log.Add(logItem);

Replace it with the following code.

string data = (string)BlogService.LoadFromDataStore(BlogEngine.Core.DataStore.ExtensionType.Extension, "RecaptchaLog");
List<RecaptchaLogItem> log = new List<RecaptchaLogItem>();
if (!string.IsNullOrEmpty(data))
{
    using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(data)))
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<RecaptchaLogItem>));
        log = (List<RecaptchaLogItem>)serializer.Deserialize(stream);
    }
}
log.Add(logItem);

In the RecaptchaLogViewer.aspx.cs file, find the code below in the BindGrid method.

Stream s = (Stream)BlogService.LoadFromDataStore(BlogEngine.Core.DataStore.ExtensionType.Extension, "RecaptchaLog");
List<RecaptchaLogItem> log = new List<RecaptchaLogItem>();
if (s != null)
{
    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<RecaptchaLogItem>));
    log = (List<RecaptchaLogItem>)serializer.Deserialize(s);
    s.Close();
}

Replace it with the following code.

string data = (string)BlogService.LoadFromDataStore(BlogEngine.Core.DataStore.ExtensionType.Extension, "RecaptchaLog");
List<RecaptchaLogItem> log = new List<RecaptchaLogItem>();
if (!string.IsNullOrEmpty(data))
{
    using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(data)))
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<RecaptchaLogItem>));
        log = (List<RecaptchaLogItem>)serializer.Deserialize(stream);
    }
}

You should now be able to use the extension with the DbBlogProvider without any problems. The rest of the extension seems to work without any problems and appears to be well written overall. It is definitely worth checking out if you are looking for a reCAPTCHA solution for BlogEngine.NET.

Tags:

Categories: BlogEngine.NET | Web Development

About the author

Alex Meyer-Gleaves I'm a software developer living in Australia (that island like continent in the southern hemisphere). I love Microsoft .NET and C#. I hate early mornings, slow drivers and Lotus Notes.

Google Reader Clips

SpringWidgets
RSS Reader
This widget is the staple of our platform. Read all your feeds right here with thisone widget - Supported feeds are OPML, RSS, RDF, ATOM. Watch your favorite Podcastin the embedded Video Player on the Desktop or publish your own video playlist toyour site for others to view!

Recent Comments

Comment RSS

Links

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008