Load an assembly at runtime(dynamic loading)

Problem:
1. We need to follow Plugin Architecture. i.e Loading Asseblies at runtime dynamically

2. An assembly that an application must use at runtime is present in some folder on the system, and has to be loaded at runtime.

Solution:
We can use a combination of
AssemblyResolve event, Assembly.Load and .Net Reflection.

Please follow the links below for a complete understanding of HOW !

ref:


Assembly.LoadFile versus Assembly.LoadFrom - .NET obscurity at its finest by Josh Fischer -http://www.codeproject.com/KB/dotnet/AssemblyLoadFile.aspx


Rotem Bloom's Blog - http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/03/how-to-load-an-assembly-at-runtime-from-specific-location.aspx


Haibo Luo's weblog - http://blogs.msdn.com/haibo_luo/archive/2005/11/17/494009.aspx


Loading and Unloading an Assembly at Runtime -http://www.codeproject.com/KB/cs/Assemblies___Appdomains.aspx

http://www.codeproject.com/KB/dotnet/AssemblyLoadFile.aspx


How the Runtime Locates Assemblies - http://msdn.microsoft.com/en-us/library/yx7xezcf.aspx


Loading assemblies (references) during runtime - http://www.danielahill.com/post/Loading-assemblies-(references)-during-runtime.aspx


How to: Load Assemblies into an Application Domain -

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

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/7eba3253-8f4d-4271-a1b1-23989926d5e9

http://social.msdn.microsoft.com/forums/en-US/clr/thread/093c3606-e68e-46f4-98a1-f2396d3f88ca/


StackOverflow.com Articles -

http://stackoverflow.com/questions/465488/c-load-assemblies-at-runtime

http://stackoverflow.com/questions/468243/c-load-assemblies-at-runtime-again

.NET Framework Tools

The Microsoft .NET Framework SDK tools are designed to make it easier for you to create, deploy, and manage applications and components that target the .NET Framework.
You can run all the tools from the command line with the exception of the Assembly Cache Viewer (
Shfusion.dll) and the Microsoft CLR Debugger (DbgCLR.exe). You must access Shfusion.dll from Microsoft Windows Explorer. DbgCLR.exe is located in the Microsoft.NET\FrameworkSDK\GuiDebug folder.

Note If you are using the .NET Framework version 1.1, you can run the tools from the command line, but you must set the correct Path, Include, and Lib environment variables in each command prompt session. To set the environment variables, open a command prompt session and run the SDKVars.bat file located in the
systemroot\Microsoft.NET\SDK\v1.1\Bin directory.

  1. Configuration and Deployment Tools
  2. Debugging Tools
  3. Security Tools
  4. General Tools


Configuration and Deployment Tools

ToolDescription
ASP.NET IIS Registration Tool (Aspnet_regiis.exe)Allows an administrator or installation program to update the scriptmaps for an ASP.NET application to point to the ASP.NET ISAPI version associated with the tool. You can also use the tool to perform other ASP.NET configuration operations.
Assembly Cache Viewer (Shfusion.dll)Allows you to view and manipulate the contents of theglobal assembly cache using Windows Explorer.
Assembly Linker (Al.exe)Generates a file with an assembly manifest from one or more files that are either resource files or Microsoft intermediate language (MSIL) files.
Assembly Registration Tool (Regasm.exe)Reads the metadata within an assembly and adds the necessary entries to the registry, which allows COM clients to create .NET Framework classes transparently.
Assembly Binding Log Viewer (Fuslogvw.exe)Displays details for failed assembly binds. This information helps you diagnose why the .NET Framework cannot locate an assembly at run time.
Global Assembly Cache Tool (Gacutil.exe)Allows you to view and manipulate the contents of the global assembly cache and download cache. While Shfusion.dll provides similar functionality, you can use Gacutil.exe from build scripts, makefile files, and batch files.
Installer Tool (Installutil.exe)Allows you to install and uninstall server resources by executing the installer components of a specified assembly.
Isolated Storage Tool (Storeadm.exe)Lists or removes all existing stores for the currently logged-on user.
Native Image Generator (Ngen.exe)Creates a native image from a managed assembly and installs it in the native image cache on the local computer.
.NET Framework Configuration Tool (Mscorcfg.msc)Provides a graphical interface for managing .NET Framework security policy and applications that use remoting services. This tool also allows you to manage and configure assemblies in the global assembly cache.
.NET Services Installation Tool (Regsvcs.exe)Adds managed classes to Windows 2000 Component Services by loading and registering the assembly and generating, registering, and installing the type library into an existing COM+ 1.0 application.
Soapsuds Tool (Soapsuds.exe)Helps you compile client applications that communicate with XML Web services using a technique called remoting.
Type Library Exporter (Tlbexp.exe)Generates a type library from a common language runtime assembly.
Type Library Importer (Tlbimp.exe)Converts the type definitions found within a COM type library into equivalent definitions in managed metadata format.
Web Services Description Language Tool (Wsdl.exe)Generates code for XML Web services and XML Web services clients from Web Services Description Language (WSDL) contract files, XML Schema Definition (XSD) schema files, and .discomap discovery documents.
Web Services Discovery Tool (Disco.exe)Discovers the URLs of XML Web services located on a Web server, and saves documents related to each XML Web service on a local disk.
XML Schema Definition Tool (Xsd.exe)Generates XML schemas that follow the XSD language proposed by the World Wide Web Consortium (W3C). This tool generates common language runtime classes andDataSet classes from an XSD schema file.


