Monday, December 19, 2016

Preserve Stacktrace in C# without reflection: ExceptionDispatchInfo Class

Exception handling is a basic build block of any application. To identify the actual problem through exception handling, stack trace play an important role.
Stack-trace contains information about method call hierarchy from beginning to actual point of exception. But sometimes exception handled in wrong way and application loose actual stack trace.
Prior to .net framework 4.5, developer has to perform reflection to preserve stack trace by calling "InternalPreserveStackTrace()" internal method. But this solution is not easy and can degrade the application performance.
.Net framework 4.5 introduces a new class ExceptionDispatchInfo. This class provide method ExceptionDispatchInfo.Capture(Exception) to take the snapshot of exception at any point of time and preserve the all exception information. These snap-shot can be re-throw at any future point of time using ExceptionDispatchInfo.Throw Method (). Throw method preserves the stack-trace and other exception information. This method can be useful in some scenarios mention scenarios.
  1. In multi-threaded application, capture the exception in child thread and raise it in main/parent thread.
var exceptionList = new BlockingCollection<ExceptionDispatchInfo>();
ThreadPool.QueueUserWorkItem(()=>
{
    try
    {
        // Code that may raise exception.
    }
    catch (Exception ex)
    {
        ExceptionDispatchInfo exceptionInfo = ExceptionDispatchInfo.Capture(ex);
        exceptionList.Add(exceptionInfo);
    }
    exceptionList.CompleteAdding();
});

foreach (ExceptionDispatchInfo exceptionInfo in exceptionList.GetConsumingEnumerable())
{
    try
    {
      exceptionInfo.Throw();
    }
    catch (Exception ex)
    {
        Console.WriteLine("{0}", ex);
    }
}


2. Perform some operations to make application stable before raise exception with original stack trace.
private ExceptionDispatchInfo _exceptionInfo=null;

private void MainMethod(){
     ExceptionMethod();
     PerformCleanUpOpsAndRaiseException();
}

private static void ExceptionMethod(){
        try
 {
  // Code that can generate exceptions here
 }
 catch (Exception ex)
 {
  // Perform some operation or Do some logging or whatever
  // Capture snap-shot of exception 'ex'.
  _exceptionInfo = ExceptionDispatchInfo.Capture(ex);
 }
}

private void PerformCleanUpOpsAndRaiseException(){
  // Code that needs to be execute before throwing an exception.
  if(_exceptionInfo!=null){
     // Raise captured exception if any
  _exceptionInfo.Throw();
  }
}

Wednesday, November 21, 2012

CSHandler.com: Difference between Layer and Tier

CSHandler.com: Difference between Layer and Tier: The difference that exists between two terms that are sometimes used interchangeably - layer and tier. Note that using layer and tier inter...

Sunday, July 22, 2012

Store custom data in SharePoint property bag


What is Property Bag?

SharePoint property bag is a place to store metadata or custom property value to different SharePoint objects. Property bag is implemented as a Key-Value pair hash-table.

Why to Use SharePoint Property Bag?

Generally developer use configuration file to store configurable properties like ConnectionString, some FilePath, some other custom setting. Since config file is allowed to store values as Key-Value pair, how property bag is useful to store information?
<configuration>
  <appSettings>
    <add key="WebAppLevelKey" value="MyValue1" />
    <add key="SiteLevelKey" value="MyValue2" />
    <add key="WebLevelKey" value="MyValue3" />
  </appSettings>
</configuration>

In SharePoint config file scope to web-application level so
  • We need to maintain different key-value for different scope because any value in config is same for all SPSite and SPWeb inside the web-application.
  • Config value is same for all users.
  • We should know the value at compile time. Information that is change or decide at run-time can't be store here.

Levels

Property bag is available to SharePoint objects from SPFarm scope to SPList. Following SharePoint objects provide property bag: -
  • SPFarm
  • SPWebApplication
  • SPSite
  • SPWeb
  • SPList

UI to manage Property Bag

SharePoint doesn't provide any interface inside the web to manage property bag. Although SharePoint designer provides a interface to manage property bag.
When you open a site in SharePoint Designer 2010, in the ribbon, all the way over to the right, you’ll see a button for Site Options
SiteOptions





By clicking on it,  a new window is opened. The first tab labeled Parameters. This parameters window is nothing else but a Property Bag window.


