# Thursday, December 28, 2006

For those of you out there that are smarter than me ... and after yesterday's post, I'm thinking that there are a *lot* of you ... You probably noticed that I was a little confused between the effects of IE7 protected mode (Low Rights IE or LoRIE), the VS 2005 SP1 release and the debugging problems that I was experiencing on Vista.

I've known about IE7 protected mode, sandboxing and virtualization for many months now and was even cognizant of that when I was having my debugging problems. I even glanded down at the bottom bit of the IE chrome and noticed "Protected Mode: On", but for some reason I thought http://localhost would *not* be affected by the protected mode. I was dead wrong. Arghh.

So, the answer to the basic debugging problems that I was having w/IE7 on Vista are entirely solved by adding http://localhost as a trusted site in IE7. Remember to uncheck the "https://" checkbox when adding the site, or else you won't be able to add http://localhost.

There are a bunch of other blog posts on the subject if you are interested.

Thursday, December 28, 2006 10:37:57 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, December 27, 2006

I decided to re-build dasblog (the blog software that I use) on Whidbey (VS 2005) over the holidays. It is something that I had always wanted to do and it seems like the dasblog folks have not yet publicly taken that on. Before anyone gets any strange ideas, I have no desire for a thinkjot-like schism, but wanted to move the codebase to Whidbey and work on getting the software to run under partial-trust. If this all works out, and the dasblog team wants to adopt my changes, cool, otherwise, I'm going to just use it myself.

Anyway, I decided to tackle this task over the holidays. Believe it or not, I almost exclusively use the free VS Express SKUs for my coding work. The "free" part isn't a big deal for me as I have a full copy of VS team suite a couple meters away from me, and I can download and install any program (including "Microsoft Bob") from the MS network that I want. Still, the Express SKUs are super convenient since I can download and install them in about 10mins and they satisfy most of my needs. Anyway, I downloaded the dasblog source and started playing with it. It became clear that I needed to use both VS express C# and VS express Web to get this done since the Web product didn't appear to support multiple projects in a single solution; in fact, it didn't appear to support the solution concept at all. And I then realized that since VS C# doesn't support JIT attach debugging (due to licensing issues), that the whole thing wasn't going to work at all. That's when I reached over for the quite large (requires two hands) VS team suite box to do some "real developlment" ;)

