Wednesday, 20 June 2012

Feature activation depending on some logic

Some time we need to get our feature de-activated mode if it fails on some logic. For instance you have written a feature that provisions some lookup list that depends on an existent list or some timer job. The name of the existent list or timer job is supplied through properties.

The easiest way to tell SharePoint not to activate this feature is to throw SPException with your message.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
   string someListName = properties.Definition.Properties["ParentListName"].Value;
   if (string.IsNullOrEmpty(someListName))
     throw new SPException("Please supply value of 'ParentListName' property.");          
   SPSite site = (SPSite)properties.Feature.Parent;
   SPList someList = site.RootWeb.Lists[someListName];

   if (someList == null)
     throw new SPException(string.Format("List:'{0}' does not exist. Please create it first before activating this feature.", someListName));

   //do your stuff

That's it.

Monday, 18 June 2012

Starting workflow programmatically

If you have an instance of SPListItem, and know the workflow association name, you can start it. First you need to find workflow assocation instance and tell SPSite.SPWorkflowManager to start your workflow.

Lets say I have a helper method that takes SPListItem and workfow association name.

private SPWorkflowAssociation GetWorkflowAssociationByName(SPListItem item, string workflowAssociationName)
    return item.ContentType.WorkflowAssociations.GetAssociationByName(workflowAssociationName, new System.Globalization.CultureInfo("en-US"));


public void StartWorkflow(SPListItem item, string associationName)

//get workflow association object
workflowAssociation = GetWorkflowAssociationByName(item, associationName);                

if (workflowAssociation == null)
  throw new Exception(string.Format  ("Workflow association '{0}' could not be found in the list '{1}'", workflowAssociationName, item.ParentList.Title));

//start your workflow...
item.Web.Site.WorkflowManager.StartWorkflow(item, workflowAssociation, workflowAssociation.AssociationData);

   catch (SPException spEx)
   { //log your exception }

//that kicks off a associated workflow.
StartWorkflow(anInstanceOfSPListItem, "Masood - Approval workflow")

Below is the picture where higlighted box is the association name.


That's it. Happy coding.