Jul 18 2010

Speaking at CodeCampOz

Category: IT Related | .Net | ApplicationsRory Primrose @ 04:19

Mitch has just posted the agenda for CodeCampOz that is running in November. Looks like it will be a really good mix of information being presented this year.

I’ll be running a session on Windows Identity Framework and how to use it without federation. Here is the abstract for my session.

Not a WIF of federation

The Windows Identify Framework (WIF) provides the latest Microsoft implementation for working in the claims-based identity space. WIF has particular strengths in providing federated security for systems that target users across multiple security domains, multiple credential types and multiple credential stores.

Unfortunately the available WIF documentation and samples almost completely deal with federated security scenarios. The information provided continues to use federated security architectures (Security Token Services, Issuing Authorities, Relying Parties etc.) even when federation is not used.

Developers of small systems may find it difficult to understand how WIF fits into their system designs. Small systems in this context tend to have their own security store, do not cross security domains and may not even run within an Active Directory managed domain.

There are clear benefits with using claims based security in both large and small systems. How do developers leverage claims-based security without being tied to federated security architectures?

This session will briefly cover the benefits of claims-based security and then look at how to implement WIF in ASP.Net and WCF applications without federation dependencies.

Tags: , , ,

Jul 12 2010

Canberra .Net Users Group Presentation next week

Category: .Net | ApplicationsRory Primrose @ 17:32

I’m going to be presenting at this months .Net Users Group in Canberra. The topic will be Unity injection for ASP.Net and WCF with some Unity extensibility added in as well.

Here is the abstract for the session.

Unity is the Microsoft Patterns and Practises implementation of an inversion of control (IoC) container. Using IoC containers facilitates the dependency injection pattern which helps to decouple code from its dependencies.

A common way to implement IoC in ASP.Net and WCF services is to couple the hosted application to the IoC container. The first half of this session will look at how ASP.Net and WCF applications can be extended to leverage the benefits of IoC while decoupling the hosted application from the container.

The second half of the session will look at how Unity can be extended to provide a recursive disposal pattern for build trees created by the container.

If you are local then I hope to see you there.

Tags: , , , , , , , ,

Jul 7 2010

Unity build failure recovery for DisposableStrategyExtension

Category: .Net | ApplicationsRory Primrose @ 17:41

I posted recently about my Unity extension that disposes build trees when a container tears down an instance it previously created. The extension makes an assumption that a Unity build operation will either succeed completely or fail completely. Normally you expect this to be the case. I have however now come up with an edge case.

I am writing another Unity extension that adds support for injecting proxy instances as dependencies. Part of this design allows for custom proxy handlers to be injected. Defining a custom proxy handler is optional and can either be specifically defined in configuration at the injection definition or be automatically resolved by the Unity container from contextual information. If a custom proxy isn’t defined or can’t be automatically resolved then the injection will fall back to a default proxy handler type.

This new extension creates a child build context within the build context of the proxy dependency being created by the Unity container. The child build context will attempt to create the proxy handler just in case the container is configured for it. Unity will throw an exception if the proxy handler isn’t defined. In this case however, the build operation needs to continue rather than failing like you would normally expect.

This becomes a problem for the DisposableStrategyExtension. It tracks build trees as they are created using the BuildTreeTracker class mentioned in the previous post. It tracks when a new build context is started and when it is finished. Each iteration of this process tracks the current tree node being built by the context. Each child build context encountered results in a new child node that is simply added to the current node. The child node then becomes tracked as the current node being built. Unfortunately there is no fault tolerance for when an item fails to be built when the overall build operation can continue.

Consider the following build tree for example.

  • Root
    • ChildA
      • DependencyA
      • DependencyB
    • ChildB

The PreBuildUp method in BuildTreeTracker gets invoked before each tree node is created and PostBuildUp gets invoked after each node (and it’s children) are completely built. The BuildTreeTracker class tracks the start and end of each item being built via these two methods. What happens if the creation of ChildA fails without any recovery action? Assuming the build process handles the build failure exception and continues the build, the BuildTreeTracker identifies the current node as ChildA when it goes to create ChildB (PreBuildUp) however it should actually point to Root. This is because the tracker re-points the current node in the build tree back to the parent of the current node on PostBuildUp. Unfortunately PostBuildUp does not get invoked when a build context fails.

Enter the IRequiresRecovery interface. This interface allows for some recovery operation to be invoked when a build context has failed to create an instance.

using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using Microsoft.Practices.ObjectBuilder2;

