Humblecoder

Apprentice unit tester, expert rambler

Archive for the ‘.NET’ Category

I Was Wrong About Delegate Factories “Micro Optimisations”

without comments

In my previous post I talked about creating typed delegate factories, towards the end of the post I talked about optimising the performance by avoiding boxing when passing value type parameters around.  My premise was that if we could use generics to select strongly typed method signatures for the method that constructs the type we could avoid the boxing and unboxing of value types.  I think outside of dependencies, the most common constructor arguments is going to be value types.  But I was wrong.

Why?

It all boils down to Constructor.Invoke, this is the method my tiny dependency injection framework uses to create new instances of objects from the container.  Its only signature takes params object[] so all our hard work is useless because the values will be boxed for this call.

The biggest thing I was wrong about, though, was that reflection is quicker than boxing.  Lets look at the timing of the reflective generic approach:

reflective

So generating the factory takes 79ms when you reflect over the type and remove any generics.  But what about calling using params object[].

bloxing

This takes 31ms to create the factory.  So it is quite clear that, at least upfront, using the param approach is substantially quicker.  One thing I will point out is, the tests didn’t use the factories to create any types.  But the values will still be boxed when passed to the invoke method so I would still expect the second method to be more performant.

My point is that we need to look more closely at how we are going to use the code and if there is any optimisation, like caching the generated delegates, that would speed up calls after taking an initial hit.  If we didn’t need to make the call Constructor.Invoke would the second approach still be quicker overall in our application?

VN:F [1.9.3_1094]
Rating: 4.0/5 (2 votes cast)

Written by Will

February 13th, 2010 at 1:06 am

Posted in .NET, C#, CodePlex

Tagged with , , , ,

Creating Typed Delegates at Runtime Using Expression Trees

without comments

In my previous post I talked about using the abstract factories pattern instead of the service locator pattern.  Towards the end of the post I went on to talk about delegate factories and I want to clear up any misunderstanding before going any further.  I think injecting the factory via the constructor is the right way to do this, the delegate factories I talked about are just a simplification and a way to remove the need to write a lot of simple and repetitive code.  I don’t think it helps that I switched example code towards the end. So here is an example using IFile / FileConsumer.

delegate IFile IFileFactoryForFileName(String fileName);

public class FileConsumer
{
    private IFileFactoryForFileName CreateFileForFileName;

    public FileConsumer(IFileFactoryForFileName ifileFactory)
    {
        CreateFileFromFileName = ifileFactory;
    }

    public void DoSomething()
    {
        IFile fileA = CreateFileForFileName("test.txt");

        //uses fileA
    }
}

In this example we don’t have an interface and implementation for a factory just the delegate declaration, this would live near the IFile interface, and we will trust the container to wire this up for us when it is resolving the constructor arguments.  This leads nicely into the how.

All About Expression

When first looking at the problem of how to generate the delegates I thought easy, anonymous delegates or lambdas and let type inference take care of the rest but the reality is somewhat more complicated.  The best way to achieve this is using Expression Trees.

Expression trees are the foundation of LINQ and a high level abstraction that allow you to treat a tree of objects as code.  This allows us to build an expression at runtime that represents the required factory then compile it to a lambda and finally the delegate we require. 

All this starts at the Expression class, it is an abstract class that is used as a base class for Expression objects that represent the various things we can do.   It, also, has static methods that create the relevant expression objects for us.  The ones we are interested in are:

  • ParameterExpression – This is what it sounds like, it allows us to create a parameter that is going to be passed into and used in by the expression.
  • ConstantExpression – Again it’s obvious what this does, it represents a value that will not change for the life time of the expression.
  • NewArrayExpression – This represents the creation of an array and its content within the expression.
  • MethodCallExpression – This allows the expression to call external methods, so far I’ve only been able to get this to work for public statics but this is not a major problem
  • Finally, LambdaExpression – This allows us to pull all of elements together and compile it into a lambda or, as in this case, a delegate of the type supplied, so long as the return type and parameters match.

Now we know what we are going to be use, lets look at how we generate the factory:

