Wednesday, November 11, 2009

Event Receivers: How to add event receivers to a sharepoint list

Scenario: How to add custom event receivers to a specific sharepoint list using SharePoint Object Model

Approach:

SPList list = web.Lists["MyList"];

string assemblyName = "CustomSharePointEventReceivers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d517db3ed1131947";

string className = "CustomSharePointEventReceivers.MyEventReceivers";
list.EventReceivers.Add(SPEventReceiverType.ItemAdding, assemblyName, className);
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, className);
list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, assemblyName, className);



Note: In general, custom event receivers to a specific list will be added through Sharepoint features by defining a feature event receivers by extending SPFeatureReceiver. In the SPFeatureReceiver, override all the 4 methods i.e, FeatureInstalled,FeatureActivated, FeatureDeactivating and FeatureUninstalling. In these overriden methods, write above code piece.

Event Receivers: Delete all event receivers associated to a list

scenario: How to delete all the event receivers associated to a list?

Approach:


List eventreceivers = new List();

foreach (SPEventReceiverDefinition EventReceiver in list.EventReceivers)
{
eventreceivers.Add(EventReceiver);
}

foreach (SPEventReceiverDefinition er in eventreceivers)
{
er.Delete();
}


Note: We can not have only 2nd foreach loop alone. The current list of event receivers associated to a list gets updated everytime a delete operation is performed. So, an exception will be raised if you use only delete operation.

Change Workflow Task Status from any SharePoint custom component

Scenario: I have a custom workflow running. I want to change status a task from another sharepoint custom component like webpart or so.

Approach:
If we update the workflow task directly by changing the status field value to Completed or to any other status, then usually workflow raises an exception "This task is currently locked by a running workflow and cannot be edited." To get rid of this error, you can use following routine:


private void CompleteTask(string taskTitle)
{
try
{
Hashtable taskHash = new Hashtable();
taskHash[SPBuiltInFieldId.TaskStatus] = "Completed";

string currentuser = SPContext.Current.Web.CurrentUser.Name.ToLower();
Guid siteID = SPContext.Current.Site.ID;
Guid webID = SPContext.Current.Web.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteID))
{
using (SPWeb web = site.OpenWeb(webID))
{
web.AllowUnsafeUpdates = true;
SPList wfTasksList = web.Lists["WorkflowTasks"];
SPQuery queryWFTasks = new SPQuery();
queryWFTasks.Query = <<>>;
queryWFTasks.ViewAttributes = "Scope=\"RecursiveAll\"";

SPListItemCollection wfTaskItems = wfTasksList.GetItems(queryWFTasks);

if (wfTaskItems.Count != 0)
{
foreach (SPListItem item in wfTaskItems)
{
if (item.Title.ToLower().Equals(taskTitle.ToLower()))
{
SPWorkflowTask.AlterTask(item, taskHash, true);
break;
}
}
}

web.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
// Log the exception here
}
}

SharePoint Workflow : Get From Email Address Configured in Central Admin

Scenario: I want to send email from workflow SendEmail activity. How to get From email address configured in central administration for my sharepoint application.

Note: For every sharepoint application, we can configure out-going email address information in central admin. This can be done in following steps:
a. Go to central admin site -> Application Management
b. Under "SharePoint Web Application Management" section, check for the link "Web application outgoing e-mail settings" and click on it.
c. Select the Web Application for which you want to set the out going email informatino.
d. Fill the following fields:
  • Outbound SMTP server:

  • From address:

  • Reply-to address:

  • Character set:

Approach:
In the SendEmail activity execute code, you write following instruction to get email set in above "From address:" field:

workflowProperties.Site.WebApplication.OutboundMailSenderAddress

How to get SharePoint user information from Person or Group field in SharePoint List

Scenario: I have a SharePoint list with various fields. One of them is Person field, in which I am storing the value selected through People Picker. How to get the Person value from this field through SharePoint Object Model.

Approach:


// Step1: Get SharePoint Item object
SPListItem Item = SPContext.Current.Web.Lists["MyList"].Item[0];

// Step2: Get user field object by passing field display name
SPFieldUser userField = (SPFieldUser)Item.Fields.GetField("Created By");

// Step3: Get user field value object
// SPBuiltInFieldId.Author refers to Created By field's internal name
SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(Item[SPBuiltInFieldId.Author].ToString());

// Step4: Get user object
SPUser userVendor = fieldValue.User;

Never use Thread.Sleep in SharePoint Workflows

From last 2 months, i was very busy in developing custom workflows. So, I didn't get chance to blog my experience during all these days. I really got great experience by working on a custom workflow. I am trying to put my experience in various posts including this post.

Coming to the main point, never ever use Thread.Sleep in SharePoint workflows

Reason: If we deploy the custom workflow with Thread.Sleep instructions, then IISReset will keep these instructions out of memory and the workflow will struck there.
Alternative: Use appropriate inbuilt or custom workflow activities.