Posts Tagged ‘dotnet’

CompulsoryCat 1.1

October 21st, 2010

Just released version 1.1 of CompulsoryCat on google code.

It is a helper lib for getting the names of methods, classes, properties and other stuff out of the methods, classes etc.  It uses lambda or reflection to be as safe as possible.

It is unit tested and has a small exe to show a few examples of its use.  There is also a help file.

Exception: Error 1083: The executable program that this service is configured to run in does not implement the service.

September 30th, 2010

In short: verify that the service name is correct.  Totally correct.

Longer:

Debugging windows services written in dotnet can be hard.  They have no GUI and have to be installed by a semi secret process.  Then they have to be started by a system call.  And if the start fails it is not necessarily possible to uninstall the service without rebooting.  The CL.exe doesn’t work and hacking the registry doesn’t work.

Today I spent hours tracking down a bug that surfaced with a “Error 1083: The executable program that this service is configured to run in does not implement the service.” when starting the service.  In the end I found out that the ServiceName was incorrect.

To be honest I got some clues, in one place it said MyMailer instead of MyMailerService.  I couldn’t be sure if this was correct or not since I had inherited the project and my search turned out nothing so I dropped it.

By (almost) chance I checked into the automagically created MyMail.designer.cs file and noticed this.ServiceName=”MyMailer”.  Which, it turned out, was the culprit.

I learned a trick on the way.  The service has 30 (I believe) seconds to start.  If it doesn’t fulfill it is shot down by Windows.  When I started the process it failed and I got a question whether I wanted to debug it.  Unfortunately it takes more thatn 30 s to open my VS2010.  So I started VS as administrator (necessary in Win7) and loaded the project.  When I then started the service I got the question whether to attach and I did.  Two seconds of work and I got a highlighted row at the exact point.

A .NET Framework error occurred during execution of user-defined routine or aggregate “XXX”: System.InvalidOperationException: The context connection is already in use.

September 2nd, 2010

If you are working with CLR in SQLServer you might run into

A .NET Framework error occurred during execution of user-defined routine or aggregate "MyCLRMethod":   System.InvalidOperationException: The context connection is already in use.

I cannot say this is the solution every time but it worked for me.  Look down to the top of the stack (furthest down in the text) and you get some more clues.

Msg 6522, Level 16, State 1, Line 1
A .NET Framework error occurred during execution of user-defined routine or aggregate "MyCLRMethod":
System.InvalidOperationException: The context connection is already in use.
System.InvalidOperationException:
 at System.Data.SqlClient.SqlInternalConnectionSmi.Activate()
 at System.Data.SqlClient.SqlConnectionFactory.GetContextConnection(SqlConnectionString options, Object providerInfo, DbConnection owningConnection)
 at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
 at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
 at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
 at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
 at System.Data.SqlClient.SqlConnection.Open()
 at Elvis.DatabaseCLR.UserDefinedFunctions.GetNextSampleID(DateTime readDate, Int32 meterID, Boolean useNextMeter)
 at Elvis.DatabaseCLR.UserDefinedFunctions.ConsumptionForNewMeter(Int32 sampleID, DateTime readDate, Int32 meterID, Decimal meterCoefficient, Int32 previousMeterConsumption, DateTime presentationDateOfSample)
 at Elvis.DatabaseCLR.UserDefinedFunctions.MyCLRMethod(Int32 sampleID, DateTime presentationDate, DateTime readDate, Int32 meterID, Decimal meterCoefficient, Boolean newMeter)

.

The MyCLRMethod calls two more methods until Open is called.  Playing around I found that I couldn’t open a connection if one already was open.  It sounds right since one of the deals with CLR in SQLServer is that we already have a connection.  The resolution is to tidy up the code so we only open the connection once, or open/closes it over and over again.

Tricks I used:
– When you get the error in your applicaiton copy the SQL string to your query editor and run it from there.
– Press F5 in Visual studio and have Visual studio deploy the CLR for you.  But use the query tool to run the query.  The error message is the same.
– Debug-through-printf, or “throw exception” in this case.  Drop in a throw-exception to find out exactly which Open call is failing.  The F5-and-wait and then run query takes a while.  If you have a logging possibility it is handy now.

Cancel a tab change in Dotnet Winforms

August 24th, 2010

For Dotnet2 and lower there was no easy way of stopping a user from switching a tab in a tab control.  I have written a solution in Dotnet compact framework (2?) that inherited from TabControl and overrided a couple of methods that together with a flag or two made it possible to cancel tab switching.  If I recall correctly it never stopped the control from blinking but it did it’s job.  It wasn’t hard but it took some hours.  If you are forced to implement this in Dotnet2 you have to inherit, the overridable methods used do not all send an event.

With Dotnet 3 to the current 4 it is easier.  Just associate a method with the Selecting event.