After a fairly lengthy install (and I didn't even install MSDN since I use the web mostly), I started back at it. I was able to get the web and class library projects into one solution in VS. Cool! I then hit F5 and it was immediately clear that something was terribly broken. The web project launched as expected, but was immediately detached from the debugger. Huh? I tried a couple more times, and I had the same experience. I was able to attach VS to WebDev.WebServer.Exe and then refresh the page, and then my breakpoints were hit. This approach though is anything but a good experience.

I had heard that there were some incompatibilities with VS on Vista, but I was under the impression that it was more niche issues, of which this is not. It is also very strange that I didn't have these same problems with the Express products, which I've been using on Vista for months. I wonder why the full product has some additional problems. I'm sure someone in building 41 knows.

Time to install VS 2005 SP1. I went to the following page. I downloaded the Vista-specific update. That didn't work, claiming that I was missing a file or two. I then downloaded and installed the non-Vista-specific SP1 package, which is just shy of 1/2 GB. Ouch! That worked. Upon launching VS, it claimed that I needed the Vista-specific update. Oh, I see, you need to install the generic VS 2005 service pack, and then the Vista-specific update. That was not at all clear to me from the VS 2005 SP1 page. Grrrr. Anyhow, now you can avoid the trouble that I had.

I then launch VS, but it claims that I need to launch the app elevated. I was actually expecting that, but thought that they would have manifested the application to force the elevation dialog. I guess not, or maybe that's still coming. Developers are going to go nuts if they have to remember to right click on the VS 2005 icon and hit "Run as administrator" every time, or just turn off UAC on their dev-boxes, which is a bad idea.

OK, launch VS again, but elevated, and voila, everything is working correctly again. Peace and harmony have now returned to my development experience.

I'm very thanksful that the VS team has pulled off this pretty significant service pack ... *before* Vista is generally available. I'm glad to be back and productive again. The directions on MSDN could use some improvement.

Wednesday, December 27, 2006 10:29:08 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
# Wednesday, December 20, 2006

I wrote a recent post about getting the list of loaded assemblies. That’s a pretty straight-forward operation as shown by the code listed in that post. I’d like to step up the problem one notch by looking at getting the list of assemblies from another domain. Seems like a very reasonable thing to do ... Or we’ll see …

To properly setup this example, I need to create another domain and keep a reference to that domain. That’s easy:

            //Create new domain

            AppDomain domain = AppDomain.CreateDomain("domain2");

 

Next, we need to load some code in that domain, or else there won’t be any assemblies loaded there to actually query. Note that Host is one of my types, as you’ll see later. The method below loads the DomainHost assembly in domain2, creates an instance of the DomainHost.Host type in domain2 and also returns a reference to that instance in the current domain. That’s why you see the cast to Host.

            Host host = (Host)domain.CreateInstanceAndUnwrap("DomainHost", "DomainHost.Host");

 

OK … this is the part that where it gets interesting. It is actually a little non-obvious on how you are intended to get the list of loaded assemblies from the other domains. Let’s first look at the most intuitive approach for doing this. There is the same GetAssemblies() method on AppDomain that I used in the last post.  So, given that I have a reference to the domain2 AppDomain instance, why not just call GetAssemblies() on it? This is what the code would look like:

            domain.GetAssemblies();

 

For a variety of reasons, assemblies are not marked as serializable objects, which means that they cannot be remoted across an appdomain (or any other) boundary. You can get around this limitation by remoting and then loading an assembly as a Byte[], but that’s a different blog post. This call gets around the limitation by remoting an array of representative AssemblyName objects, as opposed to the actual assemblies. The loader then does the equivalent of the following, assuming the AssemblyName[]is called asmNames:

            foreach (AssemblyName asmName in asmNames)

            {

                Assembly.Load(asmName);

            }

This behavior is not really expected or desirable. First, you really want the AssemblyName objects, not the Assembly objects, and you definitely do not want to cause the assemblies to be loaded in this domain. In addition, if the assemblies are not located in the GAC, and the other domain has a different AppBase, then it is very likely that the assembly loads will fail, resulting in the loader throwing an exception that you might not be prepared to catch. Ouch. That’s really bad. It is also important that not all assemblies play nicely with this behavior. For example, Reflection.Emit assemblies cannot be re-loaded cross domain, for fairly obvious reasons. Mixed-mode assemblies have another set of problems. So, let’s skip that option.

Another option is to call AppDomain.GetAssemblies() in the other domain, and then to remote the Assembly[] back through to the current domain.  That will have the same effect as what I just discussed above.

 I’ve skipped over some important details that I need to explain. My DomainHost.Host type is a regular old that type that happens to inherit from System.MarshalByRefObject. The fact that it inherits from this type is more of a marking than anything else, as I don’t override any of MBRO’s methods, nor do I have to know what they are. This is very conceptually similar to marking a type with the [Serializable] attribute. The difference is that MBRO provides copy-by-ref semantics as opposed to copy-by-value across a boundary, which is what the [Serializable] attribute provides. This means that MBRO-inherited types can be remoted across a domain, process or even machine boundary as a reference that you can easily call across. The method calls only affect the domain in which the type actually resides (not where the reference resides), with the exception that return types (which must be either MBRO or [Serializable]) are returned to where the call was made from (the current domain). The reference is called a transparent proxy, and you can see that in the debugger when you try to peer into what turns out to be the largely opaque System.Runtime.Remoting.Proxies.__TransparentProxy type. Woah! The fact that DomainHost.Host is MBRO is going to turn out quite useful, as we’ll see.

OK, now to the real solution. I need to add a method to DomainHost.Host that I can call that returns AssemblyName[] and that does not interact with the loader in any way on this side of the domain boundary, as I want to avoid any assembly loads on these AssemblyName objects. Let’s see what the method would look like:

        public AssemblyName[] GetAssemblyNames()

        {

            AssemblyName[] names;

            Assembly[] asms;

 

            asms = AppDomain.CurrentDomain.GetAssemblies();

            names = new AssemblyName[asms.Length];

 

            for (Int32 i = 0; i < asms.Length; i++ )

            {

                names[i] = asms[i].GetName();

            }

 

            return names;

        }

This method uses the AppDomain.GetAssemblies() method to get the list of loaded assemblies, but doesn’t return that. It creates an equal length AssemblyName[] array to the Assembly[] that it already has.  It then populates that array with the assembly name of each of the assemblies. After the assembly name array is populated, the method returns that array of serializable objects back to the caller, which happens to be on the other side of the appdomain boundary. And how does one call such a method on the other side of the appdomain boundary? Easy:

            AssemblyName[] asmNames = host.GetAssemblyNames();

 

This ease of cross-boundary calls is the beauty of .NET Remoting. You just call methods as if the instances were located directly beside you. Cool.

Well, that’s now about it. Let’s take a look at the whole program:

Main program:

using System;

using System.Reflection;

using DomainHost;

 

namespace GetAssemblyNamesFromDomain

{

    class Program

    {

        static void Main(string[] args)

        {

            AppDomain domain;

            Host host;

            AssemblyName[] asmNames;

 

            //Create new domain

            domain = AppDomain.CreateDomain("domain2");

//Load assembly in domain2 and create instance of DomainHost.Host

//A reference to the instance of DomainHost.Host is returned

            host = (Host)domain.CreateInstanceAndUnwrap("DomainHost", "DomainHost.Host");

 

            //Most obvious method for getting the list of loaded assemblies.

            //This method will cause the assemblies in the remote domain to

            //be loaded in this domain, which frequently won't work. Ouch!

            //domain.GetAssemblies();

 

            asmNames = host.GetAssemblyNames();

            Console.WriteLine();

            Console.WriteLine("Printing assemblies:");

            foreach (AssemblyName asmName in asmNames)

            {

                Console.WriteLine(asmName.FullName);

            }

 

        }

    }

}

 

DomainHost.Host (in DomainHost.dll)

using System;

using System.Reflection;

 

namespace DomainHost

{

    public class Host : MarshalByRefObject

    {

        public Host()

        {

            Console.WriteLine("Loading host in domain {0}",AppDomain.CurrentDomain.FriendlyName);

        }

 

        public AssemblyName[] GetAssemblyNames()

        {

            AssemblyName[] names;

            Assembly[] asms;

 

            asms = AppDomain.CurrentDomain.GetAssemblies();

            names = new AssemblyName[asms.Length];

 

            for (Int32 i = 0; i < asms.Length; i++ )

            {

                names[i] = asms[i].GetName();

            }

 

            return names;

        }

 

    }

}

 

The output of the program looks like:

Loading host in domain domain2

Printing assemblies:

mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Microsoft.VisualStudio.HostingProcess.Utilities, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

DomainHost, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

 

The fact that I see “Microsoft.VisualStudio.HostingProcess.Utilities” loaded is a VS weirdness. VS is loading an assembly in domain2 to somehow “help me”, but I don’t know why. This only occurs when I’m running/debugging my app through VS. If I run the program outside of VS, I don’t see that assembly loaded. You have noticed executables ending in vshost.exe. That’s a similar issue, but for another day.

Wednesday, December 20, 2006 8:40:10 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, December 07, 2006

A guy from a well-known company mailed me asking how to avoid deploying statically referenced assemblies that he knows will not be loaded at runtime. The issue is that the assembly is being loaded, but he doesn’t believe that it is being actually used. His current workaround is to deploy the assembly to avoid FileNotFound exceptions, which nobody likes.

I have two questions for the guy:

1.      Why are you so certain that the assembly will not be needed?

2.      Is the assembly used in other scenarios, just not this one? There must be a reason that it is statically referenced by your app in the first place.

 

As you can guess, this whole exercise is a bit of a dangerous situation. You can spend a lot of time ensuring that certain code paths will never be called, and then your users do something unexpected and low-and-behold, that darned FileNotFound exception is thrown. Ouch.

Why is this a problem?

Anyway, the core of the problem is at the level of the JIT (just-in-time compiler). The JIT jits code (MSIL) at a method-level basis.  The following is how things work at a high-level:

1.      The app calls a method

2.      The method cannot be executed because it hasn’t yet been jitted to machine code

3.      The JIT compiles the method (MSIL) into x86 (or X64 or IA64) code

4.      For every method call that the JIT sees, it must fully understand the signature of that method, specifically the return type and the arguments/parameters. This requirement may cause an assembly load.

5.      The method can now be called. The method will not need to be jitted again (at least in this app domain).

 

For example, the return type might be a value type, requiring the JIT to know how large that type is. To get that information, the JIT must load the type, and must request that the assembly (in which the type is contained) be loaded if it is not already loaded. This is still the case even if the method call is within an if statement, and might not actually be called.

Code that exposes the problem

As already suggested, you are going to run into this problem anytime you have a direct cross-assembly method call anywhere in a method you know that you will call, and hence JIT. This is even true under an if statement where the condition will not be true in this scenario.

        static void Method1()

        {

            if (condition)

            {

                //directly calling method from ClassLibrary2

                Class2.Multiply(100, 200);

            }

        }

 

Code that avoids this problem

It is pretty easy to avoid this problem. Write the following code instead.

        static void Method1()

        {

            if (condition)

            {

                //indirectly calling method from ClassLibrary2

                Method2();

            }

        }

        static void Method2()

        {

                //directly calling method from ClassLibrary2

                Class2.Multiply(100, 200);

        }

As you can see, the call to Class2.Multiply() is now an indirect call and does not require the JIT to know anything about the Class2 or require ClassLibrary2 to be loaded (the symptom to be avoided), unless of course the condition is met and Method2() is called. This trick is a little awkward sometimes, but it is a great option to at least defer and even completely avoid assembly loads.

Gotcha

Unfortunately, there is a gotcha. The JIT does optimize code by inlining methods. When this happens, you lose your indirect call, and you are now in the same bad boat you were in before. I don’t know much about the JIT inlining policy, so cannot provide a list of where this happens. This is merely a caveat that my workaround doesn’t work in all cases.  If folks are interested, I can talk to the folks on the JIT and perf teams to learn more about this gotcha.

Thursday, December 07, 2006 8:25:44 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [2]  | 
# Tuesday, December 05, 2006

We often talk about the loaded assemblies list over here. This is the list of assemblies currently loaded in the app domain. Big surprise. There isn't anything incredible special about this list. It is pretty easy to access and use. At the minimum, you can print out the list of assemblies. Beyond that, you can load and instantiate any of the types within those assemblies. That's where reflection comes in.

Here's some code that prints out the list of loaded assemblies:

using System;
using System.Reflection;

namespace GetLoadedAssemblies
{
class Program
{
static void Main(string[] args)
{
Assembly[] asms;

asms = AppDomain.CurrentDomain.GetAssemblies();

Console.WriteLine("There are {0} assemblies loaded:", asms.Length);
foreach (Assembly asm in asms)
{
Console.WriteLine(asm.FullName);
}

Console.WriteLine();
Console.WriteLine("The currently executing assembly is:");
Console.WriteLine(Assembly.GetExecutingAssembly().FullName);

}
}
}
Tuesday, December 05, 2006 11:51:00 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Wednesday, November 29, 2006

I took another look at the FileVersion sample. I wish the API was actually a little different. The API actually makes sense as a general use API, but it isn't as user-friendly as I would like. I wish that there were an instance method on the Assembly class called "GetFileVersion" or something like that it took nothing and returned a Version class.

Here is more of less what it would look like, except that the GetFileVersion wouldn't be static, it wouldn't take anything and would be on the assembly class.

If you look @ the FileVersion class, there is a lot of stuff on there, and it is a super wonky API anyway. I don't understand why it has a single static method that more or less acts that the instance constructor. Why not just have a constructor that takes a string or a FileInfo or even a FileStream. Bad API design. I prefer the Version class a lot more since it is super simple. I

using System;
using System.Reflection;
using System.Diagnostics;
namespace FileVersion
{
class Program
{
static void Main(string[] args)
{
Assembly asm;
Version ver;

asm = Assembly.Load("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
ver = GetFileVersion(asm);
Console.WriteLine(ver.ToString());
}

static Version GetFileVersion(Assembly asm)
{
FileVersionInfo versionInfo;
Version ver;

versionInfo = FileVersionInfo.GetVersionInfo(asm.Location);
ver = new Version(versionInfo.FileMajorPart, versionInfo.FileMinorPart, versionInfo.FileBuildPart, versionInfo.FilePrivatePart);

return ver;
}
}
}

If you look @ the FileVersion class, there is a lot of stuff on there, and it is a super wonky API anyway. I don't understand why it has a single static method that more or less acts like an instance constructor. Why not just have a constructor that takes a string or a FileInfo or even a FileStream. Bad API design. I prefer the above method (for the assembly case) that returns the Version class since it is super simple. I realize that the native file version is a string, so can contain more stuff, but the 4-part version number is really all I want.

Wednesday, November 29, 2006 3:39:29 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 

The file version number is a native code concept – meaning not originating from the .NET Framework. This version number is a resource found within the resource section of the windows PE (portable executable) format of a managed or native code dll. This resource is named “FILEVERSION”. This version number is used for information purposes only, not for any runtime purposes such as binding. In addition, this version number does not have to conform to a particular format, but is only a string, although it does typically takes the form of a simple four-part number (i.e. 1.2.3.4).

Reading the File Version

The easiest way to view this number is to view the properties of a file in Windows Explorer. The version number listed is the file version number. The product version is also listed, although I don’t know how the two numbers differ exactly. Naturally, you can access the file version from code. The following code does just that, largely using the System.Diagnostics.FileVersionInfo class, which I’ve never used before. In fact, I had to ask someone else on the loader team for that information.

using System;

using System.Reflection;

using System.Diagnostics;

namespace FileVersion

{

    class Program

    {

        static void Main(string[] args)

        {

            Assembly asm = Assembly.Load("mscorlib, Version=2.0.0.0, Culture=neutral,  PublicKeyToken=b77a5c561934e089");

            System.Diagnostics.FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);

            Console.WriteLine(fvi.FileVersion);

        }

    }

}

 

Setting the File Version

The CLR provides an assembly-level custom attribute to set this version number for an assembly from managed code. This attribute is called System.Reflection.AssemblyFileVersion. You can see how to set it below.

using System;

using System.Reflection;

 

[assembly:System.Reflection.AssemblyFileVersion("2.3.4.5")]

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("I just set the file version!");

        }

    }

}

 

