Archive for the ‘KM’ Category

AppDomains and AddIn

AppDomains and Addins

What is an Application Domain (AD)?

An Application Domain is a CLR feature that provides a unit of isolation for an application. An AD may be thought of as a lighter weight process boundary. Multiple AppDomains may be created within a host process. The CLR also verifies that the user code in an App domain is type safe. An assembly must be loaded into an application domain before it can run (see default domain). By default, the CLR loads an assembly into the Application Domain containing the code that references it.

Default Domain

When a process that hosts the CLR is created, the CLR automatically creates a default App Domain. Note that there is one CLR per process. I will come back to this in future posts when speaking to versioning, Side by Side (SxS), LockCRL version, etc.. The default App Domain remains as long as the host process lives. The Host code will undoubtly need to live as long as the process, but Add-in’s (Assemblies loaded by the Host) should be isolated from the host code (see isolation).


An isolation boundary provides a level of protection between the Host assembly and the assemblies running in the AD(s). And of course, an Assembly in one AD is also isolated from an assembly loaded in another AD. An isolated assembly may not directly access code or resources in another assembly.

The life time of an Add-in(s) may not be as long as the life time of the host process. The Host should have control over the Add-in’s life time and via isolation the Host has the opportunity to control the temporal nature of Add-in’s. The host may also load multiple Add-in’s into the same App Domain (clumping) where they have like semantics, such as; shared security context, life times, shared resources, etc.. In the case of ASP.net this is the model. Imagine a server application that loaded transient code into its process but never had the ability to unload and therefore release resources. The resources consumed would never be reclaimed.


There is no ability within the CLR to unload an assembly (Why not?) at run time. The ability to unload an assembly is made possible via unloading an AppDomain and thus the assembly or assemblies within the AppDomain.


As a host, you must be conscience of the remoting boundary in your programming model. Since you are crossing an AppDomain boundary (just as you would when crossing a process boundary) your objects need to be MarshalByRef (MBRO) and instantiated via System.Runtime.Remoting. There is a brief discussion on this subject in JasonZ’s blog comments. Alternatively you could use serialization but you loose the reference semantics as you are making a copy. For a great write up on value and reference types follow this link.

There are versioning considerations you need to understand when communicating between components. The good news, is that we have the WinFX AddIn model libraries and forth coming guidance on design considerations to help you in this regard. I will be blogging more on this subject and maybe even co-authoring a book on the subject, if the demand is warranted (hint, hint – tell me if you would find this valuable).


Declaring assemblies to have domain-neutral behavior may be accomplished via the runtime hosting interfaces (see the framework SDK CorBindToRuntimeEx). Loading code that is domain neutral will improve performance on subsequent referencing of the same code in additional AppDomains, because the assembly code pages will be shared across the AppDomains.

So then the question arises as to why not load everything domain-neutral. The primary reason is that domain-neutral code may not be unloaded. So does this conflict with the Add-in model guidance of unloadability and isolation? No, the majority of the scenarios addressed by the Add-in model would not have Add-in’s loaded in the GAC, nor desired to be shared across AD’s. Common functionality offered by the hosting application to the Add-in’s, is a likely candidate for domain-neutrality as opposed to Add-in assembly neutrality. You may wish to reread that last sentence ;-). These classifications of Host provided assemblies are available to consumers (Add-in’s) for the duration of the Host process. So there should be no conflict in the Add-in model isolation and unloadability recommendation and domain-neutrality.

In v1.0 and v1.1 native images that Ngen.exe produces cannot be shared (domain-neutrality) across AD’s. In v2.0, native images that Ngen.exe produces can be shared (domain-neutrality) across AD’s.

AppDomainSetup Properties

There are additional properties to the ones I touch on below, but I wanted to call out two primary properties of interest.


The ApplicationBase is the root directory of the application. When an AppDomain is created, it inherits the ApplicationBase of the AppDomain creator (the Host in the Add-in model). When an assembly is loaded from disk, the CLR uses this root as the probing path. It is very likely that the Add-in will be installed in a different directory than the host application. In the majority of the cases, the two are installed and uninstalled independently of each other.


The optional configuration file, is an XML file, that has settings for the application. Most people are familiar with the concept when they think about machine.config. The configuration file can be used for declaring a startup shim, versioning rules, etc.. The configuration file will be something along the lines of MyApp.exe.config or MyApp.dll.config.


A host can control policy in two ways.
1. The host can provide evidence when creating the AD.
2. The host can restrict the permissions granted at a policy level.


It could be argued that this is a lot of work. However, the CLR and the framework, already simplify much of this for you. Of course, as the Host, you must hook up all the various functionality provided via the framework. The number of Hosts (ISV’s and large application providers) that need to provide this functionality is small in comparison to the number of customizations/applications/Add-in’s that will be written against a Host application. So the complexity, and thus the burden, is placed on a significantly fewer number of developers. And to further simplify the lives of ISV’s, which is my current job :-), we have the System.AddIn* offering.



Read Full Post »

CAB WorkItem


1. A WorkItem is a class encapsulating logic for one dedicated use case.
2. It can be seen as a use case controller that knows all the different aspects of a use case.
3. A WorkItem holds state for all parts involved in a use case, such as views necessary to display, or sub-use cases.
4.It acts as an entry point into the use case (or one of its sub-use cases) it is responsible for.

POINT: A WorkItem can be composed of other nested WorkItems, each of which can have its own state. This state is analogous to ASP.NET session state.

POINT:You can use special persistence techniques to save WorkItems and then restore them later.

POINT:WorkItems are arranged in a tree-like chain, as shown on the facing page. The root work item, the base of the chain, is created by the shell application as part of its start-up process, as you saw in the preceding chapter. When modules are loaded into the process, they create work items and add them as children to the root work item’s chain.

WorkItem Details

The main purpose of a WorkItem today is to facilitate loose coupling by holding certain classes of objects in well-known locations so that other objects can find the resources that they need to do their jobs. To accomplish this, the WorkItem class contains a number of collections, as shown in Table 3-1. All of them are strongly typed except Items, which exists to hold anything not served by a strongly typed collection.

Property Name Description
——– ————————————–
Commands Command objects, used for tying .NET events from user interface objects such as menus to business logic methods.
EventTopics EventTopic objects, used in conjunction with CAB’s loosely coupled publish-and- subscribe event system (see Chapter 6).
Items All objects contained in this WorkItem that do not belong in any of the other collections, which are strongly typed. Web service proxies are a good example of the sort of thing that you often find here, as are WorkItem controllers.
Services CAB services
Smart Parts Smart Parts, which are objects with the SmartPart attribute applied to them, also known as views.
State State collection associated with this WorkItem.
UIExtensionSites UIExtensionSite objects, used for negotiating the content of shared user interface items such as menus and toolbars.
WorkItems Child WorkItems that belong to this WorkItem.
Workspaces Workspace objects, which are frames used for visual display of views.

Adding objects or Items in WorkItem


Objects are created and placed into the collections of a WorkItem in various ways. Sometimes this happens because of declarative attributes that are placed onto a class or a method
For example, the following code appears in the ShellForm class generated by the SCSF Wizard:


public void StatusUpdateHandler(object sender, EventArgs e)

The EventSubscription attribute, when processed by the CAB framework, tells the framework to find the EventTopic object whose name is StatusUpdate in the WorkItem causing the load, creating it if necessary, and to add this particular subscription to it. That EventTopic is created and added to the WorkItem collection the first time this attribute is encountered by the CAB framework processing.

WAY:2 By ObjectBuilder

Other types of objects are added to WorkItems transparently when the CAB object builder creates them. In the ShellForm created by the SCSF, the object builder notes when it is creating the shell form that some of the child controls on the main form are Workspaces and not just plain windows. After creating them, the object builder places them into the root work item’s Workspaces collection.

WAY:3 By calling the AddNew method

Fetch an item from a WorkItem

