Friday, May 27, 2011

Email the Approval Status to "Created By"/"Modified By" user from Visual Studio workflow

Below is the code snippet to send an email about the approval status to the user who submitted/created the list item in a SharePoint list. Assume that the Visual studio workflow is attached to the list and will trigger the workflow when the item is edited in the list.


  if (workflowProperties.Item.ModerationInformation.Status == SPModerationStatusType.Denied)
  {
        StringDictionary headers = new StringDictionary();
        headers.Add("from", "administrator@domain.com");
        headers.Add("subject", "Request - Denied");
        headers.Add("content-type", "text/html");
        System.Text.StringBuilder strMessage = new System.Text.StringBuilder();

       //link to list item display form (view item)
       strMessage.Append("The request submitted in ABC site has been rejected."+ workflowProperties.WebUrl+ "/" + workflowProperties.List.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url + "?ID=" + workflowProperties.ItemId);
        strMessage.Append("<br><br> Approver's comments: "+ workflowProperties.Item.ModerationInformation.Comment);

        SPListItem item = workflowProperties.Item;
        SPUser spUser = GetSPUser(item, "Created By");
        if (!String.IsNullOrEmpty(spUser.Email))
        {
                 headers.Add("to", spUser.Email);
                 SPUtility.SendEmail(web, headers, strMessage.ToString());
        }
  }

//Function to get the user instance who submitted the item
  private SPUser GetSPUser(SPListItem item, string fieldName)
        {
            SPFieldUser field = item.Fields[fieldName] as SPFieldUser;
            if (field != null && item[fieldName] != null)
            {
                SPFieldUserValue fieldValue = field.GetFieldValue(item[fieldName].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    return fieldValue.User;
                }
            }
            return null;
        }

2 comments:

  1. Is there a way to do with this with the SharePoint 2013 Visual Studio declarative workflows? There is a SetModerationStatus activity in SharePoint 2013 workflow but no GetModerationStatus.

    ReplyDelete
  2. You can get the moderation status of an item using listItem.ModerationInformation property.

    ReplyDelete