You can actually set this attribute in Visual Studio 2005 via the properties menu. In that case, you cannot set it in code, as I’ve done above, since you’ll then have two instances of the attribute. You only need to set the attribute directly, as I’ve done  above, if you are using the compiler directly, from the commandline.

Wednesday, November 29, 2006 12:00:36 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Tuesday, November 28, 2006

Versioning and version numbers are always a bit confusing. For the CLR and the .NET Framework, we’ve got lots of version numbers to think about. I’d like to debunk any confusion around them, explain what each version number means, how to view it and how to set it (if appropriate). Let’s take a look …

The version numbers that I’m going to discuss are:

·         Native file version

·         Managed assembly version

·         Metadata version

·         Metadata format version

·         .NET Framework versions

I’m going to discuss these version numbers (and anything else that comes up) across the next few posts.

Tuesday, November 28, 2006 11:53:35 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, November 02, 2006

I made reference to the concept of textual identity in my last post, but didn’t go into a lot of detail. In this post, I’d like to describe the broader concept of assembly identity to provide folks with further insight as to what I was going on about. The following text is from a spec that I wrote; it should apply equally to v1.0, v1.1 and v2.0 and future .NET Framework versions.

Assembly Identity

The assembly identity is the name of an assembly. The filename, path, file hash or other characteristics are not part of the identity. The identity is used in two different ways: (1) to define the name of an assembly, and (2) to reference an assembly by name. These are sometimes referred to as “def” and “ref”. Both of these are assembly identity. In the case of a reference, the identity is used during binding to determine if and where an assembly is available.

 

