Patrick's SharePoint Blog

SharePoint's Booming world

Posts Tagged ‘Workflow Activities’

Workflow activity: Set Managed Metadata column

Posted by Patrick Boom on July 23, 2013

Sometimes you wonder why certain things are not possible or why Microsoft did not included that in their shipping of the product. On the other hand, it makes sure we also have a job to do ūüėČ
One of those things is the fact that the out-of-the-box version of SharePoint 2010 seems to miss certain workflow actions that seem logical. This blog post covers one of those, the in-ability to set a Managed Metadata column.

In my current project, we encountered this behaviour when trying to create workflows that modify mms columns. Out of the box, the only way available is to use either the Update List Item or Set Field actions.
In both cases however, you need to provide the exact string for the MMS value, in the form of <id>;<value>, i.e. 34;My Value. Not ideal as this could be different here and there and could change in the future. More importantly though, it does not work in all cases. It seems to work fine when no value was set for the column yet, but as soon as it is, you are not able to modify it from the workflow.

So I decided to develop a small custom action to overcome this problem and enable us to update MMS columns, whatever their current value is. In this post, I will not go over the entire setup of developing a custom action. Please review my other post on email activities for more info on that. Instead, I will only cover the code needed specifically for this action.

Actions file

     <Action Name=Set Managed Metadata Column
             ClassName=$SharePoint.Project.FileNameWithoutExtension$.SetMMSColumn

Assembly=$SharePoint.Project.AssemblyFullName$

AppliesTo=all

Category=List Actions>
      <RuleDesigner Sentence=Update %1 with %2 from %3 and %4>
        <FieldBind Field=ColumnName Text=this column DesignerType=TextArea Id=1/>
        <FieldBind Field=TermName Text=this term DesignerType=TextArea Id=2/>
        <FieldBind Field=TermSetName Text=this termset DesignerType=TextArea Id=3/>
        <FieldBind Field=GroupName Text=this group DesignerType=TextArea Id=4/>
      </RuleDesigner>
      <Parameters>
        <Parameter Name=__Context Type=Microsoft.SharePoint.WorkflowActions.WorkflowContext Direction=In />
        <Parameter Name=__ListId Type=System.String, mscorlib Direction=In />
        <Parameter Name=__ListItem Type=System.Int32, mscorlib Direction=In />
        <Parameter Name=__ActivationProperties Type=Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties, Microsoft.SharePoint Direction=Out />
        <Paramater Name=ColumnName Type=System.String, mscorlib Direction=In/>
        <Paramater Name=TermName Type=System.String, mscorlib Direction=In/>
        <Paramater Name=TermSetName Type=System.String, mscorlib Direction=In/>
        <Paramater Name=GroupName Type=System.String, mscorlib Direction=In/>
      </Parameters>
    </Action>

As you can see above, the action defines an action with 4 parameters, the name of the MMS column, the name of the term, the name of the termset and finally the name of the group. The other 4 parameters are default parameters that allow you to get the context of the workflow.

Now let us move on to the code of the action.

       #region [ Custom Workflow Properties ]

¬†¬†¬†¬†¬†¬†¬† public static DependencyProperty ColumnNameProperty = DependencyProperty.Register(“ColumnName”, typeof(string), typeof(SetMMSColumn));
        [ValidationOption(ValidationOption.Required)]
        public string ColumnName
        {
            get
            {
                return ((string)(base.GetValue(ColumnNameProperty)));
            }
            set
            {
                base.SetValue(ColumnNameProperty, value);
            }
        }

public static DependencyProperty TermNameProperty = DependencyProperty.Register(“TermName”, typeof(string), typeof(SetMMSColumn));
       [ValidationOption(ValidationOption.Required)]
       public string TermName
        {
           get
            {
                return ((string)(base.GetValue(TermNameProperty)));
            }
            set
            {
                base.SetValue(TermNameProperty, value);
            }
        }

public static DependencyProperty TermSetNameProperty = DependencyProperty.Register(“TermSetName”, typeof(string), typeof(SetMMSColumn));
       [ValidationOption(ValidationOption.Required)]
       public string TermSetName
        {
            get
            {
                return ((string)(base.GetValue(TermSetNameProperty)));
            }
            set
            {
                base.SetValue(TermSetNameProperty, value);
            }
        }

