Showing posts with label Workflow Sharepoint. Show all posts
Showing posts with label Workflow Sharepoint. Show all posts

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;

}

}

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.

Wednesday, August 31, 2011

Programmatically pass parameters to workflow

Hi All,
I worked on SharePoint workflow and explore many things.
Here I am going to share about SharePoint parameters i.e. 'Association Data' and 'Initiation Data'.
Association Data: - Association data is declared when administrator creating an association on site/list. This data is helpful to provide some default value, some constraints values or some other information.
Initiation Data: - When a user starts a workflow, some information input is required from the user. These inputs may override the association data default values or some additional input. These inputs are specific to current workflow instance and not available to other instances.
When workflow starts using SharePoint UI, workflow's forms are prompted (if any input is required). But sometimes we need to pass this information programmatically.  In this blog I am going to share my knowledge about "Pass parameters to workflow programmatically".
Workflow persist the data in the form of xml, but to use xml in code is difficult, so i am using classes to manage data in the code and further I convert the class object into xml by serialization.
1) Create a public class with at least default parameter less constructor.
2) Mark the class as serializable at the top of the class by [Serializable] attribute. This attribute allow class to be serialize.
3) Add public properties, each correspond to required input parameters.
4) Add two static methods for serialization and deserialization.
4) By xml serialization convert the class into xml.
5) Assign the xml to workflow data.
A sample class MyWFInitiationData with two properties 'Amount' and 'ApplicantEmail'
public class MyWFInitiationData {
      public MyWFInitiationData(){
      }
      public string ApplicantEmail{
      get; set;
      }
      public int Amount{
       get;   set;
      }
// As required can add more properties corresponding to the input from the user. MyWFInitiationData
static stringInitiationDataToXml(MyWFInitiationData param) {
    string data = string.Empty;
    MyWFInitiationData objParams = param;
    MemoryStream stream = new MemoryStream();
    XmlSerializer serial = newXmlSerializer(typeof(MyWFInitiationData));
    serial.Serialize(stream, objParams);
    Byte[] bytes = new Byte[stream.Length];
    bytes = stream.GetBuffer();
    data =Encoding.UTF8.GetString(bytes);
    return data;
}
// Deserialize the initiation data from xml to MyWFInitiationData object.
static MyWFInitiationData InitiationDataFromXml(string initiationXML) {
    if (initiationXML.Length > 0) {
    XmlSerializer serializer = new XmlSerializer(typeof(MyWFInitiationData));
    XmlTextReader textReader = new XmlTextReader(new System.IO.StringReader(initiationXML));
    MyWFInitiationData reminderInitData = new MyWFInitiationData();
    object obj = serializer.Deserialize(textReader);
  
    if(obj != null)
      reminderInitData = (MyWFInitiationData) obj;
  
     return reminderInitData;
    }
    else{
     return null;
    }
  }
}
===============Start a workflow programmatically============
MyWFInitiationData data = new MyWFInitiationData();
string initiationDataXML = MyWFInitiationData.InitiationDataToXml(data);
SPWorkflowAssociation workflowAssosiation  = web.GetAssociationByName("Your workflow name", [System.Globalization.CultureInfo]::CurrentCulture);
SPWeb web =SPContext.Current.Web;
//if your workflow is associated with any listitem, you should pass the listitem reference instead of 'web.Site.RootWeb'.
web.Site.WorkflowManager.StartWorkflow(web.Site.RootWeb, workflowAssosiation, initiationDataXML,
                                    SPWorkflowRunOptions.Synchronous);
 ==========Get Data inside the workflow=================
You de-serialize the data from xml to MyWFInitiationData class object at workflow activated event as mention below
MyWFInitiationData _initData = MyWFInitiationData.InitiationDataFromXml(workflowProperties.InitiationData);
Now using _initData.Amount & _initData.ApplicantEmail we can get the values inside the workflow.