Identity Composition

The assembly identity is composed of several distinct attributes that detail different characteristics about an assembly. Each attribute is used in binding if it is provided. The allowed attributes follow:

 

·         Simple name

o   Format: string

o   Description: The name is the simple name of the assembly. It is essentially the name without all the other attributes

o   Note: The name should always be the same as filename minus extension

·         Version

o   Format: Four 16-bit integers separated by “.”

o   Description: A four-part version number (Major.Minor.Build.Revision)

o   Note: Each one of the 16-bit integers overflow at 165536 and underflow at -1

·         PublicKeyToken or PublicKey

o   Format: An 8-byte or variable length (48- to 2048-byte) string, respectively or “neutral” or “null”

o   Description: The public key token or key specifies the cryptographic signature of an assembly, guaranteeing that the assembly is from a particular publisher or set of assemblies (with that same token or key)

o   Note: The token is almost always provided instead of the much longer key

·         Culture

o   Format: string or “neutral” or “null”

o   Description: An arbitrary string that represents a culture installed on the system

·         ProcessorArchitecture

o   Format:  “MSIL” or “X86” or “X64” or “IA64”

o   Description: The processor architecture (PA) attribute specifies the requirement of a particular platform to execute a particular assembly. “MSIL” is an agnostic PA, as “MSIL” assemblies are allowed to be executed on any processor. All other PA options are “bit-specific” and must be run on a specific platform.

