Ken Kopczyk

Hurdles in .NET Development

Creating COM Interop Assemblies with .NET 2.0

Posted by Ken on August 18, 2009

If you work with .NET long enough, sooner or later you’ll probably need to leverage older Win32 COM components. To allow the CLR managed code of .NET to communicate with the unmanaged code of COM, a “middleman” in the form of an interop assembly must be created. This can be done via Visual Studio or the Type Library Importer.

Creating an interop assembly with Visual Studio
Enter the “Add reference” dialog of your project, browse for your registered COM server and select it. Now take a look at the properties of the newly created reference. It is actually pointing to a new assembly called Interop.COMServerName.dll: If your COM server is foo.dll, the resulting assembly is called Interop.foo.dll. You will find this assembly in your bin directory after you build.

If your project uses an .snk or .pfx for strong naming, the interop assembly will also be strong named using that file.

A major limitation of this method I found was the fact that you can’t change the version number of the interop assembly. It is always 1.0.0.0. Bummer.

Creating an interop assembly with Type Library Importer
If you need more control, then you should use the Type Library Importer (tlbimp). This application is included with the .NET SDK.

Running the following command will create an interop assembly with a version number of your choosing:
Using our foo.dll example:

tlbimp foo.dll /out:Interop.foo.dll /asmversion:2.0.0.0

If you need the interop assembly strongly named, you can do that also. If you are using an .snk, use the following:

tlbimp foo.dll /out:Interop.foo.dll /asmversion:2.0.0.0 /keyfile:MyKey.snk

If you are using a .pfx for strong naming, it’s a bit trickier. You will also need to leverage the Strong Name Tool (sn) to create a keycontainer:

echo Prompts you for .pfx password
sn -i MyKey.pfx KeyContainerName

tlbimp foo.dll /out:Interop.foo.dll /asmversion:2.0.0.0 /keycontainer:KeyContainerName

echo Housecleaning.  Removes the key container from memory.
sn -d KeyContainerName

Now add it as a reference and you’re good to go!

Posted in .NET SDK, COM Interop, Visual Studio | Tagged: , , , , | Leave a Comment »

Referencing GAC Assemblies With Visual Studio 2005

Posted by Ken on August 15, 2009

In Visual Studio 2005, adding an assembly reference is straight-forward and trivial, that is, unless the assembly you are trying to reference only exists in the GAC. There are a number of tabs in the Add Reference dialog, but they browse assemblies that are all located in standard directories.

Global Assembly Cache
The GAC is special because it allows a pc to store multiple versions of the same .NET assembly. This is made possible by strong naming. More importantly, it provides a centralized location for .NET assemblies that need to be shared across multiple applications.

When viewing the GAC via the Windows shell, you go here: C:\Windows\Assembly. However, the Explorer-like UI actually represents an aggregate of files and folders. Windows is just trying to make it look nice and user friendly for us.

Tricking Visual Studio
To trick Visual Studio into referencing a GAC assembly, you can do the following:
1.) Reference a copy of the assembly that is located outside of the GAC via the Add Reference dialog. You can throw a copy on your Desktop and then reference it from there. It doesn’t matter what the file’s location is.
2.) Install the assembly into the GAC. There are a number of ways to do this. The easiest way is to use the “Microsoft .NET Framework 2.0 Configuration” app. You can find it by going to Control Panel –> Administrative Tools. Once in the app, click “Manage the Assembly Cache” and then “Add an Assembly to the Assembly Cache.”
3.) Delete the assembly file that you referenced in step 1. Go into Visual Studio and refresh the project. The path of the reference should have automatically changed over to its GAC location (C:\Windows\assembly\…).
4.) You may want to set the reference’s “Copy Local” property to False so that the build does not produce a copy of the GAC assembly in the bin folder (to avoid confusion). In doing so, you can be confident that your app is in fact hitting the GAC!

Posted in Visual Studio | Tagged: , | 7 Comments »

Impressive (and Free) WinForm Controls!

Posted by Ken on February 25, 2009

Recently, I was searching for a third party WinForm component solution in an attempt to make my application look enterprise worthy.  Doing some googling yields all the heavy hitters:  Telerik, ComponentOne, etc.  These are very nice, but come at a hefty price (about $1000 per seat).  Digging deeper, I stumbled upon the Krypton Toolkit from ComponentFactory.  

For a freebie suite of controls, I was impressed.  The toolkit includes all your basic controls (Label, ComboBox, etc), 38 in all, and are very customizable.  You can also apply out of the box themes, such as Office2007, also free.  It integrates seemlessly into Visual Studio (I was using VS2005) and includes a very nice demo app that shows off what all the controls can do.

Also in the Krypton family are the Ribbon, tab control, and workspace control.  These are upgrades that you have to pay for, but still cheap when you consider all the very expensive alternatives out there.

Next time you are building an little app from the ground up, consider using these controls.  You should be able to make your app look a ton better at no extra cost.

Bookmark and Share

Posted in WinForms Components | Tagged: | Leave a Comment »

My New Favorite Regular Expression Tester

Posted by Ken on February 3, 2009

Awesomeness —> http://www.gskinner.com/RegExr/

Use it. ‘Nuf said.

Bookmark and Share

Posted in Regular Expressions | Tagged: | Leave a Comment »

Fun With the “ref” Keyword

Posted by Ken on February 3, 2009

By default, parameters are passed by value in C#.  Passing by reference requires the “ref” or “out” keywords to precede the parameter in both the method declaration and the call to the method.  Using “ref” or “out” is fairly straight forward…..or so I thought.

I recently came across two cases where parameters are valid if passing by value, but result in compilation errors after adding “ref”. Consider the following member and method:

