November 01, 2010

Dependency Injection

Loose coupling i.e. making your code modules less tightly bound to each other.
Dependency Injection helps this process, allowing clients of your code to get the application using their own code without them having to know very much at all as to how the application works internally.

The article linked in the title of this post has a very brief outline of some how it can work but basically I'm interested in using Interfaces and registering my own classes with the host application with the minimum possible code work.

There are lots of third party frameworks which provide implementations.
The method is usually the same, create and instance of the third party class and then call a method on it which tells the framework to run a particular concrete class that you have provided when a particular interface or type is used, it's a form of mapping allowing client classes to be used at runtime.

August 11, 2010

ISerializable - Serializing objects

Serializing is a mechanism to create a text/binary version of your objects state, this can be saved or sent somewhere and then deserialized back into the instance again.
i.e. The member variables of your Type get written somewhere with their values of the instance of your Type.

e.g.
Here's the class who's instance I want to recreate somewhere else or at a later time.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleClass
{
public class Class1
{
public int _myMemberVar;

///
/// required for serialization
///
public Class1()
{
_myMemberVar = 0;
}

public Class1(int value)
{
_myMemberVar = value;
}
}
}

Here's a class which Serializes the instance of the class above with the XMLSerializer. The version below writes the XML version of the instance to the Console, you could replace the
using (Stream str = Console.OpenStandardOutput())
with a FileStream of some sort to write the XML to file.
This results in

www.w3.org/2001/XMLSchema">

<_mymembervar>10



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Xml.Serialization;

namespace CallMySimpleClass
{
class Program
{
static void Main(string[] args)
{
SimpleClass.Class1 c = new SimpleClass.Class1(10);

string result = Serialize(c);
Console.WriteLine(result);
}
static string Serialize(object o)
{
string result = null;
using (Stream str = Console.OpenStandardOutput())
{
XmlSerializer x = new XmlSerializer(typeof(SimpleClass.Class1));
x.Serialize(str, o);
}
return result;
}
}
}




So that's how the default Serialization works but what if you want to customize how Serialize works.To do this you can either make members Serializable and NonSerialiazed by putting the [Serializable] and [NonSerialized] attributes on your Types and members (Note: these only work when using the Formatters .net gives you BinaryFormatter and SoapFormatter).Or you can take over the process completely buy making the Type you want to serialize implement ISerializable.


ISerializable:


July 13, 2010

Testing COM components


Here's some code you can use to try to load your Type through COM.
You can use the GetPEKind method to get the platform that the assembly was compiled for.