public virtual void RegisterDelegateFactoryForType<TResult, TFactoryDelegateType>()
{
    MethodInfo delegateInvoker = typeof(TFactoryDelegateType).GetMethod("Invoke");
    ParameterExpression[] factoryParams = GetParamsAsExpressions(delegateInvoker);

    //Build the factory from the template
    MethodInfo mi = typeof(ClassFactory).GetMethod("FactoryTemplate");
    mi = mi.MakeGenericMethod(typeof(TResult));

    Expression call = Expression.Call(mi, new Expression[] {Expression.Constant(this),
        Expression.NewArrayInit(typeof(Object), factoryParams)} );

    TFactoryDelegateType factory = Expression.Lambda<TFactoryDelegateType>(call, factoryParams).Compile();

    _typeFactories.Add(typeof(TFactoryDelegateType), factory as Delegate);
}

private ParameterExpression[] GetParamsAsExpressions(MethodInfo mi)
{
    List<ParameterExpression> paramsAsExpression = new List<ParameterExpression>();

    Array.ForEach<ParameterInfo>(mi.GetParameters(),
        p => paramsAsExpression.Add(Expression.Parameter(p.ParameterType, p.Name)));

    return paramsAsExpression.ToArray();
}

public static T FactoryTemplate<T>(ClassFactory factory, params Object[] args)
{
	return factory.ManufactureType<T>(args);
}

Starting at the top we use the MethodInfo for the Invoke method of the delegate to get the all the parameters for the required delegate.  We then get a MethodInfo for a template method that uses generics, it is important at this point we replace the generic parameters with the concrete types otherwise the compiling of the lambda expression to the delegate will fail.  It then sets up the call to the template factory method, builds the correctly typed delegate and adds it to a collection of prebuilt delegates ready to be passed into constructors.  This expression tree basically builds a lambda expression that looks like the following:

delegate myInterface myInterfaceFactory(String a, String b)

//transform to

(String a, String b) => FactoryTemplate(classfactory, a, b);

Memory and Performance Considerations

Before wrapping up, lets just reflect over the performance and memory implications of this.  We are using delegates and statics, a typical recipe for disaster in the managed world but fear not.  The use of the constant expression that relates to the ClassFactory effectively adds a new root to the ClassFactory instance but the class factory object holds the roots to the delegates.  This means before the ClassFactory instance goes out of scope we need to dispose it correctly to ensure we release the roots to the delegates.  In reality, this is unlikely to cause us problems as we would normally want the ClassFactory instance to last as long as the application.

What might be a performance problem though is the potential boxing and unboxing of value types that is caused by passing parameters into the FactoryTemplate method as an Object array.  There is no easy answer to this because when we don’t know up front how many parameters we are going to need or what type.  We could, however, make a micro optimisation to avoid it by offering several overloads that take between 0 and 4 parameters before falling back on to a params function with the idea that most people won’t need that many.  I will leave the exercise of converting the expression tree to use the correct generic template factory to the reader :)

Although I haven’t committed the latest changes, I do have this 90% done and I will push to CodePlex soon.  I am going to pull out he DI stuff I’ve been working on and host it at BitBucket.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)

Written by Will

February 11th, 2010 at 12:03 pm

Posted in .NET, C#

Tagged with , , ,

Detangling Service Locator From Dependency Injection

with 5 comments

I’m sure like many exploring Dependency Injection (DI) for the first time the biggest problem I had, was how to rid the world of those pesky little new statements.  The first application I tried to use DI with in anger was DirLinker.  I had no prior knowledge of any of the DI frameworks and started looking at patterns that would help me remove all the new statements.  Unfortunately, I hit up on service locator and the rest is a mess history.  I ended up with code the looks like the following inside DirLinker:

IFile aFile = ClassFactory.CreateInstance<IFile>();
aFile.SetFile(file);

There is a couple of things that bother me about this.  First is the static, I’m not a fan of statics at all, infact, I hate them.  Next is the SetFile call, for any meaningful work to be done with this class you need to pass in a filename and it should be a constructor argument.  In all fairness the SetFile problem is more to do with the limitations of my roll your own DI framework than anything else.

