Could not load file or assembly or one of its dependencies.

Here is a fix for an error that I received in Visual Studio 2010

The error reads:

Could not load file or assembly ‘file:/// [path to assembly]’ or one of its dependencies. An attempt was made to load a program with an incorrect format. Line 465, position 5.

To fix the problem, I did this:

  1. Double-click the error (which was located in the VS2010 Error List Window)
  2. After double-clicking the error, the cursor will be placed in an XML closing tag called </data>. From the closing </data> tag, scroll to the opening <data> tag. The <data> tag contents looked like this:
    <data name="imageList.ImageStream" mimetype="application/x-microsoft.net.object.binary.base64">
        <value>
            AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0yLjAuMC4w
  3. Manually make a change to a part of the string exactly as follows: Change the end of the string from
    j00LjAuMC4w to j0yLjAuMC4w

    Note that the only change is swapping out the second zero with a ‘y’

  4. Rebuild the Visual Studio Solution

Notice! The stream data that you edited was derived from an ImageList that exists in your assembly. So, each and every time you make a change to the ImageList or open the Windows Form  (that contains the ImageList) in Designer Mode, you will need to do the above procedure.

This problem occurs when your development machine is running a 64bit OS (I was running Windows Server 2008 RS 64bit). Apparently, what’s happening is Visual Studio is serializing ImageLists with a reference to .NET 4.0 instead of .NET 2. This information is specifically defined at the “j00” section of the serialized data. Changing the data to “j0y” informs ResGen.exe that the ImageList targets .NET 2.

Named and Optional Arguments

Compared to how much there is to know about the C# language, I’m the first to admit that I know very little. However, sometimes when I stumble across a C# spec that I’ve never known prior, I inadvertently blurt out “how did I NOT already know that?!” … just a few minutes ago, I committed the blurt!

I didn’t know (’til now) that Visual C# 2010 introduced named and optional arguments.

Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter’s name rather than with the parameter’s position in the parameter list. Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.

When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

Named and optional parameters, when used together, enable you to supply arguments for only a few parameters from a list of optional parameters. [ref]

class NamedExample
{
    static void Main(string[] args)
    {
        // The method can be called in the normal way, by using positional arguments.
        Console.WriteLine(CalculateBMI(123, 64));

        // Named arguments can be supplied for the parameters in either order.
        Console.WriteLine(CalculateBMI(weight: 123, height: 64));
        Console.WriteLine(CalculateBMI(height: 64, weight: 123));

        // Positional arguments cannot follow named arguments.
        // The following statement causes a compiler error.
        //Console.WriteLine(CalculateBMI(weight: 123, 64));

        // Named arguments can follow positional arguments.
        Console.WriteLine(CalculateBMI(123, height: 64));
    }

    static int CalculateBMI(int weight, int height)
    {
        return (weight * 703) / (height * height);
    }
}

Personally, I don’t think this new addition to the C#2010 spec isn’t something that I will use that much (if at all), but still – It’s certainly worth knowing that it’s there.

Merge Multiple .NET Assemblies Into One Using ILMerge

ILMerge is a utility for merging multiple .NET assemblies into a single .NET assembly. It works on executables and DLLs alike and comes with several options for controlling the processing and format of the output.

Today I ran into a problem merging two assemblies which targeted the .NET 4 Framework. After running the ILMerge command, I received the following exception:

An exception occurred during merging:
Unresolved assembly reference not allowed: System.Core.

I found this post by Steve Michelotti, but after implementing Steve’s solution I received this error:

Process is terminated due to StackOverflowException.

The new error led me to this post by Stephen Cleary. Not only did Stephen’s suggestion fix my particular problem, but he gives useful information on why the errors occur in the first place. Thanks, Stephen!

Go here for documentation on all ILMerge Members

The procedure below is a step-by-step listing on how you can merge two assemblies into one assembly and have that new assembly target the Microsoft .NET Framework 4

ILMerge Procedure for the .NET Framework 4
For clarity sake, the procedure below assumes that you have a Visual Studio Solution which contains two Projects with the following configurations:

  • The name of the Visual Studio Solution is ILMergeSolution
  • The names of the two projects are Project1and Project2
  • Both projects (Project1 and Project2) are configured to compile to a .DLL
  • Project1 references Project2 (i.e. When Project1 is compiled in Release mode, Project1 will output its own .DLL to its /bin/Release directory as well as the .DLL of Project2)
  • Project1 and Project2 output XML comments