I did it in Dotnet3.5 and noticed some flickering when trying to, and cancelling, the change of tab.

Cannot serialize

August 19th, 2010

Or Can’t serialise – whatever you prefer.

When using Dotnet and the built in serialiser from Microsoft it sometimes doesn’t work.  Just so.  To make it more complex the error message sometimes doesn’t say anything either, just something like FileNotFoundException.  Sucks.

One solution might be to use the XmlSerializerPreCompiler tool from SellsBrothers available gratis and with source code.  It is downloadable here.  The download is dotnet2 but I updated it to 3.5 easily with Visual Studio 2010.

There is GUI called XmlPreCompiler for it too.

You might run into that the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion as to have a DWord called EnableLog set to 1.  The XmlPreCompiler has to be restarted to understand this key has changed.

If you are working with Dotnet > 2 you have to compile the GUI from source.  It is not difficult – the Visual Studio solution file is in the source code.

When running the GUI tool and your assembly is referring to another assembly (DLL has reference to other DLL) it is important that the GUI tool’s exe is in the same folder as the assemblies you are looking at.  Unless the other assemblies are in the GAC I suppose…

Note that you might have to restart Visual Studio 2010 when up/down grading dotnet version.  It seems like VS holds reference to files with the earlier version.  This has happened to me both when downgrading 4->3.5 and upgrading 2->3.5.

This was a lot of chatter about the apps and problem but I ran into them all right now.  And if You are here – so might you.  Happy hacking!

(My problem in this case was that I had set Visual studio to break on all thrown exceptions.  Took me six hours to figure out…)

throw;

July 12th, 2010

Avoid

try{
    ...
}catch( Exception exc ){
    ...
 throw exc;
}

since it destroys the exception stack.

Instead write

try{
    ...
}catch( Exception ){
    ...
 throw;
}

If you don’t understand what “destroying the exception stack” means you probably don’t want to destroy it and this recommendation is even more something to heed.

To get to the exception use $exception.

$exception and $ReturnValue

July 12th, 2010

In dotnet one can write

try{
    ...
}catch(Exception){
   throw;
}

which gives two debugging tools.  The first is the ability to set a break point on the catch line.

Note how I haven’t written catch( Exception exc) but only catch( Exception).  This makes us avoid a compiler warning because we don’t use the exc variable.  Which brings us to trick number two in Visual studio: Since we don’t have a variable with the exception instead write $exception in the immediate window or the quickwatch window.  $exception brings forward the [hidden] exception reference.

Also note how there is no variable behind the throw statement.  This makes the framework hide the catch/throw and leave the stack intact.

Update: In VisualStudio2010 it looks like it is enough to write exception in the quickwatch window.

With dotnet 4.5.1? one can write $ReturnValue the same way to get to the… the… the… return value!

List of lists and dictionaries in dotnet

June 2nd, 2010

Update: I wrote a longer article here.

List<T> is the work horse of list handling in dotnet.  But there are several more to choose from; ArrayList, Hashtable, SortedList, DictionaryEntry, ListDictionary, StringCollection, NameValueCollection, StringDictionary, HybridDictionary andOrderedDictionary for instance. Several of these are replaceable by generic lists so don’t memorise them.

Here is a link to a better explanation: http://www.platinumbay.com/blogs/dotneticated/archive/2007/06/08/hashtables-and-stacks-and-linkedlists-oh-my.aspx

*Update*: I wrote some more, and later, info here.

Get calling method’s name automatically in dotnet

January 16th, 2010

Way too many times have I written

void MyFunction( int aNumber){ MyHomemadeLogClass.Logg( "MyFunction", "aNumber=" + aNumber.ToString()); ...}

to get logging functionality.

It would be so nice to just write

void MyFunction( int aNumber){ MyHomemadeLogClass.Logg(); ...}