Debugging Tools

ToolDescription
Microsoft CLR Debugger (DbgCLR.exe)Provides debugging services with a graphical interface to help application developers find and fix bugs in programs that target the runtime.
Runtime Debugger (Cordbg.exe)Provides command-line debugging services using the common language runtime Debug API. Used to find and fix bugs in programs that target the runtime.


Security Tools

ToolDescription
Certificate Creation Tool (Makecert.exe)Generates X.509 certificates for testing purposes only.
Certificate Manager Tool (Certmgr.exe)Manages certificates, certificate trust lists (CTLs), and certificate revocation lists (CRLs).
Certificate Verification Tool (Chktrust.exe)Verifies the validity of a file signed with an X.509 certificate.
Code Access Security Policy Tool (Caspol.exe)Allows you to examine and modify machine, user, and enterprise-level code access security policies.
File Signing Tool (Signcode.exe)Signs a portable executable (PE) file with an Authenticode digital signature.
Permissions View Tool (Permview.exe)Displays the minimal, optional, and refused permission sets requested by an assembly. You can also use this tool to view all declarative security used by an assembly.
PEVerify Tool (PEverify.exe)Performs MSIL type safety verification checks and metadata validation checks on a specified assembly.
Policy Migration Tool (Migpol.exe)Migrates security policy between two compatible versions of the .NET Framework.
Secutil Tool (Secutil.exe)Extracts strong name public key information or Authenticode publisher certificates from an assembly, in a format that can be incorporated into code.
Set Registry Tool (Setreg.exe)Allows you to change the registry settings for the Software Publishing State keys, which control the behavior of the certificate verification process.
Software Publisher Certificate Test Tool (Cert2spc.exe)Creates, for test purposes only, a Software Publisher's Certificate (SPC) from one or more X.509 certificates.
Strong Name Tool (Sn.exe)Helps create assemblies with strong names. Sn.exe provides options for key management, signature generation, and signature verification.


General Tools

ToolDescription
Common Language Runtime Minidump Tool (Mscordmp.exe)Creates a file containing information that is useful for analyzing system issues in the runtime. The Microsoft Dr. Watson tool (Drwatson.exe) invokes this program automatically.
License Compiler (Lc.exe)Reads text files that contain licensing information and produces a .licenses file that can be embedded in a common language runtime executable.
Management Strongly Typed Class Generator (Mgmtclassgen.exe)Allows you to quickly generate an early-bound class in C#, Visual Basic, or JScript for a specified Windows Management Instrumentation (WMI) class.
MSIL Assembler (Ilasm.exe)Generates a PE file from Microsoft intermediate language (MSIL). You can run the resulting executable, which contains MSIL code and the required metadata, to determine whether the MSIL code performs as expected.
MSIL Disassembler (Ildasm.exe)Takes a PE file that contains MSIL code and creates a text file suitable as input to the MSIL Assembler (Ilasm.exe).
Resource File Generator Tool (Resgen.exe)Converts text files and .resx (XML-based resource format) files to .NET common language runtime binary .resources files that can be embedded in a runtime binary executable or compiled into satellite assemblies.
Windows Forms ActiveX Control Importer (Aximp.exe)Converts type definitions in a COM type library for an ActiveX control into a Windows Forms control.
Windows Forms Class Viewer (Wincv.exe)Finds managed classes matching a specified search pattern, and displays information about those classes using the Reflection API.
Windows Forms Resource Editor (Winres.exe)Allows you to quickly and easily localize Windows Forms forms.

.Net(C#) Programming Tips

1. Virtual vs Abstract

Virtual methods allow subclasses to provide their own implementation of that method using the override keyword. A virtual method can be part of any class and needs to have body. A class with only virtual (or) non_virtual methods can be instantiated.

Abstract methods in a class contain no method body, and are implicitly virtual.If a class has any abstact methods, then it must tag itself as abstract, and no instances of it can be created.

Neither abstract or virtual can be declared private, since it would defeat the purpose, and subclasses must override them using the same method signature and "override" keyword.


2. Abstract Classe vs Interface

An abstract base class is needed in a different situation. Some times you can write most of the implementation of a class but not all of it. perhaps you have some classes that have a lot in common, and could really use a parent class, but some of the methods and/or properties don't generalize well. Let’s take the example of Image. There are lots of different kinds of images: bit maps, jpegs, gifs, tiffs, etc. You want all of those kinds of images to have (mostly) the same methods and properties, for example you want them all to have a RotateFlip() method to allow the caller to rotate the image, but you can't write a meaningful implementation for that method until you know what kind of image you're dealing with.

You need an interface if you want to assign common behaviour to various classes that do not derive from the same base class (other than Object). The excellent example of IEnumerable: you want to be able to make many classes from all over the class hierarchy enumerable, and in some methods treat them as "the same" for purposes of enumeration, even though they're otherwise completely different classes that have nothing in common. If you create an abstract class with no method implementation and no data members it is pretty much the same as defining an interface.

In general there are a number of differences.

1. In abstract classes you can have data members to keep, for instance, internal state

2. In abstract classes you can provide implementation for a method:

say you have a Vehicle abstract class, you can derive Bike, MotorCycle and Car from that, but you might want to define a method GetCC() in the base class that will never change (no can do with interfaces)

3. C# object can implement as many interface you want but can just inherit from one class.

4. An abstract class can have constructor declaration while an interface can not do so.

5. An abstract Class is allowed to have all access modifiers for all of its member declaration while in interface we can not declare any access modifier(including public) as all the members of interface are implicitly public.

ref:

http://bytes.com/topic/c-sharp/answers/259751-confuesd-about-abstract-class-vs-interface

http://www.c-sharpcorner.com/UploadFile/prasoonk/AbstractClassvsInterface06102009051117AM/AbstractClassvsInterface.aspx


3. Delegate vs Interface

Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method. Given these similarities, when should a class designer use a delegate and when should it use an interface?

Use a delegate in the following circumstances:

· An eventing design pattern is used.

· It is desirable to encapsulate a static method.

· The caller has no need to access other properties, methods, or interfaces on the object implementing the method.

· Easy composition is desired.

· A class may need more than one implementation of the method.

Use an interface in the following circumstances:

· There is a group of related methods that may be called.

· A class only needs one implementation of the method.

· The class using the interface will want to cast that interface to other interface or class types.

· The method being implemented is linked to the type or identity of the class: for example, comparison methods.

ref:

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


4. XAML Compilation: BAML

The creators of WPF knew that XAML needed to not just solve the problem of design collaboration - it also needed to be fast. And though XML-based formats such as XAML are flexible and easily portable to other tools and platforms, they aren’t always the most efficient option. XML was designed to be logical, readable, and straightforward - not compact.

WPF addresses this shortcoming with BAML (Binary Application Markup Language). BAML is really nothing more than a binary representation of XAML. When you compile a WPF application in Visual Studio, all your XAML files are converted into BAML and that BAML is then embedded as a resource into the final DLL or EXE assembly. BAML is tokenized, which means lengthier bits of XAML are replaced with shorter tokens. Not only is BAML significantly smaller, it’s also optimized in a way that makes it faster to parse at runtime.


5. WPF and XAML

XAML and WPF are separate, albeit complementary, technologies. As a result, it’s quite possible to create a WPF application that doesn’t use the faintest bit of XAML.

Altogether, there are three distinct coding styles that you can use to create a WPF application:

  1. Code-only - This is the traditional approach used in Visual Studio for Windows Forms applications. It generates a user interface through code statements.

  1. Code and uncompiled markup (XAML) - This is a specialized approach that makes sense in certain scenarios where you need highly dynamic user interfaces. You load part of the user interface from a XAML file at runtime using the XamlReader class from the System.Windows.Markup namespace.

  1. Code and compiled markup (BAML) - This is the preferred approach for WPF, and the one that Visual Studio supports. You create a XAML template for each window and this XAML is compiled into BAML and embedded in the final assembly. At runtime the compiled BAML is extracted and used to regenerate the user interface.


6. ThreadPool.QueueUserWorkItem vs Delegate.BeginInvoke

Both Delegate.BeginInvoke and ThreadPool.QueueUserWorkItem will execute on a thread pool thread.

The difference is that if you call BeginInvoke, you're obliged to call EndInvoke at some point. In contrast, ThreadPool.QueueUserWorkItem is "fire and forget". That has benefits and drawbacks. The benefit being that you can forget about it. The drawback being that you have no way of knowing, unless you add your own synchronization/notification mechanism, when the task has completed.

ref :

http://en.csharp-online.net/XAML—XAML_Compilation


7. Automated White Box Testing for .NET with Pex

Pex (Program EXploration) produces a traditional unit test suite with high code coverage. A parameterized unit test is simply a method that takes parameters, calls the code under test, and states assertions. Given a parameterized unit test written in a .NET language, Pex automatically produces a small unit test suite with high code and assertion coverage. To do so, Pex performs a systematic white box program analysis.

Pex learns the program behavior by monitoring execution traces, and uses a constraint solver to produce new test cases with different behavior. At Microsoft, this technique has proven highly effective in testing even an extremely well-tested component. Pex is now capable of producing NUnit and MSUnit tests.

ref :

http://research.microsoft.com/en-us/projects/Pex/


8. Moles - Detours for .NET

Moles is an extension of the Stubs framework to detour any .net methods i.e. any static, non-virtual method even in sealed types.To illustrate the moles, we will write a unit test involving DateTime.Now. Traditionally, any code relying on DateTime.Now would be hard to unit test because of the dependency on the machine clock.

ref :

http://research.microsoft.com/en-us/projects/stubs/moles.aspx