ILMerge Procedure

  1. Compile/build the  the ILMergeSolution  (in Release mode), then open the \Project1\bin\Release directory
  2. Move the “Project1.dll” and “Project2.dll” and their corresponding XML files from the \Project1\bin\Release directory to the root directory of the ILMerge executable program (i.e. C:\Program Files\Microsoft\ILMerge)
  3. Open a Command Prompt (Run as Administrator)  then change the prompt directory to C:\Program Files\Microsoft\ILMerge
  4. At the prompt enter: ilmerge /out:MyMergedProjects.dll Project1.dll Project2.dll /ndebug /xmldocs /targetplatform:v4,"%ProgramFiles%\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"
  5. The “C:\Program Files\Microsoft\ILMerge” will now contain two new files: 1. MyMergedProjects.dll and 2. MyMergedProjects.xml
  6. The MyMergedProjects.dll and MyMergedProjects.xml can now be distributed for other developers to implement in their .NET 4 application. Note: The .xml file makes it possible for consumers of the MyMergedProjects assembly to view the XML comment documentation within their Visual Studio Intellisense.

Missing the v4 .NET Framework Folder?
If you are missing the folder specified at /targetplatform:v4,"%ProgramFiles%\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0" try using this path instead /targetplatform:”v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319″.

Example:
C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319"
/out:MyMergedApp.exe MyWindowsFormApp.exe MyBusinessLogic.dll

Syntax Explained

  • c:\Program Files\Microsoft\ILMerge>: The command prompt must be at the location where the ILMerge.exe lives
  • ilmerge: This tells the command prompt to run the ILMerge.exe executable file
  • /out:MyMergedProjects.dll: The /out switch tells ILMerge to output the new assembly with a name of “MyMergedProjects.dll” and in the same directory where ILMerge.exe lives. Note: We could specify a different directory, but I think it’s easier to not have to type out a directory path here at the prompt.
  • Project1.dll: This is the name of one of the .dll’s that will be merged (Notice that we did not have to specify a path since we manually moved the .dll into the same directory that ILMerge.exe lives in.)
  • Project2.dll: This is the name of one of the .dll’s that will be merged (Notice that we did not have to specify a path since we manually moved the .dll into the same directory that ILMerge.exe lives in.)
  • /ndebug: This switch will disable the creation of a .pdb file. By default, ILMerge creates a .pdb file for the output assembly and merges into it any .pdb files found for input assemblies.
  • /xmldocs: This switch will tell ILMerge to create XML documentation for the output assembly. By default, ILMerge will NOT create XML documentation.
  • /targetplatform: This is an ILMerge method which takes two strings as its parameters and is used to explicitly set the .NET Framework version that the target assembly (MyMergedProjects.dll in this case) will use.The method signature of the /targetplatform method is /targetplatform:NetFrameworkVersion,PlatformDirectory. In its class state, the signature is public void SetTargetPlatform(string platform, string directory);.
    The MS documentation on the /targetplatform method is:

    This method sets the .NET Framework for the target assembly to be the one specified by platform. Valid strings for the first argument are “v1”, “v1.1”, “v2”, and “v4”. The “v” is case insensitive and is also optional. This way ILMerge can be used to “cross-compile”, i.e., it can run in one version of the framework and generate the target assembly so it will run under a different assembly. The second argument is the directory in which mscorlib.dll is to be found.

  • v4: The first parameter of the /targetplatform method which specifies which .NET Framework version to use.
  • “%ProgramFiles%\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0”: This is the second parameter of the /targetplatform method. It specifies the directory path of where the targeted .NET Framework version exists.
    Note the “%ProgramFiles%” entry is a standard (built-in) Windows Environment Variable which evaluates to the full path of the “Program Files” directory

How to remove items from an enumerable object that are equal to items of another enumerable object

Let’s say we have two integer arrays:

int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }
int[] b = { 3, 4, 5, 8, 9, 10, 45 }

C# provides a handy extension method that we can call that will compare the two arrays and then return a new enumerable object that will only contain integers from “a” that are NOT in “b”.

Example:

void Main()
{
 int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 int[] b = { 3, 4, 5, 8, 9, 10, 45 };

 // Remove items from "a" that are not in "b"
 var c = a.Except(b);
 foreach(int i in c)
 {
 Console.WriteLine(i);
 }

 Console.WriteLine("--------");

 // Remove items from "b" that are not in "a"
 c = b.Except(a);
 foreach(int i in c)
 {
 Console.WriteLine(i);
 }
}