In spite of my niggling doubts, it worked so I left it alone.  Fast forward to last week when I came across a blog post entitled Service Locator is an Anti-Pattern.  This confirmed my initial discomfort and highlighted a problem I hadn’t thought of, namely that the class doesn’t advertise its dependencies.  Very bad for reuse.

Factories

As the blog post suggests a better way of doing this would have been to use factories so lets go over a couple of examples on how this could be achieved. 

Virtual Instance Methods

This is a method I would use when trying to a create a seam in legacy code to inject a dependency for unit testing.  To do this you create a virtual method on the class that needs to create the object. In the unit test inherit from the class under test and override the factory method to return your mock or stub.  For example:

public class FileConsumer
{
    protected virtual IFile GetFile(String filename)
    {
        return new FileImp(filename);
    }

    public void DoSomething()
    {
        IFile fileA = GetFile("test.txt");
        IFile fileB = GetFile("test2.txt");
        //uses files
    }
}

[TestFixture]
public class FileConsumerTests : FileConsumer
{
    protected override IFile GetFile(string filename)
    {
        return new FileMock(filename);
    }

    [Test]
    public void DosomethingTest()
    {
        //Code to perform test
    }
}

This is good because it’s clear to any maintainer what the dependency is and where it is coming from. 

Abstraction Factory Pattern

This would loudly and proudly advertise the dependency on the ability to create IFile objects.  It works by creating a class with methods solely responsible for creating IFile objects and then taking this as dependency for your class.  For example:

public interface IFileFactory
{
    IFile CreateFile(String filename);
}

public class FileFactory : IFileFactory
{
    public IFile CreateFile(string filename)
    {
        return new FileImp(filename);
    }
}

public class FileConsumer
{
    IFileFactory _fileFactory;

    public FileConsumer(IFileFactory fileFactory)
    {

        _fileFactory = fileFactory;
    }

    public void DoSomething()
    {
        IFile fileA = _fileFactory.CreateFile("test.txt");
        IFile fileB = _fileFactory.CreateFile("test.txt");
        //uses files
    }
}

This is the pattern recommended by the blog post and it covers all the things I don’t like about Service Locator.  But I think we could take advantage of some of C#’s language features and the fact we are creating objects via a container to achieve something similar but with less code.

Delegate Factories

Before I go into this a little disclaimer, this is totally and utterly inspired by Autofac’s wonderful generated delegate factory functionality, you can read more about it here.

OK, honesty out of way lets look at what the container knows and what it does.  The DI container knows what Interfaces should map on to what concrete types and it has the ability to resolve constructor arguments for types that it knows about.  This is just a generic version of a factory so it makes sense to take advantage of it.

One way would be to use Func<TResult>() (and its friends).  If the class being constructed requires a constructor parameter of Func<TResult> where TResult is the required interface, the container could generate an appropriate delegate at runtime and pass it in.  For example:

   public class FileConsumer
   {
       Func<IFile> _fileFactory;

       public FileConsumer(Func<IFile> fileFactory)
       {

           _fileFactory = fileFactory;
       }

       public void DoSomething()
       {
           IFile fileA = _fileFactory();
           IFile fileB = _fileFactory();

           //uses fileA
       }
   }

This would require a slight modification to the container and could be extended by the use of Func<T, Tn, TResult>(T value, Tn valuen).  The container would match the parameters to a suitable constructor. 

This is quite a powerful and time saving concept but I don’t like the vagueness of Func<TResult>(), it’s not as expressive as it could be.  So the method I have chosen for DirLinker is to use strongly typed delegates and generate them at runtime from the container.   It works in the same manner only you declare the delegate up front and pass them in as an argument.  This, also, requires a bit of configuration but the pay off is worth it.  I have started work on the implementation for DirLinker so this example is taken directly from the unit tests and can be found here

interface ITestClassWithDelegateFactory { ITestClassFactory Factory { get; set; } }
delegate ITestClass ITestClassFactory();