It is no hard to do. Use reflection to get the call stack to get to the method and the parameters. Convert all this to a readable string.
Unfortunately it is not that easy to log the contents of the parameters, one has to get into some sort of debugger area to do that.

 class ReflectionUtility {     private static System.Reflection.MethodBase GetCallingMethod()     {         return new System.Diagnostics.StackTrace().GetFrame(2).GetMethod();     }     public static string GetCallingMethodFullNameReturnParametertypes()     {         return MethodFullNameReturnParametertypes(GetCallingMethod());     }     private static string MethodFullNameReturnParametertypes(System.Reflection.MethodBase method)     {         return string.Format("{0} {1}.{2} ({3})",             ((System.Reflection.MethodInfo)method).ReturnType,    // System.Void, System.Int32 etc.             method.DeclaringType.FullName,   // MyNamespace.MyClass.             method.Name,   // MyMethod.             string.Join(",", method.GetParameters().Select(p => p.ParameterType.ToString() + " " + p.Name).ToArray())   // () or (int) or (int,string) etc.             );     } }

To use this in a Logging class one must implement a GetCallingCallingMethod or even worse, but it would make this example hard to read.

One can use the Conditional attribute to avoid the call when not debugging.

I also put the code on pastebin to make the copy-paste easier. (I have yet to find a good way to present code.)

Update: go to http://compulsorycat.googlecode.com for the source code in a LGPLd project.

Catch property, field and method name changes compile time in dotnet (RTTI)

January 6th, 2010

When you want to populate a dropdown listbox with customers

class Customer{ int Id; string Name; ...}

and have to write

myDropdownListbox.DisplayMember = "Name";myDropdownListbox.DataMember = "Id";

or

myGridColumnCustomerName.DatatMeber = "Name";

you really get a sour taste in your mouth.

Having magic strings like above spread in your code is really bad since it always compiles but might fail runtime. This means more manual tests. Which in turns means a certain friction against renaming properties while refactoring.
I have been in way too many projects where one table has a field ItemNumber when it should have been ItemCount and where some fields are called Nr while another Number and these names are spread up in the layers to reach the presentation layer where they surface as magic strings like the examples above.

Luckily there is a solution in Dotnet 3 with LINQ. It isn’t the prettiest but it fails compile time when it should and that is considered a good thing.

( I won’t bother with explanation – just read the code. )

When you want to populate a dropdown listbox with customers

class Customer{ int Id; string Name; ...}

and have to write

myDropdownListbox.DisplayMember = "Name";myDropdownListbox.DataMember = "Id";

or

myGridColumnCustomerName.DatatMeber = "Name";

you really get a sour taste in your mouth.

Having magic strings like above spread in your code is really bad since it always compiles but might fail runtime. This means more manual tests. Which in turns means a certain friction against renaming properties while refactoring.
I have been in way too many projects where one table has a field ItemNumber when it should have been ItemCount and where some fields are called Nr while another Number and these names are spread up in the layers to reach the presentation layer where they surface as magic strings like the examples above.

Luckily there is a solution in Dotnet 3 with LINQ. It isn’t the prettiest but it fails compile time when it should and that is considered a good thing.

( I won’t bother with explanation – just read the code. )

// The Code.

< 

    class ReflectionUtility
    {

        public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
        {
            MemberExpression body = (MemberExpression)expression.Body;
            return body.Member.Name;
        }

        public static string GetMethodName<T, TReturn>(Expression<Func<T, TReturn>> expression)
        {
            var body = expression.Body as UnaryExpression;
            var operand = body.Operand as MethodCallExpression;
            var argument = operand.Arguments[2] as ConstantExpression;
            var methodInfo = argument.Value as System.Reflection.MethodInfo;

            return methodInfo.Name;
        }

    }


    class MyClass
    {
        public int MyField;
        public int MyPublicProperty { get; set; }
        public  string MyReadonlyProperty { get { return string.Empty; } }
        public int MyMethod() { return 0; }

        private MyClass() { }   // To make sure the class doesn't need a default constructor.
    }


    class Program
    {
        static void Main(string[] args)
        {
            string fieldName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyField);
            Console.WriteLine(string.Format("MyClass.MyField:{0}", fieldName));
            Debug.Assert("MyField" == fieldName);

            string propertyName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyPublicProperty);
            Console.WriteLine(string.Format("MyClass.MyPublicProperty:{0}", propertyName));
            Debug.Assert("MyPublicProperty" == propertyName);

            propertyName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyReadonlyProperty);
            Console.WriteLine(string.Format("MyClass.MyReadonlyProperty :{0}", propertyName));
            Debug.Assert("MyReadonlyProperty" == propertyName);

            string methodName = ReflectionUtility.GetMethodName<MyClass, Func<int>>((MyClass x) => x.MyMethod);
            Console.Write(string.Format("MyClass.MyMethod:{0}", methodName));
            Debug.Assert("MyMethod" == methodName);

            Console.Write(Environment.NewLine + "Press any key.");
            Console.ReadKey();
        }

< }

Honor those who should.  (This link contains a comment regarding generic methods that I’d like to impolement in CompulsoryCat.)

Update: When copy-pasting through manoli.net some angle brackets got dropped. This is, hopefully, fixed now.  Otherwise – get the source here: http://selfelected.pastebin.com/f77563a02

Update:

Check out Compulsorycat.  It is my F/OSS library with some of these functions.

Honor those who should.  (This link contains a comment regarding generic methods that I’d like to impolement in CompulsoryCat.)

Update: When copy-pasting through manoli.net some angle brackets got dropped. This is, hopefully, fixed now.  Otherwise – get the source here: http://selfelected.pastebin.com/f77563a02

Update:

Check out Compulsorycat.  It is my F/OSS library with some of these functions.