o   Note: PA doesn’t relate directly to processor or CPU. For example, X86 assemblies can be execute on X64 machines using the WoW64 infrastructure.

·         Retargetable

o   Format: “yes” or “no”

o   Description: The retargetable attribute specifies that an assembly can be retargeted to another assembly, meaning a reference to another assembly can be retargeted to this one.

o   Note: The retargeting mechanism is more complicated than described here, and is not at all a common scenario

 

Note: In all cases, the attributes and enumeration values are matched during binding case insensitively.

 

Textual Identity

The assembly identity can be specified in a string format, most often referred to as a “textual identity”. This form of the assembly identity is used by many APIs within the .NET Framework. There are also APIs that parse the textual identity string and return the identity back as a class, removing the need for developers to parse or create a textual identity string. More on that class later.

 

Textual Identity Specification

The specification of this format follows:

 

simple_name (“,” attribute “=” value)+

 

The textual identity starts with the simple name, and then a set of attributes and their values. Each attribute starts with a “,” and then its name, followed by a “=” and then a quoted or non-quoted value for that attribute. Whitespace can occur pretty much anywhere within the string, except within the attribute names, which are essentially tokens.

 

The allowed attributes, mapping directly to the components described in the previous section, are listed below:

  • Simple name à has no attribute name, requiring only its value
  • Version à “Version”
  • Culture à “Culture”
  • Public key or token à “PublicKey” or “PublicKeyToken”
  • Processor architecture à “ProcessorArchitecture”
  • Retargetable à “Retargetable”

 

 