class TestClassWithDelegateFactory : ITestClassWithDelegateFactory
{
     public ITestClassFactory Factory { get; set; }
     public TestClassWithDelegateFactory(ITestClassFactory delegateFactory)
     {
         Factory = delegateFactory;
     }
}

[Test]
public void ManufactureType_Type_delegate_factory_manufactures_correct_type()
{
	IClassFactory testClassFactory = new ClassFactory();

	testClassFactory.RegisterType<ITestClass, TestClass>()
                .WithFactory<ITestClassFactory>();

	testClassFactory.RegisterType<ITestClassWithDelegateFactory, TestClassWithDelegateFactory>();

 	ITestClassWithDelegateFactory manufacturedType =
			testClassFactory.ManufactureType<ITestClassWithDelegateFactory>();
	ITestClass instance = manufacturedType.Factory();

	Assert.IsInstanceOf(typeof(TestClass), instance);

}

Admittedly there is quite a lot going on here but the main points are we registered a type and factory in a strongly typed manner with the container.  Then pull it out and use it to create an instance of a different type.  I am going to cover this in quite some detail along with the how to create strongly typed delegates at runtime in my next post.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)

Written by Will

February 9th, 2010 at 7:42 am

Posted in .NET, C#, DirLinker, Unit testing

Tagged with , ,

Don’t Be a Fool, Wrap Your Tool!

without comments

As a hormone ravaged teenage, I squirmed uncomfortably as parents, teachers and community health practitioners imparted the words of wisdom “Don’t be a fool, wrap your tool”.  So it is fitting, I’m equally as squeamish when coming across the same advice as an adult. 

What am I talking about?  Creating wrappers for anything at all on the boundaries of your code for the purpose of unit testing.  I’ve been struggling to think of a succinct way to explain this so I decided to go through a worked example.

Consider the following code:

   public class CommandReceiver
    {

        public void WaitForMessage()
        {
            using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.In))
            {

                // Wait for a client to connect
                Trace.Write("Waiting for client connection...");
                pipeServer.WaitForConnection();

                Trace.WriteLine("Client connected.");
                try
                {
                    // Read user input and send that to the client process.
                    using (StreamReader sr = new StreamReader(pipeServer))
                    {
                        String command = sr.ReadLine();
                        DispatchCommand(command);
                    }
                }
                catch (IOException e)
                {
                    Trace.WriteLine("ERROR: {0}", e.Message);
                }
            }
        }

        private void DispatchCommand(String command)
        {
            //Knows how to deal with messages.
        }
   }

Looking at this code there is a number of problems but lets focus on the unit testing problems.  It is impossible to unit test this code because it creates a real pipe server and waits on a blocking call before continuing.  This means to test this code we need to create a pipe client, connect and all this would have to be threaded because of the blocking call.  Of course, this would make a good integration test because it tests that the pipe is connectable and receives a string message.

Before we set about making this code more unit test friendly, lets look at what we are trying to unit test.  We are trying to test that the WaitForMessage method can receive a string and pass it on.  For us to do this we need to abstract the pipe and stream out.  Also, while we are there lets remove the DispatchCommand method since it violates SRP and it would be more testable on its own.  So lets take a second stab at the code.

public interface INamedPipeServer : IDisposable
{
    void WaitForConnection();
}

public class ManagedNamedPipeServer : INamedPipeServer
{
    private NamedPipeServerStream _pipeServer;

    public ManagedNamedPipeServer(String name, PipeDirection pipeDir)
    {
        _pipeServer = new NamedPipeServerStream(name, pipeDir);
    }

    public void WaitForConnection()
    {
        _pipeServer.WaitForConnection();
    }

    public void Dispose()
    {
        _pipeServer.Dispose();
    }

}

public interface IStreamReader: IDisposable
{
    String ReadLine();
}

public class ManagedStreamReader : StreamReader, IStreamReader
{
    public ManagedStreamReader(Stream stream) : base(stream)
    {}
}

public class CommandReceiver : ICommandReceiver
{
    INamedPipeServer _NamedPipeServer;
    ICommandDispatcher _CommandDispatcher;

