Upgrading to .NET framework 2 and Visual Studio 2005

August 26, 2006

Considering the number of lines of code we have written in .net 1.1 I must say I’m impressed that the upgrade to .NET 2 was so relatively painless. We cover a large range of programming areas (windows forms, remoting, reflection, data access, reporting etc.) and most projects ran straight out of the box under .NET 2. That said there have been a few issues some of which unfortunately have been runtime issues which were spotted by the end users.

If you are considering an upgrade fully test the converted solutions as if there are any issues they’ll mostly not stop the project compiling – just cause problems when running!

Read the rest of this entry »

Advertisements

Using reflection to get a resource from the new Properties.Resources object

August 20, 2006

VS 2005 has added the extremely handy Properties.Resources object for any bitmaps etc. which you care to add to your project resource file. This is very easy to use within a single assembly, simply reference the correct property of the Resources object. e.g.

Image myResourceImage = (Image) Properties.Resources.myResourceImage;

(We need the cast here to convert the Bitmap resource into an image).

This is all well and good, but I recently came across the need to get a resource object across assembly boundaries using reflection. This caused a bit of noodle scratching. I was able to get my hands on the Type object for the Resources object, but the type appeared to have no properties. After a bit of snooping in the Object Browser I learned that the resources are marked as internal by VS and so the specific binding flags BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static need passed to the GetProperty method of the Type object.

I ended up with the following method which scans all loaded Assemblys for a matching resource of a given name.

        public static object CreateResourceByType( string resourceName )
{
foreach ( Assembly ass in AppDomain.CurrentDomain.GetAssemblies() )
{
try
{
foreach ( Type type in ass.GetTypes() )
{
if ( type.Name == “Resources” )
{
PropertyInfo p = type.GetProperty( resourceName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static );

if ( p != null )
{
object field = p.GetValue( null, new object[ 0 ] { } );
return field;
}
}
}
}
catch ( System.Reflection.ReflectionTypeLoadException )
{
System.Windows.Forms.MessageBox.Show( ass.FullName );
}
}

throw new ArgumentException( “Resource ” + resourceName + ” could not be found.” );
}