As you can see in the code above, the handy extension method is called “Except”. The formal definition of this extension method is:

Enumerable.Except(Of TSource) Method (IEnumerable(Of TSource), IEnumerable(Of TSource))
Produces the set difference of two sequences by using the default equality comparer to compare values.

Namespace: System.Linq
Assembly: System.Core (in System.Core.dll)

How To Develop a Portion of a Photo to Fit a Specific Sized Frame Using Photoshop

Problem:

You want to develop just a portion of a photo that you will add to a certain sized picture frame. You are choosing to have your photo developed at a retail store that only offers photo sizes of 4×6, 5×7, etc – in other words, the retail store does NOT develop photos in the size that match the size of your picture frame.

Solution:

  1. Determine the exact size of the picture that is required for the picture frame. The picture frame in this example requires a picture size of 4.6cm X 4.6cm
  2. Open the picture in Photoshop
  3. Set your Photoshop Preferences to use the Units of Measure that your picture frame uses. In this example, the picture frame requires a 4.6cm X 4.6cm picture so I will set the Photoshop Units to use Centimeters 
  4. In Photoshop, select the “Rectangular Marquee Tool (M)”, then select the portion of the image that you want to be added to your picture frame.
  5. Crop the image to the selection that you just made by going to “Image > Crop” in the main menu.
  6. Open the “Info” palette by going to “Window > Info (F8)”
  7. Select the entire image by going to “Select > All”
  8. Take note of the width and height sizes that is specified in the Info Palette
  9. Using a calculator, divide the target width by the image width. In this example the target width is 4.6cm and the image width is 14.14cm then multiply my 100. So we calculate [(4.6/14.14) * 100 = 32.5]. The value 32.5 implies that the target image is 32.5% the size of the original image. Take note of this value – you will use it in the next step.
  10. We will now resize the image so that it will fit perfectly into the picture frame. Go to “Image > Image Size”. Set the “Pixel Dimensions” units to “Percent”. Then enter in the value that you calculated in the previous step. In this example we came up with the value 32.5%
  11. At this point, the size of the image in Photoshop should be the target size – to confirm this, take a look at the Width and Height specified in the Info Palette.
  12. Create a “Layer from Background” by double-clicking on the “Background” image that is located in the Layers Palette.
  13. Since we will be developing this image onto a 4in X 6in photo paper, we now need to place our image onto a 4x6in Canvas. To do so, go to “Image > Canvas Size”. In the “Canvas Size” window, enter the following values:
    Width: 6 inches
    Height: 4 inches
    Relative Uncheck the “Relative” option
    Anchor: Anchor towards the center
  14. Now we will add a border to the image so that we can see the outline of the 4×6 dimensions. Select the entire layer by hitting “Ctrl>A”, then go to “Edit > Stroke”
  15. In the “Stroke” window, enter
    Width: 5 px
    Color: Black
    Location: Inside
    Blending: Normal
    Opacity: 100%
  16. Save the Photoshop file as a JPEG file
  17. Upload the JPEG file that you just saved to your favorite photo developing store (Walgreens, Walmart, CVS, etc)
  18. Once you receive the developed 4×6 picture, you can cut out the image and insert it into the picture frame.

How to check if string exists in a List<string>

If you need to determine whether or not a string exists within a List<string>, you may want to ignore the case of the strings while doing the compare.

Thanks to an extension method that hangs off of the List<T>.Contains() method, this is very easy to do.

Say you have a List<string> which contains email addresses and you want to check to see if a specific email address exists within the List<string>, your code may look like this:

List<string> emails = new List<string>() {“keean@domain.com”, “ty@domain.com”, “milo@domain.com” };

string target = “KEEAN@domain.com”;

if (emails.Contains(target, StringComparer.OrdinalIgnoreCase))

    Console.WriteLine(“{0} exists in the list.”, target);

else

    Console.WriteLine(“{0} does not exist in the list.”, target);

For more information on the StringComparer class, read this MS article.

If you use the StringComparer class, you will notice that there are three “IgnoreCase” properties:

  1. StringComparer.CurrentCultureIgnoreCase
  2. StringComparer.InvariantCultureIgnoreCase
  3. StringComparer.OrdinalIgnoreCase

These are enumerations that specifies the culture, case, and sort rules to be used by certain overloads of the String.Compare and String.Equals methods. For more information, check out this article.