¬†¬†¬†¬†¬†¬†¬† public static DependencyProperty GroupNameProperty = DependencyProperty.Register(“GroupName”, typeof(string), typeof(SetMMSColumn));
        [ValidationOption(ValidationOption.Required)]
        public string GroupName
        {
            get
            {
                return ((string)(base.GetValue(GroupNameProperty)));
            }
            set
            {
                base.SetValue(GroupNameProperty, value);
            }
        }

#endregion
[ Custom Workflow Properties ]

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            using (var web = __Context.Web)
            {
                   try
                   {
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† Common.AddCommentWorkflowHistory(“Start trying to set MMS column”, executionContext, WorkflowInstanceId);
                    // get column to update
                    SPList list = web.Lists.GetList(new Guid(__ListId), true);
                   SPListItem item = list.GetItemById(__ListItem);
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† Common.AddCommentWorkflowHistory(“Obtained list and item references”, executionContext, WorkflowInstanceId);
                   // get MMS column
                   TaxonomyField field = (TaxonomyField)list.Fields[ColumnName];
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†Common.AddCommentWorkflowHistory(“Obtained list, item and column references”, executionContext, WorkflowInstanceId);
                   //Get the Guid for the Term Store
                   Guid termStoreID = field.SspId;
                   TaxonomySession session = new TaxonomySession(web.Site);
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† Common.AddCommentWorkflowHistory(“Taxonomy session created”, executionContext, WorkflowInstanceId);
                   // Get group, termset and term
                   TermStore store = session.TermStores[termStoreID];
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†Common.AddCommentWorkflowHistory(“TermStore reference created”, executionContext, WorkflowInstanceId);
                   // Get Group, Set abd Term
                   Group group = store.Groups[GroupName];
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† Common.AddCommentWorkflowHistory(“Found group”, executionContext, WorkflowInstanceId);
                   TermSet set = group.TermSets[TermSetName];
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† Common.AddCommentWorkflowHistory(“Found TermSet”, executionContext, WorkflowInstanceId);
                   Term term = set.Terms[TermName];
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† Common.AddCommentWorkflowHistory(“Found Term”, executionContext, WorkflowInstanceId);
                   // Set value
                   field.SetFieldValue(item, term);
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† Common.AddCommentWorkflowHistory(“Updated column”, executionContext, WorkflowInstanceId);
                   item.Update();
                }
               catch (Exception ex)
                {
                   // Log entry to Workflow History Log
¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† Common.WriteFailToHistoryLog(web, WorkflowInstanceId, string.Format(CultureInfo.InvariantCulture, “Failed to set MMS column. Error message: {0}”, ex.Message));
                   throw;
               }
               finally
               {
                   // Cleanup РDispose of these private properties before exiting
                  if (__ActivationProperties != null)
                  {
                       __ActivationProperties.Dispose();
                  }
                  if (__Context != null)
                  {
                      __Context.Dispose();
                  }
                }
            }
           return ActivityExecutionStatus.Closed;
       }

Now the real meat to the bone is in the ActivityExecutionStatus method that will be called by our workflow on start. We will first obtain references to the list and current item before proceeding. Once done, we get the MMS column from the item and cast it to a TaxonomyField. We can then obtain the configured TermStore for that column through the field reference.

We then setup a TaxonomySession and obtain a reference to the TermStore. From that point on, easy to get the Group, TermSet and Term required for the update. We finally update the item using the SetFieldValue method from the TaxonomyField.

This simple action can be extended by allowing parameters from the start of the action to allow the end-user to enter the appropriate term, set and group on start of the workflow. That is however beyond the scope of this blog.

Couple of things you should be aware of.

  1. When no TermStores are returned by the session object, please ensure that your MMS service proxy is added to the default proxy group using the following PowerShell command:

    Set-SPMetadataServiceApplicationProxy¬†-Identity¬†“<your MMS name>”¬†‚ÄďDefaultProxyGroup

  2. If your activity does not show up in SharePoint designer, please check if you created the appropriate language folder in your project for the ACTIONS file. Misplacing this file will cause the activity not to show up.
  3. The session object is not very consistent. I found it more reliable to use the term store ID from the taxonomy field to request the TermStore from the session object.
  4. When deployed, run the workflow a couple of times. It takes a while for the connections to be setup and running the workflow directly after deployment might cause an exception in finding the TermStore.
  5. I suspect the reason why we cannot update a MMS column from a workflow using the OOB actions is because the link to the TermStore fails in doing the update. I have not reveived the OOB code using Reflector or something, but it could explain why it is not posisble.