namespace Neovolve.Toolkit.Unity
{
    internal class BuildTreeRecovery : IRequiresRecovery
    {
        public BuildTreeRecovery(IBuilderContext context, BuildTreeItemNode failedNode, Action<BuildTreeItemNode> failureAction)
        {
            Contract.Requires<ArgumentNullException>(context != null, "The context parameter is null");
            Contract.Requires<ArgumentNullException>(failedNode != null, "The failedNode parameter is null");

            Context = context;
            FailedNode = failedNode;
            FailureAction = failureAction;
        }

        public void Recover()
        {
            try
            {
                if (FailureAction != null)
                {
                    FailureAction(FailedNode);
                }

                BuildTreeItemNode parentNode = FailedNode.Parent;

                BuildTreeDisposer.DisposeTree(Context, FailedNode);

                if (parentNode != null)
                {
                    parentNode.Children.Remove(FailedNode);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Recovery failed: " + ex);
            }
        }

        protected IBuilderContext Context
        {
            get;
            private set;
        }

        protected BuildTreeItemNode FailedNode
        {
            get;
            private set;
        }

        protected Action<BuildTreeItemNode> FailureAction
        {
            get;
            private set;
        }
    }
}

The BuildTreeRecovery class allows for a custom action to be invoked. It then cleans up any partial build trees that were successfully created under the failed node and then removes it from its parent. If you assume in the previous example that DependencyA and DependencyB were successfully created before ChildA failed, then BuildTreeRecovery will ensure that ChildA, DependencyA and DependencyB are all disposed and that the failed node (ChildA) is then removed from the build tree.

The final piece missing here is that the BuildTreeTracker class will still have a reference to ChildA being the current node instead of Root when PreBuildUp is invoked for ChildB. This is where the custom action of the recovery class comes in. The BuildTreeTracker.PreBuildUp method has been updated to create the BuildTreeRecovery class and use it in a recovery stack. The action passed to its constructor is a lambda expression that repairs the assignment of the current node in the build tree to be the parent of the failed node.

public override void PreBuildUp(IBuilderContext context)
{
    base.PreBuildUp(context);

    if (context == null)
    {
        return;
    }

    Boolean nodeCreatedByContainer = context.Existing == null;
    BuildTreeItemNode newTreeNode = new BuildTreeItemNode(context.BuildKey, nodeCreatedByContainer, CurrentBuildNode);

    if (CurrentBuildNode != null)
    {
        // This is a child node
        CurrentBuildNode.Children.Add(newTreeNode);
    }

    CurrentBuildNode = newTreeNode;

    BuildTreeRecovery recovery = new BuildTreeRecovery(context, newTreeNode, failedNode => CurrentBuildNode = failedNode.Parent);

    context.RecoveryStack.Add(recovery);
}

Completing the example proposed above, the resultant build tree when ChildA fails to build would be:

  • Root
    • ChildB

While using this recovery class satisfies my optional build requirement for proxy injection, it provides an arguably more important feature. Build trees might fail at anytime and applications may recover from or simply ignore the failures and continue. The partial build trees created in these attempts may have created some references that require disposal but this can never occur because the original BuildTreeTracker code would simply lose track of nodes successfully created in a failed build tree. This solution will ensure that these instances are disposed immediately if the build operation fails.

Tags:

May 18 2010

WinMerge support for VS2010 and TFS

Category: .Net | ApplicationsRory Primrose @ 10:12

Back in 2007 I wrote a post about WinMerge support for TFS in Visual Studio. It turned out to be the most hit post on my blog ever since. I have just updated the post with some reg files that add the same support for VS2010 for both x86 and x64 platforms.

Tags: ,

May 17 2010

Unity dependency injections for WCF services – Part 2

Category: .Net | ApplicationsRory Primrose @ 16:23

In Part 1, I described the code used to leverage ServiceHostFactory to create WCF service instances with dependency injection via Unity. Using a custom ServiceHostFactory is a really easy way to get dependency injection in WCF but comes with two drawbacks. The standard Unity configuration section name (“unity”) must be used and named Unity containers are not supported. Most applications will work within these constraints.

Using a configuration based service behavior is the answer to situations where these constraints are a problem. The UnityServiceElement class is used to define the configuration support for the UnityServiceBehavior. As outlined in the last post, the UnityServiceBehavior class is used to assign a custom instance provider to each endpoint in the service. The instance provider is used to resolve a service instance from a Unity container.

The UnityServiceElement class looks like the following. The UnityServiceElement calls into a UnityContainerResolver helper class to resolve the unity container. The code for UnityContainerResolver can be found here.

using System;
using System.Configuration;
using System.Diagnostics.Contracts;
using System.ServiceModel.Configuration;
using Microsoft.Practices.Unity;

namespace Neovolve.Toolkit.Unity
{
    public class UnityServiceElement : BehaviorExtensionElement
    {
        public const String UnitySectionNameAttributeName = "unitySectionName";