    public CommandReceiver(INamedPipeServer pipeServer, ICommandDispatcher dispatch)
    {
        _NamedPipeServer = pipeServer;
        _CommandDispatcher = dispatch;
    }

    protected virtual IStreamReader GetStreamReader()
    {
        //Code to create a stream reader from the pipe
    }

    public void WaitForMessage()
    {
        // Wait for a client to connect
        Trace.Write("Waiting for client connection...");
        _NamedPipeServer.WaitForConnection();

        Trace.WriteLine("Client connected.");
        try
        {
            // Read user input and send that to the client process.
            using (var sr = GetStreamReader())
            {
                String command = sr.ReadLine();
                _CommandDispatcher.DispatchCommand(command);
            }
        }
        catch (IOException e)
        {
            Trace.WriteLine("ERROR: {0}", e.Message);
        }
    }
}

This is where my uncomfortable squirm returns because my “keep-it-simple” sense is tingling.  I’ve just taken a fairly simple class that was around 30 lines and turned it into 75 lines of complicated OOP code.  I would hope that anyone reading this can follow it but in a real project this will probably be split over several files and the two styles of wrapping (because NamedPipeServerStream is sealed) can add significant cognitive burden to understanding what is going on.

What benefits does this bring?  It allows us to unit test that we read a string and pass it on to a dispatcher.  But I would go out on a limb and say that this is least likely of all the code in that class to go wrong.  The real problem area will be in connecting the pipe and reading from it.  We can make assumptions about failure conditions from the docs but as we all know docs != reality. 

Is the abstraction here a benefit? In my opinion, not to the extreme level we have. The abstraction at ICommandReceiver will allow us to swap out how the application does IPC calls making it flexible in the future and, as I eluded to above, the unit test ‘coverageability’ is of lower value in this instance. 

My point in all this rambling nonsense?  In an ideal world we would have both sets of tests and the unit tests would cover all the error conditions but in the real world we only have a finite and, usually, short amount of time with pressure from project managers and deadlines.  So we have to look at what will bring us the most value and focus on that.  I believe at application boundaries like this one we should focus our attention on writing integration tests because it will bring us more value in the long run.  I would not shun unit testing entirely and in this example the ICommandDisptacher and other supporting classes would have a full suite of unit tests.

As a side note, my final version of the code would be a mid way point between the two listings.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)

Written by Will

February 5th, 2010 at 9:03 am

Posted in .NET, C#, Unit testing

Tagged with , ,

Why DirLinker Doesn’t Support XP

without comments

I posted up the Directory Linker CodePlex project a little over 2 weeks ago and it has clocked up a reasonable 103 downloads in that time.  Last night I was glancing over where the traffic came from on the stats page and a lot of referrals have come from this review site, they state that:

The app works on Windows 7 and Vista only, support for Windows XP is planned in the near future.

This is incorrect and maybe I should have been more clear that Directory Linker will not support XP unless there is some overwhelming outcry for it or someone else does it.

Why?

First for selfish reasons, I don’t use a machine that has XP installed anymore, furthermore, I would encourage anyone on XP to upgrade for security if nothing else.  At the end of the day, I created this tool for my use and I don’t use XP.

The second reason is technical, without going to far in, symbolic directory links have been in NTFS for quite a while but only got ‘first class’ support by the OS recently.  Previous to Vista they were called Junction Points and had all kinds of weird side effects (more details here).  Also, the API calls used by Directory Linker to create the symobolic link is only supported by Vista and above.  It is technically possible to do the same for XP and it is not difficult but Directory Linker simply doesn’t do it.

I hope that clears things up, also if you find a download link for Director Linker that links to SoftSea in anyway please do not use it.  If you’re not a programmer it’s safe to stop reading now.

Fork You!