Hope this fills a gap in your requirements!

Update: I have updated the code of the email activity to include this activity too. Download the sample solution here!

Posted in SharePoint 2010 | Tagged: , , , | 6 Comments »

Custom Email activity for SharePoint Designer 2010

Posted by Patrick Boom on August 9, 2011

You have probably run into it if you created SharePoint 2010 workflows using SharePoint Designer. The cool part of SharePoint 2010 is that it actually allows you to modify or copy the out-of-the-box workflows. The not so cool part is that the activities in SharePoint Designer are quite limited in their functionality.

For example, in the email activity that comes out of the box it is not possible to add attachments, nor does it allow you specify the From field.

Fortunately, using Visual Studio, we can upgrade the toolbox for SharePoint Designer activities to add more specialized activities that can then be used in the designer workflows.

Sure, it is possible to just create the workflow in Visual Studio, but to me, the hassle of creating a complete Visual Studio workflow, just because you want to change the From field does not make sense. It is not cost effective. SharePoint Designer workflows are powerful and should be part of the evaluation for any workflow solution. It has its limits, but also a lot of strengths.

In this post, I will show how to create a custom workflow activity for this purpose. To keep things simple, if possible using this subject, I will only allow for a single attachment. I will leave it up to you to update the activity with multiple attachments if you want to. Before I begin though, if you would like to just buy a lot of additional custom activities for SharePoint 2010, please take a look at the offerings from Nintex.

To build this feature, we will follow the following steps:

  1. Set up a standard SharePoint solution in Visual Studio 2010
  2. Define our ACTIONS file, which tell SharePoint and SharePoint Designer which activities I would like to include
  3. Define our SendMail class, which will implement the actions specified in the ACTIONS file
  4. Register our new custom action in the web.config using an eventreceiver (I will post a cool feature to do this easily in a later post)
  5. Package, deploy and test

Set up the solution structure

First, create a new Visual Studio solution using the SharePoint empty project template . Ensure that you have a key, so the resulting assembly is signed and deployable to the GAC. Then add a SharePoint Mapped folder, pointing to the following location:

Template\<yourlanguageLCID>\Workflow

Once done, add a file in this folder with the extension ACTIONS. You can call the file any way you want, but I used BoomCustomActivities.ACTIONS. Your solution should look like this now:


Define the ACTIONS file for our activity

We will now define which actions we will add to the toolbox. These will become available in the Actions tab on the Ribbon in SharePoint Designer. Populate the ACTIONS file with the following XML definition:

<?xml version=1.0encoding=utf-8?>
  <WorkflowInfo Language=en-us>
    <Actions Sequential=thenParallel=and>
<Action
Name=Send email with attachment
ClassName=$SharePoint.Project.FileNameWithoutExtension$.SendEmailActivity
Assembly=$SharePoint.Project.AssemblyFullName$
AppliesTo=all
Category=Email actions>
<RuleDesigner
Sentence=Send email with attachment %1 to %2. Use %3 as the sender>
<FieldBind Field=AttachmentFileNameText=this file (url)DesignerType=TextAreaId=1/>
<FieldBind Field=To,CC,Subject,BodyText=these user(s)DesignerType=EmailId=2/>
<FieldBind Field=FromText=this userDesignerType=TextAreaId=3/>
</RuleDesigner>
<Parameters>
<Parameter Name=__ContextType=Microsoft.SharePoint.WorkflowActions.WorkflowContextDirection=In/>
<Parameter Name=__ListIdType=System.String, mscorlibDirection=In/>
<Parameter Name=__ListItemType=System.Int32, mscorlibDirection=In/>
<Parameter Name=__ActivationPropertiesType=Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties, Microsoft.SharePointDirection=Out/>
<Parameter Name=AttachmentFileNameType=System.String, mscorlibDirection=In/>
<Parameter Name=ToType=System.Collections.ArrayList, mscorlibDirection=In/>
<Parameter Name=CCType=System.Collections.ArrayList, mscorlibDirection=Optional/>
<Parameter Name=SubjectType=System.String, mscorlibDirection=In/>
<Parameter Name=Body” Type=System.String, mscorlibDirection=Optional/>
<Parameter Name=FromType=System.String, mscorlibDirection=In/>
</Parameters>
</Action>
</Actions>
</WorkflowInfo>