SiteOptionsWindow

From this window, you can add/modify/delete the property bag.

Access Property Bag through code

Most of the time property bag is useful to store information decide at run-time. As mention above different level of SharePoint object provides property bag to store data. To manage property bag through code, SharePoint API class exposes.
// Use this RunWithElevatedPrivileges to
// avoid error if user doesn't have permission to update.
SPSecurity.RunWithElevatedPrivileges(delegate()
 {
   try
    {
    using (SPSite RootSite = new SPSite(URL))
     {
      using (SPWeb rootWeb = RootSite.OpenWeb())
       {
       try
        {
         rootWeb.AllowUnsafeUpdates = true;
         // Get property value against MyKey key from Property bag
         if (rootWeb.AllProperties.ContainsKey("MyKey"))
          {
           string myValue = rootWeb.AllProperties["MyKey"].ToString();
          }
          // Set siteID in the Property bag
          rootWeb.Properties["siteID"] = siteID;
          rootWeb.Properties.Update();
          rootWeb.AllowUnsafeUpdates = false;
         }
         catch (Exception ex)
         {
           //Handle Exception
         }
        }
       }
      }
      catch(Exception ex)
      {
      }
   }
);

Store Custom Class Object INTO Property Bag

SharePoint property bag is allow to store any type of data that can be serialize. So to store custom class object, custom class should be mark as serializable.
[System.Serializable]

public class CustomClass{

public string Name{

get;

set;

}

}

Saturday, May 19, 2012

Implementation of Interface Dependency Injection using Microsoft Unity Block 2.0

In my previous article I try to elaborate interface dependency injection. Here I implemented a simple example. For the injection we use the Microsoft Unity 2.0 container. For more information about the Unity 2.0 container please refer MSDN.
This sample has on Project entity class as mention below:
// Project entity class
public class Project {

 public Project(string title, string id) {
  this.title = title;
  this.id = id;
 }

 private string title;

 public string Title {
  get {
   return title;
  }
  set {
   title = value;
  }
 }

 private string id;

 public string ID {
  get {
   return id;
  }
  set {
   id = value;
  }
 }

} 
 
 
To access Project information from database, we have one data layer class
and another is business layer class to implement business logic.
I am assuming that different user have different database so data layer classes
implementation vary for each database type.
So sample project have two data layer class one for sql server and another for Oracle.
 
// Project Data Layer to interact with sql server database.
public class ProjectDLForSQLServer : IProjectDL {

 public Project GetProjectById(int id) {
   Console.WriteLine("IProjectDL is resolved as ProjectDLForSQLServer.");
   Project project = null;
   // logic to access database and return the mapped data object to project entity.
   return project;
 }

 public List<Project> GetProjects() {
   List<Project> projects = null;
   // logic to access database and return the mapped data object to project entity.
   return projects;
 }
}


Another datalayer class for Oracle.

 
 // Project Data Layer to interact with sql server database.
public class ProjectDLForOracle : IProjectDL {

  public Project GetProjectById(int id) {
    Console.WriteLine("IProjectDL is resolved as ProjectDLForOracle.");
    Project project = null;
    // logic to get project from oracle database.
    return project;
  }

  public List<Project> GetProjects() {
    List<Project> projects = null;
    // logic to get projects from oracle database.
    return projects;
  }
} 
 
 
We have single business layer class for project entity. If this business class directly instantiate data layer class as mention below:
 
 
 // Project Business Layer class
public class ProjectBL {

  IProjectDL _projectDL;

  public ProjectBL() {
    // Here it directly instantiating data layer class.
    _projectDL = new ProjectDLForSQLServer();
  }

  public ProjectBL(IProjectDL projectDL) {
    _projectDL = projectDL;
  }

  public Project GetProjectById(int id) {
    return _projectDL.GetProjectById(id);
  }

  public List<Project> GetProjects() {
    return _projectDL.GetProjects();
  }
} 
 

So if we want to deploy same dll on another client using Oracle as a back end.
We need to change in business layer and recompile whole project once again.
And also need to maintain two version of same dll just because of this kind of tight coupling.
Interface interception will solve this problem. By mean of interface interception we can decide at runtime that which class implementation should our code use.
By using Unity 2.0, we can achieve the same. Binding of interface and class implementation can be done either in code or by using xml configuration file.
Here I am using second approach i.e. by xml configuration.
 
 <?xml version="1.0" encoding="utf-8" ?>