(Recently ran into a problem where I couldn't be sure the assembly I'd registered was registered correctly, my query was particular to win64, there are some changes in the registry entries for 64bit windows when running 32 bit applications.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Reflection;

namespace ComTest
{

class MyGetTypeFromCLSIDSample
{
public static void Main()
{
try
{
Guid myGuid1 = new Guid("3A21CE6B-8571-4955-9780-BAE1EE3215C0");//my Types GUID, regasm was ran on this assembly.

// Get the type associated with the CLSID
// and specify whether to throw an exception if an error occurs
// while loading the type.

//if this shows The type of the GUID is System.__ComObject.
//The current module is mscorlib.dll.
//assembly kind ILOnly, PE32Plus , platform AMD64
//then your assembly isn't registered.


Type myType1 = Type.GetTypeFromCLSID(myGuid1, true);
Console.WriteLine("The GUID associated with myType1 is {0}.", myType1.GUID);
Console.WriteLine("The type of the GUID is {0}.", myType1.ToString());

// Show the current module.
Module m = myType1.Module;
Console.WriteLine("The current module is {0}.", m.Name);

PortableExecutableKinds peKind;
ImageFileMachine machine;
m.GetPEKind(out peKind, out machine);

Console.WriteLine("assembly kind {0} , platform {1}", peKind.ToString(), machine);//assembly kind ILOnly , platform I386

Console.ReadLine();
}
catch
{
Console.WriteLine();
}
}
}

July 09, 2010

Visual Studio build configuration with x64 "Any CPU"

In Visual Studio you may have noticed, and ignored, the pulldowns in your toolbar which usually contain "Release" "Any Cpu".
The "Any CPU" part in particular is of interest especially if you plan on running your apps on Windows 64.
These configurations are contained in each project and solution i.e. if you open the projects in a text editor you'll see sections in the XML which contain the settings. These settings are also accessible through the Visual Studio UI via the pulldowns mentioned earlier.

The significance of the "Any CPU" is it's telling the compiler to compile the code into assemblies into code which can run on either 32 or 64 bit machines. If your assemblies are used by an application written in 64bit (and of course the app runs on a 64bit machine) then your assemblies will be used in the 64bit context, the same stands for 32bit (of course 32bit apps can also run on 32 or 43 bit machines).
64bit machines have an additional registry section "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node", this section contains registry entries for applications build with "Any CPU" or x86 (32bit). The normal registry section "HKEY_LOCAL_MACHINE\SOFTWARE" is used for pure 64bit apps but if the 64bit OS comes across 32bit apps then it uses the "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node" to get registry settings.
Note to that your installer may target this "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node" section if your assemblies and installer are configured to "Any CPU" or "x86". It may not be what you expect.




Registry.
There are some cavaets around the Registry entries used on 64bit machines. If your application uses registry entries in any way then you'll need to be aware.
When you compile your assemblies with "Any CPU" and your assembly is used by an application written for 64bit then the registry entries used will be slightly different.
(thanks to Miral on the msdn forums)
  • .NET app compiled for "x86":
    • Always 32-bit
    • On 32-bit platforms, accesses 32-bit registry
    • On 64-bit platforms, accesses 32-bit registry (inside Wow6432Node)
      • 64-bit registry inaccessible (without doing something weird)
  • .NET app compiled for "x64":
    • Always 64 bit
    • On 32-bit platforms, won't run
    • On 64-bit platforms, accesses 64-bit registry (not inside Wow6432Node)
      • If you want to get to the 32-bit registry, you need to do something weird
  • .NET app compiled for "AnyCpu"
    • Either 32 or 64 bit depending on platform
    • On 32-bit platforms, accesses 32-bit registry
    • On 64-bit platforms, accesses 64-bit registry (not inside Wow6432Node)
      • If you want to get to the 32-bit registry, you need to do something weird

July 07, 2010

Roles in ASP.NET

Roles are part of the Authorization in ASPNET i.e. a mechanism to tell if the user has or has not access to resources.

Roles are a mechanism to group users into sets of permissions.
Roles can reuse already existing groups from windows. Roles can also be linked into a SQL database.
Roles are configured on the aspnet websites web.config.

http://msdn.microsoft.com/en-us/library/ff647401.aspx

XMLSerializer and .NET CLR (sgen.exe)

You might have spotted on your .NET projects in Visual Studio a radiobutton to turn on/off serialization "Generate serialization assembly" in your project's property's Build tab , so what's that all about?

Serialization is a mechanism for recreating .NET objects from text. There's another post in this blog on the topic. So why is this option on your project? in brief it's there as a performance improvement for .NET CLR.

.NET serializes the assemblies when loading, if you tick the "Generate serialization assembly" listbox your creating a second assembly to accompany the original, the second assembly , with extension .xmlserialize.dll , will be loaded by the CLR at load load if it exists, this improves performance at load time because now the CLR does not have to serialize the original assembly at load time instead if can just load the already existing second assembly.

The second assembly is generated with Visual Studio with a tool called sgen.exe.

June 03, 2010

Interop Assemblies

What the hell are these Interop Assemblies, Primary Interop Assemblies (PIAs)?

You'll see these assemblies from time to time pulled in as references in you projects, but I never really cared why they were called Interop and what it meant, I'll explain.

Interop is short for interoperability meaning how to get .NET to talk to COM.

Primary Interop Assembly (PIA):
A PIA is an interop assembly that is signed by the originator to mark it as the one and only assembly to use to get the Type information. It's used to avoid conflicting Types. The assembly is signed in a particular way using the tlbimp.exe and then used by the client to resolve Types.

What have they got to do with COM?
So implementations and Types available through COM is not accessible itself through .NET itself in the usual manner i.e. you cannot new up objects etc because you do not know the Type names. To get over this the COM Types are wrapped into an Interop Assembly. Interop is short for interoperability meaning how to get .NET to talk to COM.
So using some mechanism we want to extract all the Type information on the COM Types into a nice assembly which we can then pass around as references to let clients know what Types are available from COM. One tool we can uses is tlbimp.exe. This tool is ran against the COM Type and results in an assembly with all the Type information of those COM Types found, it does not contain the implementations, they still exist in COM.
The usefulness of this is you can add a reference to this Interop assembly to you .NET project in Visual Studio and then us the Types like ordinary .NET types allowing you to new up objects etc without having to worry about the COM mechanism which runs in the background.


What is TLB and a .tlb file?
tlb stands for Type Library. A .tlb file is a file that contains the COM Type information. The COM Type information does not have to be in a .tlb file, it can also be in an assembly or other file types such as .ocx or .olb.
A tlb file can be generated using the tlbimp.exe http://msdn.microsoft.com/en-us/library/tt0cf3sx.aspx



What does the "Embed Interop Type" property do in Visual Studio?
In .NET 4, Visual Studio 2010, you have the ability to include references to Interop Assemblies with the property "Embed Interop Type" (you'll see then in the assemblies properties window after you add the reference). This is known as "design-time-only interop assemblies". This embeds the interop type information into the current executable/assembly, the benefit is you do not have to redeploy the interop assemblies with your application afterwards. This is handy as when using installers etc you usually have to copy the interop assemblies to the clients machine, this new mechanism removes that requirement.