        private const String UnityContainerNameAttributeName = "unityContainerName";

        private ConfigurationPropertyCollection _properties;

        public override void CopyFrom(ServiceModelExtensionElement from)
        {
            Contract.Requires<ArgumentException>(from is UnityServiceElement, "The from parameter is not of type UnityServiceElement.");

            base.CopyFrom(from);

            UnityServiceElement element = (UnityServiceElement)from;

            UnitySectionName = element.UnitySectionName;
            UnityContainerName = element.UnityContainerName;
        }

        protected override Object CreateBehavior()
        {
            IUnityContainer container = UnityContainerResolver.Resolve(null, UnitySectionName, UnityContainerName);

            return new UnityServiceBehavior(container);
        }

        public override Type BehaviorType
        {
            get
            {
                return typeof(UnityServiceBehavior);
            }
        }

        [ConfigurationProperty(UnityContainerNameAttributeName)]
        public String UnityContainerName
        {
            get
            {
                return (String)base[UnityContainerNameAttributeName];
            }

            set
            {
                base[UnityContainerNameAttributeName] = value;
            }
        }

        [ConfigurationProperty(UnitySectionNameAttributeName)]
        public String UnitySectionName
        {
            get
            {
                return (String)base[UnitySectionNameAttributeName];
            }

            set
            {
                base[UnitySectionNameAttributeName] = value;
            }
        }