// SuperDataTable inherits from DataTable
// Indexing a SuperDataTable yields a SuperDataRow 
// which inherits from DataRow.
private SuperDataTable mySuperDataTable = new SuperDataTable();

public void DoSomethingSuper(ref DataRow myDataRow)
{
	return;
}

Now examine the following three scenarios:

// #1 You receive a compiler error "A property or indexer 
// may not be passed as an out or ref parameter"
DoSomethingSuper(ref mySuperDataTable[0]);

// #2 You receive a compiler error "Cannot convert from 
// 'ref SuperDataRow' to 'ref DataRow'
SuperDataRow mySuperDataRow = mySuperDataTable[0];
DoSomethingSuper(ref mySuperDataRow);

// #3 Only does it work in the following manner, when you 
// explicitly "upcast" the row to the exact type in the 
// signature of the method
DataRow myDataRow = mySuperDataTable[0];
DoSomethingSuper(ref myDataRow);

Try it again, this time passing by value. No compiler errors! I probably am just lacking an intimate understanding of “ref”, but this came out of left field for me and I haven’t seen it documented online. Can anybody fill me in as to why scenarios #1 and #2 don’t work?

Bookmark and Share

Posted in Programming Languages | Tagged: | 4 Comments »

Displaying Source Code in a WordPress Post

Posted by Ken on February 1, 2009

While setting up this blog, I came upon my first challenge:  How can you display source code in a WordPress post?

There are many solutions to this problem which include various WordPress.org plug-ins.  The problem with the plug-ins is that they don’t work with freebee WordPress.com blogs.  The simplest solution that I found for WordPress.com blogs was to simply wrap the code you want to post in “sourcecode” tags and let javascript take care of the rest. Implementing this is easy because you don’t have to worry about a big blob of HTML. All that is required is the code you want to paste and the javascript tags. Example:

static void Main(string[] args)
{
      Console.Out.WriteLine("Hello World!");
      return;
}

Being the perfectionist that I am, I wanted to see if I could get the code to look closer to the default fonts and colors used in Visual Studio. Thanks to this posting, I discovered pastebin.com.  It does a nice job of converting source code into html.  And it has syntax highlighting for most languages, including C#.  To streamline the process, I wrote a parser.  This code will parse the full source of the pastebin output, yank out the relevent html, and add style to make it look close to Visual Studio.  The following source code is a solution to the problem and also a demonstration. Which method do you think looks better?

using System;
using System.IO;
using System.Text.RegularExpressions;
 
namespace PasteBinCodeScrubber
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo[] allHtmlFiles = new DirectoryInfo(“.”).GetFiles(“*.htm*”);
            foreach (FileInfo htmlFile in allHtmlFiles)
            {
                string allHtml = File.ReadAllText(htmlFile.FullName);
 
                // capture all relevent html
                Regex sourceCodeRegex = new Regex(“<div class=csharp style=font-family: monospace;><ol>[\s\S]*?</ol></div>”);
                string sourceCodeHtml = sourceCodeRegex.Match(allHtml).Value;
 
                // doctor the html
                sourceCodeHtml = ScrubHtml(sourceCodeHtml);
                sourceCodeHtml = ReplaceCssClassWithStyle(sourceCodeHtml);
 
                File.WriteAllText(htmlFile.FullName + “.out”, sourceCodeHtml);
            }
        }
 
        private static string ReplaceCssClassWithStyle(string sourceCodeHtml)
        {
            sourceCodeHtml = sourceCodeHtml.Replace(“class=de1, string.Empty);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=de2, string.Empty);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=inp, “style=color: red;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=li1, “style=background: #ffffff;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=li2, “style=background: #f4f4f4;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=kw1, “style=color: #0600FF;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=kw2, “style=color: #FF8000;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=kw3, “style=color: #0600FF;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=kw4, “style=color: #0600FF;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=kw5, “style=color: #000000;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=co1, “style=color: green;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=co2, “style=color: green;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=coMULTI, “style=color: green;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=es0, “style=color: #008080;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=br0, “style=color: #008000;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=st0, “style=color: maroon;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=nu0, “style=color: #FF0000;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=me1, “style=color: #0000FF;);
            sourceCodeHtml = sourceCodeHtml.Replace(“class=me2, “style=color: #0000FF;);
            return sourceCodeHtml;
        }
 
        private static string ScrubHtml(string sourceCodeHtml)
        {
            // add font size
            sourceCodeHtml = sourceCodeHtml.Replace(“<div class=csharp style=font-family: monospace;>”,
                                                    “<div style=font-family:monospace; font-size:1.3em;>”);
 
            // remove list tags
            sourceCodeHtml = sourceCodeHtml.Replace(“<ol>”, string.Empty);
            sourceCodeHtml = sourceCodeHtml.Replace(“</ol>”, string.Empty);
            sourceCodeHtml = sourceCodeHtml.Replace(“<li “, “<div “);
            sourceCodeHtml = sourceCodeHtml.Replace(“</li>”, “</div>”);
 
            // remove hyperlinks
            Regex hyperLinkRegex = new Regex(“<a href=.*?>(?’linkWrappedHtml'[\s\S]*?)</a>”, RegexOptions.ExplicitCapture);
            MatchCollection hyperLinkMatches = hyperLinkRegex.Matches(sourceCodeHtml);
            foreach (Match hyperLinkMatch in hyperLinkMatches)
            {
                string sHtmlInsideHyperLink = hyperLinkMatch.Groups[“linkWrappedHtml”].Value;
                string sFullHyperLink = hyperLinkMatch.Value;
                sourceCodeHtml = sourceCodeHtml.Replace(sFullHyperLink, sHtmlInsideHyperLink);
            }
 
            return sourceCodeHtml;
        }
    }
}

Bookmark and Share

Posted in WordPress | Tagged: , | 4 Comments »