Just another WordPress.com site

Posts tagged ‘Sharepoint’

How to store custom class object 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;

}

}

 

Advertisements

How to programmatically start sharepoint workflow

SharePoint workflow is great way to automate the business process.  SharePoint workflow can be configured to start automatic or manually. But sometimes our requirement lies in between two default options i.e. we want to start workflow automatically if and only if certain condition met e.g.  workflow initiation depends on certain business logic or depends on some field value entered by user.  If condition met we need to start workflow otherwise not. In this scenario, SharePoint default options ( Automatic OR Manual) to start workflow do not work and developer requires to start workflow at run time using code.

To start a workflow at run-time  we need two important values: –

  1. Workflow Association Reference Id OR Workflow association name: – Workflow association id that we want to start. OR workflow association name can also use to identify it.
  2. Workflow Initiation Data: – Its optional but most of the workflow requires some initiation data. Initiation data that requires by workflow to take decision. To know more about the initiation data and how to pass it, please refer http://wp.me/p1nAw1-m

To start any workflow, we requires following objects: –

  1. WorkflowManager: – With each SPSite object a SPWorkflowManager object is associated , enabling you to centrally control the workflow templates and instances across the site collection.  We can get WorkflowManager instace by SPSite instace.
    E.g.

     WorkflowManager = SPContext.Current.Web.Site.WorkflowManager;
    
  2.  SPWorkflowAssociation: – Workflow association is a binding between list/library and workflow template.  When a workflow is added to SharePoint list/library an workflow association is crated. We can get the workflow association by list/library where workflow is associated.
  3. E.g.
      SPWorkflowAssociationCollection associationColl = ParentList.WorkflowAssociations;
      foreach (SPWorkflowAssociation association in associationCollection) {
        // We can find the association by BaseId or by workflow association name.
        // if (String.Compare(objWorkflowAssociation.BaseId.ToString("B"), {"Workflow_GUID"}, true) == 0)
       // you can identify the workflow association by association name, entered during association creation.
      if (association.Name == wfName)        {
        association.AutoStartChange = true;
        association.AutoStartCreate = false;
        // We can change the
        association.AssociationData = string.Empty;
        // We can use other overload StartWorkflow methods.
       spSite.WorkflowManager.StartWorkflow(listItem, association,  association.AssociationData);
      }
    }
    

So complete code to start workflow at runtime is

public void StartWorkflow(SPListItem listItem, SPSite spSite, string wfName)  {
    SPList parentList = listItem.ParentList;
    SPWorkflowAssociationCollection associationCollection = parentList.WorkflowAssociations;
    foreach (SPWorkflowAssociation association in associationCollection)  {
      if (association.Name == wfName){
       association.AutoStartChange = true;
       association.AutoStartCreate = false;
       association.AssociationData = string.Empty;
       spSite.WorkflowManager.StartWorkflow(listItem, association,  association.AssociationData);
       }
     }
}
Aside

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.

SharePoint Workflow : Pass Association & Initiation parameters to SharePoint workflow programmatically

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.

Gallery

SharePoint Security Terms : Permission, Permission Levels Role Assignment etc….

As I worked on SharePoint security I always confused about the SharePoint security terms used in SharePoint class library. Here I am trying to blog SharePoint Security related terms like Permissions, Permissions Level, RoleDefination, Security Groups and Role Assignments which helps to explain the SharePoint classes.

  1. Permissions: – SharePoint Foundation doesn’t allow defining custom permission. SharePoint provides 35 predefined permission to create different permission levels. By grouping these permission together in different sets, can create different permission levels.
    You can get the more details of predefined permission at MSDN
  2. Permission Levels: – Permission Level is nothing but a set of different permissions. We can’t directly assign permissions to group/user, instead need to create permission level and it can be assign. By default SharePoint provides 5 permission levels. These are “Full Control”, “Design”, “Contributor”, “Read” & “Limited Access”. You can get more detail of default permission levels at MSDN.
  3. SharePoint Security Groups: – SharePoint allows adding active directory groups as well as admin can create SharePoint groups at site collection level. Each SharePoint group contains one or more user.
  4. RoleDefination: – Each SharePoint group/user should have one or more permission levels assign to it. Permission levels with SPGroup/User calls RoleDefination. In simple words when we assign permission levels to group/user, it defines a role for the corresponding group/user.
  5. RoleAssignment:- When an SharePoint group/user is added to SharePoint web, this process is called RoleAssignment. Adding a role assignment to web is the final stage of assigning a permission to group/user.
  6. Permission Inheritance:- As word ‘Inheritance’ say most of the thing about it. By default, SharePoint objects like Site Collection, Web, List & List Item are inherit permission from his parent object. It means user have all the permission on an SharePoint object that user have on parent object. If we want to child object have different permission then parent, we need to explicitly break the inheritance.