Well, I rather you didn’t.  I will happily accept any patch that is submitted to the project to do this.  To help you out here is a quick overview on how to do  it.

  1. Locate FolderImp.cs and make the CreateLinkToFolderAt method virtual.
  2. Create a new class that inherits from FolderImp and name it to show it is for XP.
  3. Override only the CreateLinkToFolderAt and add the code to create a link in XP (Tip: start at DeviceIoControl).
  4. Open Program.cs and go to the FillIoCContainer method and add code to conditional select the correct IFolder class when the application starts.

Quite simple really.

VN:F [1.9.3_1094]
Rating: 3.0/5 (1 vote cast)

Written by Will

February 3rd, 2010 at 9:39 am

ShutdownEx, I wouldn’t let you beat me!

with 2 comments

The Problem

In my haste to leave the office I will often click shutdown on my laptop then shut the lid.  The laptop will probably shutdown successfully 1 in 5 times for two main reasons:

  • The laptop will hibernate or suspend before it can shutdown
  • Windows will be waiting on applications to close that are waiting for save dialogs etc to be dismissed.

I have two possible solutions, create an application that modifies this behaviour or be more patient.

Software Solution

Lets face it I was never going to change so I started to put some thought in to an application to modify the behaviour and ShutdownEx was born.  Not long ago I created a shutdown timer app so I had all the interop calls required to shutdown the machine and a quick search of MSDN turned up the WM_POWERBROADCAST message for intercepting suspends.

Armed with this I created a quick plan and requirement list in my mind:

  • The app should be standalone, no install, no dependencies, just work.
  • A simple Winform application, the main form would have a couple of options and a button to shutdown the system.
  • When shutdown was invoked from it, it would listen for the WM_POWERBROADCAST message and stop it from suspending.
  • If the system didn’t shutdown within a set time out, it would recall shutdown with the force shutdown flag.

Before even writing a line of code I spotted a major flaw with this.  In order to wait for the timeout the application would have to ignore the first WM_QUERYENDSESSION message that came in, meaning it would always timeout and we would be forced to shutdown when the second message came.  This introduces two massive problems

  1. We’re holding up shutdown meaning it will always take longer when we’re running.  Not cool!
  2. When we have been forced to shutdown, a small window of opportunity will open up for the suspend event to come in.

The second problem is a deal breaker, the whole point of the application is to stop the suspend from taking place during shutdown.

Revised Solution and Compromising My Own Requirements

I came up with two more solutions.  The first, and ultimately still flawed approach, keeping to the simple WinForm one executable approach.  I could enumerate all process running in my session and keep polling till everything has closed then close gracefully myself allowing the shutdown to continue.  While the majority of the time, I feel, it wouldn’t send out the force shutdown there is still a sizeable (measured in seconds) gap when the suspend event could still take place.  Breaking one of the main requirements.

The second approach is to ditch the requirement of a standalone WinForm applications and go to a Windows Service.  The Windows service will not need to end when the session does so I don’t have to worry holding up the shutdow.  This, also, means I have a longer window of opportunity to block the suspend message.  With the theory being when I go down, Windows will be taking its subsystems down and the message will be ignored anyway.  The big downsides are I now have to install the service from an MSI and I’ve just added a new and very complex layer to my simple application.

Complexity from a service point of a view because I need to create a hidden Window so I can listen for Windows Messages. I will still need a UI for the user to shutdown with so I need to have comms between the service and UI, a named pipe more than likely.  Throw in any permissions problems I might have when running as system and it’s now quite far from the quick app with lots of existing code samples I first thought of.

The worst part of it is, I’ve started it now and I have to finish to prove it can be done.  Although, I will never be happy with the comprised requirements.

Also, I have a private SVN repo I work against but seriously considering moving to GitHub from the start of development, would you be interesting in seeing it take shape?

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)

Written by Will

January 19th, 2010 at 7:16 am

Posted in .NET, C#

Creating Symbolic Directory Links a GUI

with 5 comments

Introduction

I’m a massive DropBox fanboy, I just love it, love it, love it.  Up until recently I’ve used it by dragging and dropping stuff in or saving directly into it from the application.  Then I came across this post by GrumpyDev which describes how to move Windows Live Writer draft posts into Dropbox by using symbolic directory links.