<configuration>

<configSections>
<!--A reference to unity dll-->
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<!--Defing assembly reference and namespace of policy injection and our custom dll-->
<assembly name="Microsoft.Practices.EnterpriseLibrary.PolicyInjection"/>
<namespace name="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers"/>

<assembly name="InterfaceInterception" />
<namespace name="InterfaceInterception, InterfaceInterception"/>

<assembly name="ITDataService" />
<namespace name="ITDataService, ITDataService"/>

<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>

<alias alias="IProjectDL" type="InterfaceInterception.IProjectDL, InterfaceInterception"/>
<alias alias="ProjectDLForSQLServer" type="InterfaceInterception.ProjectDLForSQLServer, InterfaceInterception"/>
<alias alias="ProjectDLForOracle" type="InterfaceInterception.ProjectDLForOracle, InterfaceInterception"/>

<alias alias="IewAppsSessionHandler" type="ITDataService.IewAppsSessionHandler, ITDataService"/>
<alias alias="ewAppWebSessionHandler" type="ewAppWeb.ewAppWebSessionHandler, ewAppWeb"/>

<container>

<extension type="Interception"/>
<!-- Here is the mapping of interface to class -->
<register name="IProjectMapper" type="IProjectDL" mapTo="ProjectDLForOracle">
<interceptor type="TransparentProxyInterceptor"/>
<interceptionBehavior type="PolicyInjectionBehavior"/>
</register>

</container>

</unity>

</configuration> 
 
 
Above config file have complete configuration. To use this unity container class
we have created a wrapper class "UContainer"
public class UContainer : IContainerAccessor {

  private static IUnityContainer _container = null;

  public static IUnityContainer Container {
    get {
     return _container;
    }
    set {
     _container = value;
    }
  }

#region IContainerAccessor Members

  IUnityContainer IContainerAccessor.Container {
    get {
     return Container;
    }
  }

#endregion

}

public interface IContainerAccessor {

   IUnityContainer Container {
    get;
   }
} 
 
 
Now all the required configuration and class implementation is completed.
Now time to use configuration to know the binding at runtime. Our business
layer class now have little different implementation.
// Project Business Layer class
public class ProjectBL {

  IProjectDL _projectDL;

  public ProjectBL() {
    // Here we are calling unity container to resolve the IProjectDL implementation.
    _projectDL = UContainer.Container.Resolve<IProjectDL>("IProjectMapper");
  }

  public ProjectBL(IProjectDL projectDL) {
    _projectDL = projectDL;
  }

  public Project GetProjectById(int id) {
    return _projectDL.GetProjectById(id);
  }

  public List<Project> GetProjects() {
    return _projectDL.GetProjects();
  }
} 
 
 
In above class I don't use any class, to resolve the current implementation to be use, use unity container.
We just missing one thing that is initialization of UContainer class.
public class UContainer : IContainerAccessor {

  private static IUnityContainer _container = null;

  public static IUnityContainer Container {
   get {
    return _container;
   }
   set {
    _container = value;
   }
 }

#region IContainerAccessor Members

  IUnityContainer IContainerAccessor.Container {
    get {
     return Container;
    }
   }

#endregion

}

public interface IContainerAccessor {

  IUnityContainer Container {
    get;
  }
} 
 
 
I am using a console application to test our sample code. So in Program class, main function I am initializing UContainer class as mention below:

class Program {
 static void Main(string[] args) {
  IUnityContainer container = new UnityContainer();
  UnityConfigurationSection configSection = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
  configSection.Configure(container);
  container.AddNewExtension<EnterpriseLibraryCoreExtension>();
  UContainer.Container = container;
  ProjectBL bl = new ProjectBL();
  bl.GetProjectById(1);
  Console.ReadLine();
 }
} 
 

Unity container instance look into default config file of project for configuration information. If any error is found in configuration file like some syntax error or some of the defined types are not able to resolve an runtime exception has been thrown.
So when you run application, you get the following output.

If we change the configuration mapping to ProjectDLForSqlServer output will be
I hope this article will help.

Friday, February 24, 2012

Interface Dependecy Injection : A way of loose coupling in C#

To know more about Dependency Injection please read my previous post. Dependency injection can be implement by three possible ways. One of these Interface Injection.