        protected override ConfigurationPropertyCollection Properties
        {
            get
            {
                if (_properties == null)
                {
                    ConfigurationPropertyCollection propertys = new ConfigurationPropertyCollection();

                    propertys.Add(
                        new ConfigurationProperty(
                            UnitySectionNameAttributeName, typeof(String), String.Empty, null, null, ConfigurationPropertyOptions.None));

                    propertys.Add(
                        new ConfigurationProperty(
                            UnityContainerNameAttributeName, typeof(String), String.Empty, null, null, ConfigurationPropertyOptions.None));

                    _properties = propertys;
                }

                return _properties;
            }
        }
    }
}

The configuration to hook this behavior up to a service looks like this.

<?xml version="1.0" ?>
<configuration>
    <configSections>
        <section name="customUnitySection"
                 type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
    </configSections>
    <customUnitySection>
        <containers>
            <container name="customContainer">
                <register type="Neovolve.Toolkit.Unity.WebIntegrationTests.TestService, Neovolve.Toolkit.Unity.WebIntegrationTests">
                    <constructor>
                        <param name="prefix">
                            <value value="Injected by custom unity section and container"/>
                        </param>
                    </constructor>
                </register>
            </container>
        </containers>
    </customUnitySection>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="UnityBehavior">
                    <unityService unitySectionName="customUnitySection"
                                  unityContainerName="customContainer"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <extensions>
            <behaviorExtensions>
                <add name="unityService"
                     type="Neovolve.Toolkit.Unity.UnityServiceElement, Neovolve.Toolkit.Unity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=911824a9aa319cb2"/>
            </behaviorExtensions>
        </extensions>
        <services>
            <service behaviorConfiguration="UnityBehavior"
                     name="Neovolve.Toolkit.Unity.WebIntegrationTests.TestService">
                <endpoint address=""
                          binding="basicHttpBinding"
                          bindingConfiguration=""
                          contract="Neovolve.Toolkit.Unity.WebIntegrationTests.ITestService"/>
            </service>
        </services>
    </system.serviceModel>
</configuration>

The configuration for the element shown here allows for defining custom configuration section and container names for resolving the Unity container.

ServiceHostFactory or configured service behavior

Which one to use?

If you have multiple containers, or a single container that must have a name, then you have no choice but to use the service behavior element as outlined in this post. The only other reason for using the behavior element is if you must use another type of custom factory (such as the WIF WSTrustServiceHostFactory). There really should be no reason to use a non-standard configuration section name for Unity so I don’t think that is a big factor.

Using the ServiceHostFactory is the preferred option as it will result in a slightly cleaner configuration if you are not forced into using a configured service behavior,

The code with xml comments can be found in my Toolkit project on CodePlex.

Tags: , , , ,

Feb 17 2010

Recommended reading for developers

I was reminded this morning of an email that I sent to the junior developers on my team when they joined us. It is an overview of some of the development practices, patterns and products that they would get exposed to on our project. I have included it here as a reference collection for others.

Principles and Patterns

These are things that I often use and are still learning to use.

Jeremy Miller also writes a series called Patterns in Practice for MSDN Magazine (see list at http://msdn.microsoft.com/en-au/magazine/cc720886.aspx). They are all a good read, especially:

Tools

These are tools that are good to get experience using. Most of them relate to the patterns above. There are other tools used like ReSharper, dotTrace, StyleCop, WinMerge etc, but they don’t have the up skill requirement that the following tools do.

Probably the most important tool to start using is Rhino Mocks. The only way to get experience with it is to start writing unit tests in VS. See the documentation at http://ayende.com/wiki/Rhino+Mocks+Documentation.ashx.

Tags: , , , , , , , , , , , , , ,

Sep 15 2009

Adding delete comment support to the Commentor extension

Category: Applications | .NetRory Primrose @ 09:24

The Commentor extension for BlogEngine.Net written by rtur is a great extension for catching comment spam on the blog. Unfortunately the custom rules you can apply to comments only support a Block or Allow action.

What I want is to prevent the comments being saved at all if a manual rule has been violated. This is better for my needs as I don’t need to clean up the comments on the blog and I don’t get hassled by constant emails regarding comments that require moderation.

The changes to the extension to support this are relatively minor.

First is a change to the User controls\Commentor\Settings.aspx user control. The action dropdown now has a Delete action.

<td>
    <asp:DropDownList ID="ddAction" runat="server">
        <asp:ListItem Text="Block" Value="Block" Selected=true></asp:ListItem>
        <asp:ListItem Text="Allow" Value="Allow" Selected=false></asp:ListItem>
        <asp:ListItem Text="Delete" Value="Delete" Selected=false></asp:ListItem>
    </asp:DropDownList>
</td>

The next set of changes were to implement the Delete action in the App_Code\Extensions\Commentor.cs class.

The ManualFilter enum definition has been extended to include the Delete action.

private enum ManualFilter { None, Block, Allow, Delete }

The Post_AddingComment method now supports this enum value in its processing of a new comment.

// validate against filter
switch (CheckFilter(comment))
{
    case ManualFilter.Block:
        comment.IsApproved = false;
        return;
    case ManualFilter.Allow:
        comment.IsApproved = true;
        return;
    case ManualFilter.Delete:
        comment.IsApproved = false;
        e.Cancel = true;
        return;
    default:
        break;
}

And finally, the CheckRow method has been updated to use the new Delete action.

if (match)
{
    if (action == "Block")
        return ManualFilter.Block;
    if (action == "Delete")
        return ManualFilter.Delete;
    return ManualFilter.Allow;
}

Make these changes and you will be able to use delete actions to prevent comments from being saved.

NOTE: The settings for existing rules will need to be updated where they are stored (most likely in a database or xml file) in order for them to use the Delete action. A restart of the website will be required to pick up these changes that were made directly against the settings datastore. Alternatively you will need to delete and recreate any existing custom rules that you want to use the Delete action with.

My Commentor extension settings now look like the following.

Commentor settings

Tags: , ,

Jun 1 2009

GhostDoc has been acquired by SubMain

Category: Applications | .NetRory Primrose @ 21:26

Just like Reflector, SubMain has just acquired GhostDoc and has released an updated version. Looks like SubMain has already put in a decent amount of effort for GhostDoc. This is appears to be significantly different in contrast to what Red Gate has published for Reflector. Looks like it will be interesting times ahead for these tools.

Tags:

Mar 19 2009

GhostDoc feature in hiding - Roland already has the goods!

Category: .Net | ApplicationsRory Primrose @ 04:44

As I was writing and using my custom GhostDoc rules (here and here), I was thinking that it would be nice if GhostDoc was able to clear the existing documentation and then apply the DocumentThis command. I emailed Roland Weigelt about the feature idea not realising there is a forum for feature requests. He quickly replied saying that the feature is already there albeit undocumented. This is exactly what I was after.

If you open up the keyboard bindings and do a search for GhostDoc, you will find a RebuildDocumentation command.

GhostDoc keyboard bindings

I have assigned the RebuildDocumentation to a Ctrl+Shift+D, Ctrl+Shift+R combination and changed DocumentThis to Ctrl+Shift+D, Ctrl+Shift+D combination. Roland said to make sure that the new keyboard binding is only used in Text Editor (as highlighted above).

Tags:

Mar 18 2009

Using GhostDoc to document unit test classes

Category: .Net | ApplicationsRory Primrose @ 06:47

To follow up on my last post about documenting unit test methods with GhostDoc, a similar concept can be applied to documenting unit test classes.

Add a custom rule under the Classes section in the GhostDoc configuration dialog.

I have used the name "Matches unit test class" and identified type names that end with "Tests". I have entered the summary documentation with the following value:

The $(TypeName.ShortNameAsSee)
class is used to test the <see cref="$(TypeName.Words.Verbatim.ExceptLast)" /> class.$(End)

Edit Rule dialog

This produces much nicer documentation that the default documentation provided by Visual Studio.

Tags: