I have an InfoPath form with a button "Cancel". This button cancels the workflow is running. I created an EventReceiver and I'm able to change "Approval 2010" column to Cancel but I cannot change the "Approval Status" column to "Reject", still in "Draft".
My code:
private void ItemCanceled(SPItemEventProperties properties)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite elevSite = new SPSite(properties.SiteId))
using (SPWeb elevWeb = elevSite.OpenWeb(properties.RelativeWebUrl))
{
using (DisabledEventsScope scope = new DisabledEventsScope())
{
SPList elevList = elevWeb.Lists[properties.ListId];
SPListItem elevListItem = elevList.GetItemById(properties.ListItemId);
SPWorkflowManager workflowManager = elevSite.WorkflowManager;
SPWorkflowAssociationCollection workflowAssociations = properties.List.WorkflowAssociations;
SPWorkflowAssociation workflowAssocation2010 = workflowAssociations.GetAssociationByBaseID(AdministrativeFormsUtility.ApprovalTemplateId2010);
var itemWorkflowsCompleted = elevListItem.Workflows
.Cast<SPWorkflow>()
.Where(w => w.AssociationId == workflowAssocation2010.Id).ToList();
if (itemWorkflowsCompleted.Any())
{
Logger.Info(Title, string.Format("Verifying if a workflow is running on item '{0}'...", elevListItem.File.Name), Category);
foreach (SPWorkflow mySPWorkflow in itemWorkflowsCompleted)
{
foreach (SPWorkflowTask taskWorkflow in itemWorkflowsCompleted[0].Tasks)
{
//cycle throught all tasks associated to the workflow
bool result = false;
Hashtable ht = new Hashtable();
ht["PercentComplete"] = 1.0f;
ht["Status"] = "Completed";
ht["TaskStatus"] = "Rejected";
ht["ows_FieldName_Comments"] = "Rejected";
result = SPWorkflowTask.AlterTask(taskWorkflow, ht, true);
Logger.Info(Title, string.Format("Removed workflow instance '{0}'", mySPWorkflow.InstanceId), Category);
}
SPWorkflowManager.CancelWorkflow(mySPWorkflow);
Logger.Info(Title, string.Format("Canceled workflow instance '{0}'", mySPWorkflow.InstanceId), Category);
SendEmailCanceled(properties);
properties.ListItem["Approval Status"] = "1";
properties.ListItem.SystemUpdate();
}
}
else
{
Logger.Info(Title, string.Format("No running workflow instances detected."), Category);
}
}
}
});
}