To fetch an item from a WorkItem collection to use it, you usually use the Get method. When using the Services collection, as you saw in the preceding lesson, you specify the interface for which you want the implementing service, thus:

private void AuthenticateUser()
// Fetch the authentication service from the root work item,
// and call the method to make it authenticate the user.
IAuthenticationService auth =rootWorkItem.Services.Get(true);

The objects in the other collections are designated by string names. You fetch the desired item by indexing the collection with the string name, thus:

// User clicked this button. Look at event topic and
// fire it programmatically.
private void toolStripButton3_Click(object sender, EventArgs e)
EventTopic et =_rootWorkItem.EventTopics[EventTopicNames.StatusUpdate] ;
if (et != null)
et.Fire(this, new EventArgs(“Fired programmatically”),_rootWorkItem, PublicationScope.Global );

Disposing WorkItem

The WorkItem class provides this capability by implementing the IDisposable interface. If you call Dispose on a WorkItem, it iterates through all its collections and calls Dispose on every item that supports that interface. In the CabApplication class startup code, for example, the Run method calls Dispose on the root WorkItem to clean it up as the application is terminating

Read Full Post »

Composite UI Application Block (CAB)

The Composite UI Application Block is a ready-to-use building block provided by the Microsoft patterns & practices group for creating complex, modularized smart client applications. This building block basically provides the following functionality:
1 Dynamically loading independent yet cooperating modules into a common shell
2 Event broker for loosely coupled communication between modules and parts of modules
3 Ready-to-use Command pattern implementation
4 Base classes for Model-View-Control (MVC) pattern implementations
5 Framework for pluggable infrastructure services ranging, such as authentication services, authorization services, module location, and module loading services

CAB is built for designing applications based on a use case¡Vdriven approach by clearly separating use case controller classes from views with their controller classes or presenter classes. Central client-side services can be added through the services infrastructure provided by CAB.

Major terms related to CAB that are important for architectural decisions.

A WorkItem is a class encapsulating logic for one dedicated use case. It can be seen as a use case controller that knows all the different aspects of a use case. As such, a WorkItem holds state for all parts involved in a use case, such as views necessary to display, or sub-use cases. Furthermore, it acts as an entry point into the use case (or one of its sub-use cases) it is responsible for.

Services encapsulate functionality that is common for the whole client application, for a specific module, or just for WorkItems within a certain hierarchy of WorkItems (for example, for sub-WorkItems of a specific parent WorkItem). Typical services are security services responsible for authentication or authorization or Web service agents encapsulating service communication and offline capability.

Multiple, logically related WorkItems can be summarized into a single unit of deployment. A module is an example of a unit of deployment. Configuration of CAB-based smart clients basically works on a module-level. Therefore, finding the right granularity for encapsulating WorkItems into modules is crucial.

The profile catalog is just a configuration that specifies which modules and services need to be loaded into the application. By default, the catalog is just an XML file that resides in the application directory. This XML file specifies which modules need to be loaded. By writing and registering a custom IModuleEnumerator class, you can override this behavior to get the catalog from another location, such as a Web service.

This is a general service provided by CAB, which is responsible for loading all the modules specified in a profile catalog. It just walks through the configuration of the profile catalog, tries to dynamically load the assembly specified in a catalog entry, and then tries to find a ModuleInit class within that assembly.

Each module consists of a ModuleInit class, which is responsible for loading all the services and WorkItems of a module.

Shell application
The Shell application is the primary application that is responsible for initializing the application. It is responsible for dynamically loading modules based on the configuration and launching the base services for the smart client application, in addition to starting the main form (Shell).

This is the main form of the application; it provides the user interface that is common to all dynamically loaded modules. The Shell always hosts the root WorkItem, which is the entry point into any other parts of the application, such as services, modules, and WorkItems that are created and registered by these modules.