I hadn’t thought of this before, instead of remembering to move my files about or saving them to places other than the standard documents folder, which I always forget to, I could create symbolic directory links for all the common things I use.  I went a bit mad at this point and moved all kinds of folders inside my Dropbox.

The only thing about doing this is, the process is a bit clunky.  You have to:

  1. Create the target
  2. Copy any existing content to the target
  3. Delete the folder you want to be a link
  4. Start cmd.exe and then enter the mklink command along with the full paths of the folders you want to link

I was very surprised to find there is no pretty little one click GUI to do this.  So I decided to create one, I was looking for a test app to allow me to practice with TDD and MVC in Winforms and this was a perfect opportunity to.

DirLinker

screeny

So there it is, a very basic UI that allows you to enter where you want the link and where you want to link to.  You can just delete the link place or copy the contents over first.  Use these options at your own risk, I will not be held responsible for any data loss.

Requirements:

  • Vista or later (I have tested it on Vista x86 and Win7 x64)
  • .NET 3.5
  • Admin rights

Download links:

This can now to be downloaded from CodePlex: http://dirlinker.codeplex.com/

DirLinker

DirLinker – source (I do have this in SubVersion at Unfuddled but I can’t make the repo public.  When I remove the dependency on Telerik to build, I will move it to CodePlex)

This is only the first version and I have a list of planned updates, which includes:

  • A full UI review and remove the dependency on Telerik - Updated 17/01/2010:  http://www.humblecoder.co.uk/?p=59
  • Add rollback support when an operation fails -
  • A general tidy up
  • Add a check for .NET 3.5 at start up
  • XP support (maybe)

Download, enjoy and please report any bugs.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)

Written by Will

January 5th, 2010 at 4:19 pm

Posted in .NET, C#, DirLinker

Diagnosing Non Starting .Net Applications

with 2 comments

Recently I’ve been working on an application that uses the Telerik Winform controls.  Today I was happy enough with it to start testing it on various environments so I performed a release build, got the non framework referenced DLLs, packaged them up into a zip and copied it to the target machine.  Happy I had everything I fired up the application on the test machine, only to be met with this dialog:

rubbishError

I don’t know about anyone else but this is completely useless.  It didn’t tell me anything at all about what was wrong.  So some basic debugging to start with.

  • Correct .NET version installed? – Yes.
  • Built for the correct architecture (the VM was x64)? – Yes, Any CPU.
  • Is it an unhandled exception at application start? – No, it’s the wrong dialog.
  • Google the details?  Nothing relevant.

Just a quick note on ‘Any CPU’, if we had of been using Interop during the app starting up then this could have been a real problem.  Sometimes a dying interop can take out the app bypassing the unhandled exception event.  So it is definitely worth while looking more closely at if you have interop at startup.  I would normally check this by targeting x86 and x64 independently and seeing if only one fails.

Everything appeared OK at this point so it was time for some more hardcore debugging tools.  First up was ProcMon, this a fantastic tool that provides tons of information.  It is quite easy to get lost or over awed when you first generate a log but it has an excellent filter system that is extremely powerful.

I fired up ProcMon, filtered on my process name and started my app.  The log clearly shown the problem:

procmon

(Highlighting added for emphasis of the problem.)

The log is showing the app, unsuccessfully, searching for a DLL named TelerikCommon.  It turns out that even though I had all my referenced DLLs they themselves had references and dropping in the missing one made everything work.

My next step would have been to use WinDbg to see what was going on.  WinDbg, while powerful, has an extremely steep learning curve that I’m still fighting with.  So thankfully we didn’t have to go there.

Not looking to a portion blame here but the dialog could have been better as to what the problem was.  Maybe if I’d read the Telerik documentation this dependency would have been made clear or they would have a redistributable run time you need to install.  But I wanted to keep the size down as much as possible so only grabbing the ones I need is the best way to go.

VN:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)

Written by Will

November 30th, 2009 at 12:55 pm

Posted in .NET, Debugging, ProcMon

Tagged with

Get Adobe Flash playerPlugin by wpburn.com wordpress themes