The following characters can be escaped as part of the identity, with the escape character “\”:

  • t
  • r
  • n
  • \
  • =
  • U(HexChar)

Textual Identity Error Cases

The textual identity parser will error in the following cases:

 

  • The textual identity doesn’t match the correct general format (“,” attribute “=” value)+
  • The textual identity includes attributes that are unknown (i.e. foo=bar)
  • There is a value that doesn’t match a member of a given enumeration (i.e. “powerpc”)
  • A part of any version number under- or over-flows the integer

AssemblyName Class

The .NET Framework includes a class called System.Reflection.AssemblyName. An AssemblyName takes the textual identity in its constructor, parses the string and then provides access to each attribute of the identity via handy properties. The constructor throws if the provided string is invalid according to the specification provided above.

 

The term “assembly name” is sometimes used interchangeably with “assembly identity”. It is generally best to think of “assembly name” as the AssemblyName class, and “assembly identity” as the boarder concept of the multi-part name of an assembly as described earlier.

 

Strong versus Partial versus Weak Names

Up until this point, the assembly identity has been described as if all the parts always have to be there. That is not the case. There are essentially three categories of names, depending on how much of the identity attributes are specified.

 

Strong name

·         Simple name

·         Version

·         Culture

·         PublicKey or PublicKeyToken

 

Weak name

·         Simple name

 

Partial name

·         A weak name, or

·         Additional attributes beyond a weak name, but not enough to be considered a strong name

 

There are two other attributes: ProcessorArchitecture and Retargetable. ProcessorArchitecture is always optional, and just really makes a strong name more stronger. Retargetable is not commonly used.