As we know in C# an interface object can have reference of any of the class, implementing the same interface. This is the base behind the Interface Dependency Injection.
Interface injection allows to pass the dependency into dependent object in the form of interface, implemented by dependent class.
Or in easy words, Dependency declared inside the dependent class  in the form of Interface. So any class that implements dependency interface, can be substituted into dependent class.
Lets look an example:-

IDependent interface :- This interface defines the methods that inject one or more dependency into dependent class.


Dependent Class :- The class, that implement the IDependent interface.


IDependency interface :- This interface includes all dependency members that can be called from the Dependent class. By mean of IDependency interface, we can easily inject any of the class that implements IDependency interface.

Dependency Class :- Any class that implements IDependency interface use to substitute into dependent class using Interface injection.

Lets look into simple example:-
 
using System;
using System.Collections.Generic;
using System.Text;
namespace InterfaceInjectionSample {

 // Project entity class
 public class Project {
   public Project(string title, int id) {
   this.title = title;
   this.id = id;
 }

 public string Title {
   get {
    return title;
   }
   set {
    title = value;
   }
 }

 public string ID {
   get {
    return id;
   }
   set {
    id = value;
   }
 }

 private string title;

 private string id;

}

// Project Business Layer class
public class ProjectBL{

  IProjectDL _projectDL;

  public ProjectBL(IProjectDL projectDL){
    _projectDL=projectDL;
  }

  public Project GetProjectById(int id){
    return _projectDL.GetProjectById(id);
  }

  public List<Project> GetProjects(){
    return _projectDL.GetProjects();
  }
}

public interface IProjectDL{
  public Project GetProjectById(id);
  public List<Project> GetProjects();
}

// Project Data Layer to interact with database.
public class ProjectDL : IProjectDL{

  public Project GetProjectById(int id){
    Project project=null;
    // logic to access database and return the mapped data object to project entity.
    return project;
  }

  public List<Project> GetProjects(){
    List<Project> projects=null;
    // logic to access database and return the mapped data object to project entity.
    return projects;
  }

 }
} 
 
 
Here Project BL class depends on IProjectDL interface to perform any operations on data layer. Since IProjectDL object can reference to any class implementing IProjectDL like ProjectDL.
By using interface dependency injection we can insert the any interface dependency.
Lets we have another implementation of IProjectDL as below:

// Another implementation of Project data layer.
// Lets assume its to interact with other database like oracle.
public class ProjectDLForOracle : IProjectDL{

  public Project GetProjectById(int id){

    Project project;

    // logic to get project from oracle database.

    return project;

  }

  public List<Project> GetProjects(){

    List<Project> projects;

    // logic to get projects from oracle database.

    return projects;

  }

} 
 
 
So ProjectBL just depend on IProjectDL implementation.  We can pass either ProjectDL or ProjectDLForOracle without changing in ProjectBL class.
Many dependency injection container available to automate and configurable this. Enterprise library also provides the policy injection block. By means of this block we can map interface to its implementing class. Policy injection block will read this configuration and inject the corresponding class instance into dependent class.
In this way BL layer classes loosely coupled with DL. We can easily change the one data layer implementation with other one.
So at the end i want to conclude about the whole content.
If dependency in the form of interface its called "Interface Dependency".
Injecting the interface dependency reference by either mean is called "Interface Dependency Injection".
I hope this article will helpful for novice to understand the concept.

Dependency Injection : A pattern for loose coupling

What is Dependency Injection?

Dependency Injection means dynamically inserting code at run time. So that application behavior can be change without affecting/recompiling whole application.

How this Injection is helpful?

Most of the application have many component which are depending on other i.e.  One component needs other to complete their job, know as Dependencies.
The purpose of most of the application architecture is to reduce the coupling between component to make the application more configurable & more loosely coupled. So that changes in one component doesn't affect other component.

Lets look at an example:-
public class BankAccount {
  private ILogger _logger = new DBLogger();

  public void Deposit(decimal amount) {
    // logic to update account
    _logger.LogTransaction(
       string.Format("Amount deposited at {0}", DateTime.Now));
  }

  public void Withdraw(decimal amount) {
    // logic to update account
    _logger.LogTransaction(
       string.Format("Amount withdraw at {0}", DateTime.Now));
  }

}
 