A workspace is a control that is primarily responsible for holding and displaying user interface elements created by WorkItems. Usually workspaces are added to the Shell (or to other extensible views within your WorkItem hierarchy) and act as containers for parts of the UI that are going to be dynamically filled with UI items that are provided by WorkItems or sub-WorkItems. Any user control can be a workspace by implementing the IWorkspace interface. Out-of-the-box, CAB includes classic container controls as workspaces, such as a tabbed workspace.

UIExtensionSites are special placeholders for extending fixed parts of the Shell such as menus, tool strips or status strips. Unlike workspaces, they are intended to be used for parts of the UI, which should not be completely overridden by WorkItems; instead, they should just be extended (such as adding a new menu entry).

Command is a base class of CAB for implementing the Command pattern. CAB supports classic commands created manually or declarative commands by applying the [CommandHandler] attributes to the method; these attributes act as command handlers. You can register multiple invokers for one command

EventPublications are used by event publishers for loosely coupled events. An event publisher implements the event through .NET Framework events that are marked with the [EventPublication] attribute. Events are uniquely identified by event URIs (unique strings). Only subscribers using subscriptions with the same event URI will be notified by CAB. A subscriber needs to have a method with the same signature as the event used [EventPublication] and needs to be marked with the [EventSubscription] attribute.

EventSubscription is the opposite of EventPublication. Any class that wants to subscribe to an event with a specific event URI needs to implement an event handler that matches the method signature of the EventPublication. You must mark this event handler with the [EventSubscription] attribute and the publisher’s event URI (in the attribute’s constructor) and CAB makes sure that a subscriber will be notified each time a publisher raises an event with a matching event URI and method signature.

Model is the (client-side) business entity a WorkItem processes; for example, Customer, BankAccount, or Loan.

View is an ordinary .NET Framework user control that is responsible for presenting a part of or the whole model to the user and allowing the user to modify its contents through user interface controls. Typically, the view implements only UI logic; whereas the related client-business logic is implemented in the presenter/controller.

A SmartPart is a .NET Framework user control with the [SmartPart] attribute applied. Optionally, a SmartPart can implement the ISmartPartInfoProvider interface. As such, it provides additional information about itself, such as a caption or a description.

Controller is a class that implements the logic for modifying a model. One controller can modify a model presented by many views. Origin: Model-View-Controller

ObjectBuilder is a foundation component of CAB that acts as the factory for creating objects that require specific builder strategies to be created or that need features, such as automatic instantiation and initialization of dependant objects when creating instances. As such, the ObjectBuilder has a combined role as a factory, a dependency injection framework, and a builder strategy framework.

Dependency Injection
Dependency Injection is a pattern that allows a factory to automatically create or initialize properties or members of objects with dependant objects. ObjectBuilder provides this functionality.

A WorkItemController is a class introduced by the Smart Client Software Factory that encapsulates common initialization logic for a WorkItem. When creating WorkItems with SCSF, instead of directly inheriting from the WorkItem base class, you inherit from this class to get the added initialization logic.

Again, this is a class introduced by the Smart Client Software Factory; it is a generic class for instantiating new WorkItems based on a WorkItemController. It launches the added initialization entry points provided by the WorkItemController for you.

ModuleController classes are introduced by the Smart Client Software Factory and are used for encapsulating a special WorkItem within a module taking on the role of a root WorkItem within a module. The default ModuleInit implementation of a module created with the Smart Client Software Factory automatically creates a WorkItem for a module named ModuleController. Therefore, the ModuleController is the primary entry point for all WorkItems provided by a module.

Presenter is a class that implements the logic for one single
SmartPart (view). The presenter is based on the Model-View-Presenter (MVP) pattern, which is basically a simplified variant of the Model-View-Controller (MVC) pattern. The big difference between MVP and MVC is that with MVP, the View is completely controlled by the presenter, whereas in the MVC, the controller and the model can update the view.

Happy Coding…:)

Read Full Post »

What is the difference between abstract class and interface?

If a class is to serve the purpose of providing common fields and members to all subclasses, we create an Abstract class. For creating an abstract class, we make use of the abstract keyword. Such a class cannot be instantiated. Syntax below:

abstract public class Vehicle { }

Above, an abstract class named Vehicle has been defined. We may use the fields, properties and member functions defined within this abstract class to create child classes like Car, Truck, Bike etc. that inherit the features defined within the abstract class. To prevent directly creating an instance of the class Vehicle, we make use of the abstract keyword. To use the definitions defined in the abstract class, the child class inherits from the abstract class, and then instances of the Child class may be easily created.
Further, we may define abstract methods within an abstract class (analogous to C++ pure virtual functions) when we wish to define a method that does not have any default implementation. Its then in the hands of the descendant class to provide the details of the method. There may be any number of abstract methods in an abstract class. We define an abstract method using the abstract keyword. If we do not use the abstract keyword, and use the virtual keyword instead, we may provide an implementation of the method that can be used by the child class, but this is not an abstract method.
Remember, abstract class can have an abstract method, that does not have any implementation, for which we use the abstract keyword, OR the abstract class may have a virtual method, that can have an implementation, and can be overriden in the child class as well, using the override keyword. Read example below

Example: Abstract Class with Abstract method
namespace Automobiles
public abstract class Vehicle
public abstract void Speed() //No Implementation here, only definition

Example: Abstract Class with Virtual method
namespace Automobiles
public abstract class Vehicle
public virtual void Speed() //Can have an implementation, that may be overriden in child class


Public class Car : Vehicle
Public override void Speed()
//Here, we override whatever implementation is there in the abstract class
//Child class implementation of the method Speed()

An Interface is a collection of semantically related abstract members. An interface expresses through the members it defines, the behaviors that a class needs to support. An interface is defined using the keyword interface. The members defined in an interface contain only definition, no implementation. The members of an interface are all public by default, any other access specifier cannot be used. See code below:

Public interface IVehicle //As a convention, an interface is prefixed by letter I
Boolean HasFourWheels()

Difference between Abstract Class and Interface

1) A class may inherit only one abstract class, but may implement multiple number of Interfaces. Say a class named Car needs to inherit some basic features of a vehicle, it may inherit from an Aabstract class named Vehicle. A car may be of any kind, it may be a vintage car, a sedan, a coupe, or a racing car. For these kind of requirements, say a car needs to have only two seats (means it is a coupe), then the class Car needs to implement a member field from an interface, that we make, say ICoupe.
2) Members of an abstract class may have any access modifier, but members of an interface are public by default, and cant have any other access modifier.
3) Abstract class methods may OR may not have an implementation, while methods in an Interface only have a definition, no implementation.

Happy Coding….!!!

Ref: http://www.dotnetuncle.com

Read Full Post »

Consider below Example to understand difference between Timespan.Milliseconds and Timespan.TotalMilliseconds

Consider timespan pDif value is 00:00:30.9340203 and

pDif.Seconds = 30
pDif.Milliseconds = 934

So is it correct to assume that the total time span, in MILLISECONDS is then 30,934 using the following formula:

TotalMilliseconds = TimeSpan.Milliseconds + (TimeSpan.Seconds * 1000)

Read Full Post »

This tip provides a way to access the user control’s variables inside an ASP.NET
Web page.

Assume that strVar is the variable declared in the user control’s code-behind
file. To access the variable in the ASP.NET Web page called webform1.aspx,
follow these two steps:

Declare strVar as public in the user control’s code.

Use the Register directive to register the user control in the Web page called

<%@ Register TagPrefix=”UC” TagName=”MyCon” src=”webusercontrol1.ascx”%>

The following shows how to instantiate the user control:

<uc:mycon id=”mycon1″ runat=”server”></uc:mycon>

This is the actual way to access the variable:

<%= mycon1.strVar %>

Read Full Post »

Asp.Net 2.0 Menu Control is not working with Mac Safari browser properly.
Use below code to your page_load event and see the magic

if (Request.UserAgent.IndexOf(“AppleWebKit”) > 0)


if you are using Master page then paste this code into master page code behind page.

for more detail Click here

Read Full Post »

Older Posts »