Thursday, November 02, 2006 11:12:05 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
# Thursday, October 26, 2006

The CLR loader offers a few APIs for loading assemblies, each of which have a slightly different model and behaviour for how they go about the task. I'd like to cover those and hopefully set folks on the best path for using loading assemblies.

The APIs that I have in mind are:

  • Assembly.Load(), and
  • Assembly.LoadWithPartialName()

First, you need to understand the concepts of fully-specified and partial assembly names.  A fully specified name contains the following parts: the simple name, version, culture, and public key or public key token. A partial name contains at least the simple name and optionally any of the other parts of the full-specified name. This concept is most relevant to the textual identity of an assembly. For example, here is the fully-specified assembly textual identity for v2.0 System.dll: "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089". The textual identity is a specially formatted string that is used to describe some or all of the aspects of identifying an assembly.

Assembly.Load() takes a string as one of the overloads. The textual identity, as you see formatted above, is just the sort of string that Load() is expecting. Load() also takes other types, such as AssemblyName, but that's not important for the moment. The textual identity can be fully or partially specified, and which one it is has an important impact on the way that these loader APIs operate. The one you see above for System.dll is fully specified, since all the parts are there. Note that there is an additional part (or attribute) of the textual indentity that I've missed -- ProcessorArchitecture -- but that complicates the discussion too much for not much benefit, so I'm not going to cover it here.

The following bit of code shows the use of these APIs with full- and partially-specified names. The comments inline should pretty well explain what to expect

using System;
using System.Reflection;

namespace BindingByIdentity
{
class Program
{
static void Main(string[] args)
{
Assembly asm;

//LoadWithPartialName() looks in both the appbase and the GAC, looking for the best match,
//where "best match" isn't very clearly defined
//In addition, this method has been deprecated, which means "don't use this anymore, and it may be removed later"
try
{
Console.WriteLine("Calling LoadWithPartialName");
asm = Assembly.LoadWithPartialName("System");
Console.WriteLine("Loaded: {0}",asm.FullName);
}
catch(Exception e)
{
Console.WriteLine("LoadWithPartialName threw with the following exception:");
Console.WriteLine(e.Message);
}


//Load() with a partial name looks only in the appbase
//There is no gaurantee that you will get the assembly that you want
//In the case that you have private bin paths specified, there are no order gaurantees
//This particular use of the Assembly.Load() will always throw, since this assembly will not be found (because it is GAC'd)
try
{
Console.WriteLine("Calling Load");
asm = Assembly.Load("System, PublicKeyToken=b77a5c561934e089");
Console.WriteLine("Loaded: {0}", asm.FullName);
}
catch(Exception e)
{
Console.WriteLine("Load threw with the following exception:");
Console.WriteLine(e.Message);
}

//Load() with a fully-specified name looks in the appbase and the GAC and gaurantees that you
//will get the assembly that you asked for
try
{
Console.WriteLine("Calling Load");
asm = Assembly.Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
Console.WriteLine("Loaded: {0}", asm.FullName);
}
catch (Exception e)
{
Console.WriteLine("Load threw with the following exception:");
Console.WriteLine(e.Message);
}


}
}
}

Output:

Calling LoadWithPartialName
Loaded: System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Calling Load
Load threw with the following exception:
Could not load file or assembly 'System, PublicKeyToken=b77a5c561934e089' or one
 of its dependencies. The system cannot find the file specified.
Calling Load
Loaded: System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

The moral of this story is that Assembly.LoadWithPartialName() is always bad and shouldn't be used since its behaviour isn't well-defined or predictable, and that you should always fully-specify the textual identity strings that you pass into Assembly.Load(). It may be the case that partially specified strings "work" since the assemblies you are attempted to load are always going to be in the app-base, but the fully-specified names do make your code and your intentions more clear, particularly for the next guy that has to look at the code you wrote. The funny thing is that sometimes "the next guy" is you, just two months later ;)

There is also the case that your code might not be strong-named. You should still specify everything but the publickey/token in that case.

Thursday, October 26, 2006 7:43:59 AM (GMT Daylight Time, UTC+01:00)  #    Disclaimer  |  Comments [0]  |