DBLogger object is directly instantiated inside the BankAccount class so BankAccount should know in advance about the DBLogger implementation and to change another implementation of ILogger we need to change BankAccount class too.
Lets we have another implementation of ILogger for text file logging.

public class DBLogger : ILogger {

  #region ILogger Members

    public void LogTransaction(string message) {
     // Logic to log the message to database.
    }

  #endregion
}

public class TextFileLogger : ILogger {

  #region ILogger Members

    public void LogTransaction(string message) {
      // Logic to log the message to text file.
    }

  #endregion

}
 
public interface ILogger {
  void LogTransaction(string message);
}
 
To change DBLogger to TextFileLogger in BankAccount, we need to compile BankAccount class too.

Dependency Injection (DI) remove these kind of tight coupling between component by injecting the dependency at run time.So dependent class doesn't know about the dependency at design time, DI injects dependency object's instance at run time. Based on the configuration, DI will inject the ILogger implementation in BankAccount class.

Dependency injection can be possible by three ways:
  1. Interface Injection
  2. Setter Injection
  3. Constructor Injection
Microsoft Enterprise Library provides the DI framework for all .Net applications.I am referencing MS Enterprise Library 5.0 that can be download from here .In EntLib 5.0, Policy Injection Block is kept just for the compatibility with previous version. Dependency configuration using EntLib 5.0 can be possible either by Code or by .Net configuration file.

I will continue about the dependency injection type in my next articles.

Monday, February 6, 2012

SharePoint Workflow Association : Associate workflow to list or web programmatically

Hi,
It's very frequently required to attach/associate workflow to list or web programmatically. For a workflow a history list and task list is required.
History list is use to log activity/error occurred during workflow running span.
Task list is use to create and assign task for some approval etc. to user.
Workflow Association:- The binding of any workflow template to list or web is called workflow association.

Step. 1 Create a workflow history list.

public void CreateHistoryList(){

     using(SPSite site = new SPSite("Your web url")){
        using(SPWeb web = site.OpenWeb()){
           web.Lists.Add("YourHistoryListTitle","ListDescription",SPListTemplateType.WorkflowHistory);
        }
     }
}

Step. 2 Create a Workflow Task list.

public void CreateTaskList(){
using(SPSite site = new SPSite("Your web url")){
        using(SPWeb web = site.OpenWeb()){
           web.Lists.Add("YourTaskListTitle","ListDescription",SPListTemplateType.Tasks);
        }
     }
}

Step. 3 Associate workflow with web ( In case of Site Workflow)


 public void AddWorkflowAssociation(){childWeb.AllowUnsafeUpdates = true;

using(SPSite site = new SPSite("Your web url")){
using(SPWeb web = site.OpenWeb()){

//Add workflow association
SPWorkflowTemplate workflowTemplate = web.WorkflowTemplates.GetTemplateByName("YourWorkflowTemplateName", new CultureInfo(1033));
SPWorkflowAssociation association = SPWorkflowAssociation.CreateListAssociation(workflowTemplate, "Workflow Association Name",
web.Lists["TaskListTitle"], web.Lists["HistoryList"]);

//configures workflow assocition options
association.AllowManual = true;
association.AutoStartCreate = false;
association.AutoStartChange = false;
association.AllowAsyncManualStart = false;
web.WorkflowAssociations.Add(association);
web.Update();
}
     }
}

Step. 4 Associate workflow with web ( In case of List Workflow)


public void AddWorkflowAssociation(){childWeb.AllowUnsafeUpdates = true;
using(SPSite site = new SPSite("Your web url")){
        using(SPWeb web = site.OpenWeb()){
        //Add workflow association
        SPWorkflowTemplate workflowTemplate = web.WorkflowTemplates.GetTemplateByName("YourWorkflowTemplateName", new CultureInfo(1033));
        SPWorkflowAssociation association = SPWorkflowAssociation.CreateListAssociation(workflowTemplate, "Workflow Association Name",
                                web.Lists["TaskListTitle"], web.Lists["HistoryList"]);
        //configures workflow assocition options
        association.AllowManual = true;
        association.AutoStartCreate = false;
        association.AutoStartChange = false;
        association.AllowAsyncManualStart = false;
        SPList list = web.Lists.TryGetList("YourListTitle");
        list.WorkflowAssociations.Add(association);
        web.Update();
         }
     }
}

Now your workflow is associated with either list or web.