Let’s discuss the contents. The WorkflowInfo node just indications this definition applies to Workflows. The Actions node defines how the text is build up in the workflow designer. For example, if used in a sequential action, the action will read <actiondescription> then. Nothing really interesting there. The real magic starts with the Action node. In there, the attributes Name, ClassName, Assembly, AppliesTo and Category define the name of the action in the actions menu, the class and assembly for the code, if it relates to list items, documents only or all, and the Category in which it is listed in the actions menu.

The RuleDesigner node specifies the text shown in the editor and related input parameters. The attribute Sentence specifies the sentence shown in the designer. You specify each parameter by a % followed by a number. %1 will point to the first parameter and so on. The parameters are specified using FieldBind attributes. The Text attribute substitutes the ‘%’ parameter indicator in the sentence in the designer. The Id attribute should match the order of the parameter.

The Parameters node and subsections define the parameters that will be passed into your custom activity class. Parameters obtained from the FieldBinding should exactly match the parameter names in the parameters section for them to be transferred to your code. You also specify whether your parameter is in or out and the type of the property, which is a .NET type. For more information on Workflow Action files, see MSDN.

So now we have our ACTIONS definition file. Let’s move on to the code itself.

Create the class for our activity

Add a new class to your project. Call the class SendEmailActivity as stated in the ACTIONS file. Have the class inherit from the System.Workflow.ComponentModel.Activity class. That is the easy part. Now for each of the parameters we stated in the ACTIONS file, we need to create properties and ensure that they map. First do the Workflow Context properties. They use a DepencyProperty to map the property in the class to the parameter stated in the ACTIONS file. See below code snippet.

#region [ Workflow Context Properties ]

public static DependencyProperty __ContextProperty = DependencyProperty.Register(“__Context”, typeof(WorkflowContext), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Required)]
public WorkflowContext __Context
{
get
{
return
((WorkflowContext)(base.GetValue(__ContextProperty)));
}
set
{
    base.SetValue(__ContextProperty, value);
}
}

public
static DependencyProperty __ListIdProperty = DependencyProperty.Register(“__ListId”, typeof(string), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Required)]
public string __ListId
{
  get
{
      return ((string)(base.GetValue(__ListIdProperty)));
}

set
{
      base.SetValue(__ListIdProperty, value);
}
}

public static DependencyProperty __ListItemProperty = DependencyProperty.Register(“__ListItem”, typeof(int), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Required)]
public int __ListItem
{
  get
  {
    return ((int)(base.GetValue(__ListItemProperty)));
}

set
{
base.SetValue(__ListItemProperty, value);
}
}

public
static DependencyProperty __ActivationPropertiesProperty = DependencyProperty.Register(“__ActivationProperties”, typeof(SPWorkflowActivationProperties), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Required)]
public SPWorkflowActivationProperties __ActivationProperties
{
  get
{
return (SPWorkflowActivationProperties)base.GetValue(__ActivationPropertiesProperty);
}

set
{
base.SetValue(__ActivationPropertiesProperty, value);
}
}

#endregion
[ Workflow Context Properties ]

What is important here is that the name of the DependencyProperty is equal to the name of the property in the class, appended with Property. Also, the name of the property should be equal to the name of the parameter in the ACTIONS file. Now that we have these properties, we also map the rest of the properties that are more relevant to our solution.

#region [ Custom Workflow Properties ]

public static DependencyProperty ToProperty = DependencyProperty.Register(“To”, typeof(ArrayList), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Required)]
public ArrayList To
{
  get
{
return ((ArrayList)(base.GetValue(SendEmailActivity.ToProperty)));
}

set
{
base.SetValue(SendEmailActivity.ToProperty, value);
}
}

public
static DependencyProperty CCProperty = DependencyProperty.Register(“CC”, typeof(ArrayList), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Optional)]
public ArrayList CC
{
  get
  {
return ((ArrayList)(base.GetValue(SendEmailActivity.CCProperty)));
}

set
{
base.SetValue(SendEmailActivity.CCProperty, value);
}
}

public
static DependencyProperty SubjectProperty = DependencyProperty.Register(“Subject”, typeof(string), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Required)]
public string Subject
{
  get
{
return ((string)(base.GetValue(SendEmailActivity.SubjectProperty)));
  }

set
  {
    base.SetValue(SendEmailActivity.SubjectProperty, value);
  }
}

public
static DependencyProperty BodyProperty = DependencyProperty.Register(“Body”, typeof(string), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Optional)]

public
string Body
{
  get
  {
return ((string)(base.GetValue(SendEmailActivity.BodyProperty)));
  }

set

  {
base.SetValue(SendEmailActivity.BodyProperty, value);
  }
}

public static DependencyProperty AttachmentFileNameProperty = DependencyProperty.Register(“AttachmentFileName”, typeof(string), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Required)]
public string AttachmentFileName
{
  get
  {
    return ((string)(base.GetValue(AttachmentFileNameProperty)));
  }

set
  {
base.SetValue(AttachmentFileNameProperty, value);
  }
}

public static DependencyProperty FromProperty = DependencyProperty.Register(“From”, typeof(string), typeof(SendEmailActivity));
[ValidationOption(ValidationOption.Required)]
public string From
{
  get
{
return ((string)(base.GetValue(SendEmailActivity.FromProperty)));
  }

set
  {
base.SetValue(SendEmailActivity.FromProperty, value);
}
}

#endregion [ Custom Workflow Properties ]

So basically it is more of the same. It connects the parameters from the Action file to our code behind class. So now that we have our properties and our class is fed with the parameters entered by the workflow designer in SharePoint Designer, we can further construct our class to do something useful. The base class System.Workflow.ComponentModel.Activity contains a method called Execute, which is the entry point for our custom activity. To implement, override the method in your custom activity. See the implementation of the method below:

protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
  using (var web = __Context.Web)
{
  try
{
       // Get all of the information we currently have about 
       // the item that this workflow is running on
var message = BuildMailMessage(web);
// get the attachment if specified
SPFile attachment = null;

try
{
using (SPSite site = new SPSite(AttachmentFileName))
{
using (SPWeb fileWeb = site.OpenWeb())
{
attachment = fileWeb.GetFile(AttachmentFileName);
string name = attachment.Name;
Stream ms = attachment.OpenBinaryStream();
message.Attachments.Add(new Attachment(ms, name));
}
}
}
catch (Exception ex)
      {
// log could not find file
Common.WriteFailToHistoryLog(web, WorkflowInstanceId, string.Format(CultureInfo.InvariantCulture, “Unable to add attachment. Could not find or load file ‘{0}’.”, AttachmentFileName));
}

      if (!string.IsNullOrEmpty(From))
{
message.From = GetMailAddress(__Context.Web, From);
}

if (message.To.Count > 0)
      {
        // Send email w/ attachments
SmtpClient smtpClient = LoadSmtpInformation();
smtpClient.Send(message);

// Log entry to Workflow History Log
Common.WriteSuccessToHistoryLog(web, WorkflowInstanceId, string.Format(CultureInfo.InvariantCulture, “Email successfully sent to the following recipients: {0}”, message.To));
      }
      else
      {
// Log entry to Workflow History Log
StringBuilder emailAddressesTo = new StringBuilder();

for (int i = 0; i < To.Count; i++)
        {
¬†¬†¬†¬†¬†¬†¬†¬†¬† emailAddressesTo.AppendFormat(CultureInfo.InvariantCulture, “{0}, “, To[i]);
}

        // Trim off last comma
emailAddressesTo = emailAddressesTo.Remove(emailAddressesTo.Length – 1, 2);
Common.WriteFailToHistoryLog(web, WorkflowInstanceId, string.Format(CultureInfo.InvariantCulture, “Unable to send email out. No valid user email addresses for the following users ({0}) were found.”, emailAddressesTo));
}
   }
   catch (Exception ex)
   {
// Log entry to Workflow History Log
Common.WriteFailToHistoryLog(web, WorkflowInstanceId, string.Format(CultureInfo.InvariantCulture, “Failed to send email. Error message: {0}”, ex.Message));
   }
   finally
   {
      // Cleanup РDispose of these private properties before exiting
if (__ActivationProperties != null)
{
__ActivationProperties.Dispose();
}
if (__Context != null)
{
__Context.Dispose();
}
}
  }

return ActivityExecutionStatus.Closed;
}

To walk through the method, we first get the current web through the Workflow Context. We then use a couple of helper methods to build the mail message (BuildMailMessage), get the SMTP information from SharePoint (LoadSmtpInformation) and get the mail address of a user if it is passed as an account name (GetMailAddress). Please review those methods yourself if needed. Please note the LoadSmtpInformation method. It requests the outbound server address from the WebApplication. Be aware that multiple SMTP settings exist in SharePoint 2010 and that you can specify the outbound server both on server level in Central Admin and for each web application separately. In our case, we use the latter.


private static SmtpClient LoadSmtpInformation()
{
  string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address;
return new SmtpClient(smtpServer);
}

After we created the message, we try to load the attachment specified by the property. To do that, we use the AttachmentFileName property to open the SPSite where the file resides. We then open the SPWeb and use the GetFile method to load the file into a SPFile object. Finally, we use a MemoryStream to add the attachment to the mail message.

The rest of the method is to assign the From and To mail addresses. You can further expand the activity to also include CC and BCC addresses if you wish.

Register your custom action

Before you can use your custom action, you need to register it with SharePoint in the web.config. We therefore use a feature receiver to do this when activated. Add a feature to your solution and attach a feature receiver. Implement the receiver as follows:


public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
  SPWebApplication webapp = (SPWebApplication)properties.Feature.Parent;
  UpdateWebConfig(webapp, true);
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
  SPWebApplication webapp = (SPWebApplication)properties.Feature.Parent;
UpdateWebConfig(webapp, false);
}

private void UpdateWebConfig(SPWebApplication webApp, bool featureActivated)
{
¬† SPWebConfigModification modification = new SPWebConfigModification(“authorizedType[@Assembly=\”Boom.WorkflowActivities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1f97cfd14d08de08\”][@Namespace=\”Boom.WorkflowActivities\”][@TypeName=\”*\”][@Authorized=\”True\”]”, “configuration/System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes”);

¬† modification.Owner = “Boom.WorkflowActivities”;
  modification.Sequence = 0;
  modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
¬† modification.Value = string.Format(CultureInfo.InvariantCulture, “<authorizedType Assembly=\”{0}\” Namespace=\”{1}\” TypeName=\”{2}\” Authorized=\”{3}\”/>”, new object[] { “Boom.WorkflowActivities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1f97cfd14d08de08”, “Boom.WorkflowActivities”, “*”, “True” });

  if
(featureActivated)
webApp.WebConfigModifications.Add(modification);
  else
    webApp.WebConfigModifications.Remove(modification);

SPFarm
.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}

This will add or remove an authorizedType node to your web.config file, enabling SharePoint to use the action in SharePoint Designer workflows.

Add safecontrol entries to the package manifest

To ensure that SharePoint will safely load our custom activity, we add a SafeControl entry to the web.config. We do that by overriding the Package.Template.xml to include our SafeControl entry. Also note we use the VS ability to inject the assembly details on build.

<Assemblies>
  <Assembly Location=Boom.WorkflowActivities.dll DeploymentTarget=GlobalAssemblyCache>
<SafeControls>
<SafeControl Assembly=$SharePoint.Project.AssemblyFullName$ Namespace=$SharePoint.Project.FileNameWithoutExtension$ TypeName=* />
</SafeControls>
</Assembly>
</Assemblies>

Build and Test

So, the hard work is now done. The last thing to do is have VS build the package and deploy to your environment. Once an IIS reset (or app pool recycle) has been done, fire up SharePoint Designer and connect to your site. Create a new SharePoint Reusable Workflow and see if your custom action is there:

Figure 1: Custom action available

Figure 2: Complete the action parameters

Conclusion

You can do a lot with the reusable workflow abilities in SharePoint Designer 2010. However, the best part is that you can extend the capabilities that the OOB version has, which makes the SharePoint workflows far more likely to be used as they can be tweaked. A definite improvement over SharePoint 2007 where they were as they came.

Have fun building your own!

Posted in SharePoint 2010, Visual Studio 2010 | Tagged: , , , , , | 55 Comments »

 
%d bloggers like this: