Starting SharePoint Designer Workflows from SharePoint Events 

Tags:

This post describes how to start workflows from SharePoint events.  The details here are known to apply to SharePoint Designer workflows, but may also apply to Visual Studio 2005 workflows.
 
Purpose
 
Why would you want to do start a SharePoint workflow from a SharePoint event?  One good reason is that the data available within a SharePoint Designer workflow may not contain sufficient information.  In this situation there are several workarounds:
  1. Use a Visual Studio 2005 workflow instead.
  2. Do all of the work within a SharePoint event.
  3. Create custom SharePoint Designer workflow actions or conditions
  4. Provide the needed data by passing it into the workflow from an event.

The last item above is the focus of this post.  All of the items above basically give full access to the SharePoint object model, but only the last one provides the flexibiliity and ease of access of SharePoint Designer workflows.

Starting a Workflow

(Note: This discusses SharePoint events, but describing how to set up SharePoint events is beyond the scope of this post.)

To start a workflow, you'll need to reference Microsoft.SharePoint and have a using statement (imports for VB.Net) for Microsoft.SharePoint and Microsoft.SharePoint.Workflow.

Within a SharePoint event (SPItemEventReceiver), you have access to the ListItem via SPItemEventProperites.ListItem.  From there you can create a workflow manager and get the workflows associated with the list.  The code below demonstrates how to do this (note that for simplicity all error handling, etc. has been removed from this code).

    public class MyListUpdateReceiver : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            this.StartWorkflow(properties, "Added");
        }

        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            this.StartWorkflow(properties, "Updating");
        }

        private void StartWorkflow(SPItemEventProperties properties, string listEventType)
        {
            SPListItem item = properties.ListItem;

            SPWorkflowManager workflowManager = item.Web.Site.WorkflowManager;
            SPWorkflowAssociationCollection workflowAssocCol = item.ParentList.WorkflowAssociations;

            foreach (SPWorkflowAssociation workflowAssoc in workflowAssocCol)
            {
                if (workflowAssoc.Name == "MyWorkflow")
                {
                    workflowManager.StartWorkflow(item, workflowAssoc, String.Empty);
                    break;
                }
            }
        }
    }

Multiple Instances Running

When starting a workflow, you may need to make sure that no other instances of this are running.  If a version of your workflow is already running for the particular list item, then you may not be able to start another instance.  I apologize for not having the code available for this part...

Workflow Association Naming

Note that care should be taken in making sure you actually find the right workflow association.  When you save workflows from SharePoint Designer when existing versions of the workflow already exist for a list, the behavior will work in one of two ways:

  1. The latest version of the workflow will be "MyWorkflow (n)" where "n" is a incremented version number.
  2. The latest version of the workflow will be "MyWorkflow" and the previous version will be renamed to something like "MyWorkflow (previous version at <date/time>)".

It's not clear how the system determines which behavior is used (this seems to be a bug).  So, if the case is #1 for you, then you must modify your code each time to get it to work.  If it is #2, then your code should work every time.  The safest bet is to go to the list and delete all workflow association versions based on your workflow name (other completely different workflows can remain associated to the list) before you save any workflow changes in SharePoint designer.

If you dig a little further on this you will find that in the database for #1 above all workflows have the same vesion number and for #2 they have different version numbers.  So it seems that #1 is likely a bug.

Initiation Parameters

So, you've started a workflow but this didn't really gain you anything.  What you really want to do is pass in some information that is not available in a SharePoint Designer workflow.  To do this you must define initiation parameters for your workflow.  In our examples below we defined "EventType" and "After_Property1" as initiation parameters.  The parameters are provided as XML.  To make it easier to provide this, the following helper class can be used.  You'll need to add a using statement for System.Collections.Specialized.

    /// <summary>
    /// Provides event data to a workflows in the format expected by workflows created in SharePoint Designer 2007.
    /// </summary>
    /// <remarks>
    /// Example usage:
    /// <code lang="c#">
    /// // Package up the workflow event data
    /// WorkflowEventData eventData = new WorkflowEventData();
    /// eventData.Add("Param1", "Value1");
    /// eventData.Add("Param2", "Value2");
    ///
    /// // Start the workflow for an item/association pair and provide the event data
    /// workflowManager.StartWorkflow(item, workflowAssoc, eventData.ToString());
    /// </code>
    /// </remarks>
    public class WorkflowEventData : NameValueCollection
    {
        public WorkflowEventData()
        {
        }

        /// <summary>
        /// Outputs the name/value collection in the format expected by SharePoint Designer workflows.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            // The output looks like:
            // <Data>
            //    <param1>value1</param1>
            //    <param2>value2</param2>
            // </Data>
            StringBuilder sb = new StringBuilder();
            sb.Append("<Data>");
            foreach (string key in this.Keys)
            {
                sb.Append(String.Format("<{0}>{1}</{2}>", key, this[key], key));
            }
            sb.Append("</Data>");
            return sb.ToString();
        }
    }

Here is a modified version of our StartWorkflow() method showing how to pass data to your workflow using the WorkflowEventData helper class.

        private void StartWorkflow(SPItemEventProperties properties, string listEventType)
        {
            SPListItem item = properties.ListItem;

            SPWorkflowManager workflowManager = item.Web.Site.WorkflowManager;
            SPWorkflowAssociationCollection workflowAssocCol = item.ParentList.WorkflowAssociations;

            foreach (SPWorkflowAssociation workflowAssoc in workflowAssocCol)
            {
                if (workflowAssoc.Name == "MyWorkflow")
                {
                    string afterProperty1 = properties.AfterProperties["Property1"].ToString();
                    WorkflowEventData eventData = new WorkflowEventData();
                    eventData.Add("EventType", listEventType.ToString());
                    eventData.Add("After_Property1", afterProperty1);
                    workflowManager.StartWorkflow(item, workflowAssoc, eventData.ToString());
                    break;
                }
            }
        }

Make sure you understand the issues around before and after properties and how they act differently for synchronous and asynchronous events.  Discussion on this is beyond the scope of this post.

Note also that when accessing fields within a list (e.g., "Property1" above), you need to use the internal name for the field.  This can be determined using code, but can also be found using the U2U CAML Builder and can be downloaded from the U2U Community Tools Site.

Disclaimer

The code above was scrubbed to create an example suitable for this post.  Extra content such as constants, error handling, references to specific list names, etc. has been removed.  The code has been checked to ensure there were no compilation errors after the scrubbing exercise, but has not been tested after it was scrubbed.

 
Posted by Kirk Liemohn on 13-Mar-07
12 Comments  |  Trackback Url  |  Link to this post | Bookmark this post with:        
 

Links to this post

Comments


wow gold commented on Tuesday, 28-Oct-2008
Masters wow gold of the hunt, wilderness wow gold trackers and buy wow gold the strongest buy wow gold ranged DPS cheap wow gold in cheap wow gold, Hunters world of warcraft gold play an fast wow gold essential sell wow gold role in the dangerous age of conan gold land of aoc gold Azeroth. Able to ffxi gil tame wild warhammer gold animals to serve as runescape gold loyal companions, Hunters tibia gold are swg credits excellent soloers lotro gold and can single-handedly 2moons dil fight multiple maple story mesos beasts eve isk simultaneously and still lineage 2 adena emerge victorious. Their eq2 plat strength wow power leveling lies in wow power leveling long-ranged power leveling combat, but world of warcraft power leveling Hunters are still wow power level quite wow leveling capable up wow leveling close in power leveling melee. They wow gold are easily buy wow gold considered one cheap wow gold of the world of warcraft gold strongest wow power leveling overall characters in power leveling and have world of warcraft power leveling quickly become wow gold a popular cheap wow gold favourite for many buy wow gold players. One of wow gold the key unique nut and boltbolt nut powers of the Hunter nuts and bolts is their bolts nuts ability to track a variety of creatures.


wow commented on Thursday, 30-Oct-2008
lc Welcome to wow gold. We are a world class wow powerleveling store online. We supply cheap wow gold to our loyal and World of Warcraft goldreliable customers. you canwow power leveling buy really cheapwow gold wow gold here. We havewow power leveling mass available stock ofwow power leveling wow gold onwow power leveling most of the servers, sowow power leveling that we can do aRolex really instant way of wow power levelingwow gold wow golddelivery. We canwow powerleveling deliver yourwow powerleveling wow gold on powerlevelingthe order powerlevelingin a short cheap wow goldwhile. We have beencheap wow gold an ebay powerpower leveling seller and paypalpower leveling confirmed seller rolex replicaof wow gold for replica rolexyears.So it ischeap wow gold securest and safestRunescape Gold to buy RuneScape Money wow gold from Watches Rolexus. Don’t be Rolex Watchesirresolute! We arewow gold hoping to servegold wow you and helpingWatch Rolex you to have a wonderfulRolex Watch wow life! We arers gold ready now, how about you?


nq316 commented on Saturday, 1-Nov-2008

wowgolds987 commented on Saturday, 8-Nov-2008
World of Warcraft to sell wow gold professional trading platform moinn.com coming! We have launched cheap warcraft gold and wow power leveling , and so on, do not you take a look at as soon as possible. We provide you with quality service, you can rest assured that purchase.


asdf commented on Wednesday, 12-Nov-2008
2GB MP3 PLAYER "In addition to providing . 4GB MP3 PLAYER my own WoW Leveling Guide to help you maximize your. buy wow gold WoW enjoyment I’ll discuss . buying gold world of warcraft other great WoW leveling guides available to you along with. cell phones the problems and benefits of power leveling . cheap cell phones guides and power leveling services. cheap wow gold I may also poke a little fun at the . cheap wow gold WoW forum communities. cheap wow gold for their uncanny persistence . cheapest wow gold so you’ll eventually find both a horde .eve isk One important note about my approach . mp3 players I strictly avoid and discourage cheats and hacks. phones cell and I also strongly discourage paying for leveling services. portable mp3 player This game is meant to be played; it is meant to be FUN. portable mp3 players your money or making yourself feel lame for cheating. sell wow gold Joana’s Horde Leveling Guide and Brian Kopp’s Alliance Leveling Guide. world of warcraft gold give you some extra tips to help you maximize their usage. wow value than any power leveling service or cheat. wow gold you can use them over-and-over for the rest of your life. wow gold And they don’t teach methods that will either get you banned or make you feel lame. wow gold that one might argue you’re already at a disadvantage for not yet using them. wow gold it so boring and tedious that it ruined the game for you. wow gold This is what I want to avoid. wow gold I do encourage some aggressive and creative methods because . wow gold kaufen help you learn methods you could already learn from .wow gold kaufen If you have played World . mp3playershopping.de/Shops/8GB-MP3-Player.aspx">8GB MP3 PLAYER of Warcraft for any amount of time. you will be able to relate to what I'm about to share with you. apple ipodFor the first time ever. buy cheap wow gold my self-used secrets of the power of leveling. which I have used to. canon digital camera count the ones I helped with. cheap world of warcraft gold friends. WARNING This. digital cameraof the way I learned how to level.digital cameras I wanted in World of Warcraft. dvd player Not only that. eve isk leveling speed to. below 6 days /played! We are only . ipod at the beginning of this letter. ipod nano If I were you.ipod shuffle And you are completely right to.ipod touch Look, if I wasn't the guy who used.ipods and seen the process with my own two eyes. mp3 player So let me set the record straight by pulling back . mp3 players mp4 I know you've heard people talk about ""competitive gamers"" before, you know. portable dvd players no life, and they Eat. Sleep and Breath gaming. world of warcraft buy gold So right now. wow I'm going to set the records straight and let you . wow gold I started playing. wow gold Completely blind to any concept of the game. wow leveling This is before The Burning Crusade. wow powerleveling Unfortunately I made that character before I found out. zubehoer mp3 player They talked me into switching servers and playing with them. survived the horrific explosion rallied. buy cheap wow gold landmass in sight. Cheapest wow gold Somehow. by the grace of Elune. des po wow fellow survivors and establish. digital audio mp3 player they surveyed the . wreckage of their. digital mp3 player ripped from the world by the Well's destruction. free online games Malfurion and his companions were left to ponder . free online war games of the new land along with. gold wow he was satisfied that they could cause . gold wow elves landed upon the shores of the new land. lord of the rings online gold Seeking to establish a . lotro gold new home for themselves. mp3 player nestled between the mountain's enormous peaks. online games they found a small. tranquil lake. play war games Sundering as well. po wow and the night elves. wow europe precious waters from the Well of Eternity. wow fr energies quickly ignited and coalesced. wow geld was shocked when Malfurion hunted him down. wow gold Illidan refused to relinquish his magical powers. wow gold cheap With Cenarius' help. wow gold cheapest where he would remain chained and. wow gold verkaufen Maiev Shadowsong, to be Illidan's personal jailor. wow golds Well might bring about an . wow level service leave it be. wow leveling service would never practice the . wow powerleveling arts of magic again. the prospect of making. 20gb mp3 player didn’t seem like a bad idea either. cheap wow power leveling Too deep in his own thoughts. flash mp3 player a human voice said.flash mp3 players he could recollect Loran was some sort of Captain too. HDRO gold I don’t think I’ve seen you around before. level wow hundreds of prisoners .lord of rings online gold all to be quite frank. lotro gold but right now an upper-class. lotro gold trotted off just now. mp3 player 2gb video as Trolls are from my experience quite . mp3 player usb stumble your way into this god forsaken place. mp3 player with video .power level the delivery, although somewhat late. power level Loran continued. usb mp3 players and started walking back. wow level warn Stormwind of the structure. wow leveling “There’s been quite some activity. wow lvl though most of them were Trolls themselves”. wow lvl he didn’t like it too much. wow lvl 60 unable to organize anything more advanced than a barbecue. wow lvl 70 have been transferred up to some sort of execution chamber. wow power leveling Durin noticed the upper-class Stormwind speech. wow powerlevel not a very jolly sight at. wow powerlevel He decided he had to. wow powerleveling


情趣用品 commented on Tuesday, 18-Nov-2008
情趣用品,情趣用品,情趣用品,情趣用品,情趣,情趣,情趣,情趣,按摩棒,跳蛋,充氣娃娃,免費A片,AV女優,美女視訊,情色交友,免費AV,色情網站,辣妹視訊,美女交友,色情影片,成人影片,成人網站,A片,H漫,18成人,成人圖片,成人漫畫,情色網,日本A片,免費A片下載,性愛,A片,色情,成人,做愛,情色文學,A片下載,色情遊戲,色情影片,色情聊天室,情色電影,免費視訊,免費視訊聊天,免費視訊聊天室,一葉情貼圖片區,情色,情色視訊,免費成人影片,視訊交友,視訊聊天,視訊聊天室,言情小說,愛情小說,AIO,AV片,A漫,av dvd,聊天室,自拍,情色論壇,視訊美女,AV成人網,色情A片,情趣用品,A片,免費A片,AV女優,美女視訊,情色交友,色情網站,免費AV,辣妹視訊,美女交友,色情影片,成人網站,H漫,18成人,成人圖片,成人漫畫,成人影片,情色網,sex,情趣用品,A片,免費A片,日本A片,A片下載,線上A片,成人電影,嘟嘟成人網,成人,成人貼圖,成人交友,成人圖片,18成人,成人小說,成人圖片區,微風成人區,成人文章,成人影城,情色,情色貼圖,色情聊天室,情色視訊,情色文學,色情小說,情色小說,臺灣情色網,色情,情色電影,色情遊戲,嘟嘟情人色網,麗的色遊戲,情色論壇,色情網站,一葉情貼圖片區,做愛,性愛,美女視訊,辣妹視訊,視訊聊天室,視訊交友網,免費視訊聊天,美女交友,做愛影片,情境坊歡愉用品,情趣用品,情人節禮物,情惑用品性易購,av,情趣用品,a片,成人電影,微風成人,嘟嘟成人網,成人,成人貼圖,成人交友,成人圖片,18成人,成人小說,成人圖片區,成人文章,成人影城,愛情公寓,情色,情色貼圖,色情聊天室,情色視訊,情色文學,色情小說,情色小說,色情,寄情築園小遊戲,情色電影,aio,av女優,AV,免費A片,日本a片,美女視訊,辣妹視訊,聊天室,美女交友,成人光碟


warhammer commented on Thursday, 27-Nov-2008

wowgolds987 commented on Friday, 19-Dec-2008
Do not want to spend a lot of money buy wow gold ? mmoinn.com desire to help you achieve. We provide you with the cheapest wow gold and wow power leveling . To buy as soon as possible!


taro commented on Saturday, 20-Dec-2008

car wash commented on Monday, 29-Dec-2008
Best china wholesale service, quick wholesale delivery, nice wholesale products, is there anything more you can expect on this platform? This net will build up a link between you and you supplier so that to be sure you would have a satisfied wholesale clothingwholesale apparel trading. The account managers will take care of all your wholesale products questions, inquires and help you manage your account. We provid popular wholesale products such as wholesale watch and wholesale electronics. Different from other platforms, we also provide consumer electronics products, for example car electronics and digital camera. Meanwhile, we offer the best bluetooth phones and GPS Cellphone . Well begun is the half done. Please choose our platform to shorten your way to the successwholesale shoes,wholesale handbagsand wholesale toys
we offer chloe betty handbag,hermes handbags,gucci handbags,,balenciaga handbags,mulberry handbag,roxanne bag,hermes kelly bags,chloe betty bags ,miumiu bags,d&g handbags,fendi spy bag,chloe ascot handbag,hermes birkin,prada handbag,jimmy choo,leather wallets hermes we a supplier of those products.if you have any interest.contact ours Chinese antique furniture supplier and we can supplycar wash systems. car wash systems .car wash equipment. car wash equipment. automatic car wash .automatic car wash .car washing machine. car washing machine. car wash. car wash

楼梯有机玻璃电焊机硬度计测厚仪毛刷厂 毛刷毛刷北京汽车租赁防静电地板 白癜风 白癜风治疗货架 货架厂 网络地板 白癜风遮盖白癜风资讯白癜风资讯白癜风治疗有机玻璃加工数控切割机数控火焰切割机数控等离子切割机焊机健身器材 桶装水送水公司

工业毛刷 尖锐湿疣 尖锐湿疣治疗 生殖器疱疹 生殖器疱疹治疗 毛刷厂 帕金森清洗毛刷轻松过关名师课堂 粘钢胶树脂灌缝胶建筑结构胶植筋胶 结构胶灌浆料 灌浆 XYLITOLSODIUM SULPHATECAUSTIC SODA FLAKESMANGANESE SULFATESODIUM FORMATEMAGNESIUM SULFATEOXALIC ACIDFORMIC ACIDXYLITOLSODIUM SULPHATECAUSTIC SODA FLAKESMANGANESE SULFATESODIUM FORMATEMAGNESIUM SULFATEOXALIC ACIDFORMIC ACID Chinese antique furniture supplier and we can supplycar wash systems. car wash systems .car wash equipment. car wash equipment. automatic car wash .automatic car wash .car washing machine. car washing machine. car wash. car wash if u need ,contact me 会计专业资格会计专业资格考试会计从业资格证书会计专业技术资格会计从业资格证初级职称初级会计资格初级会计职称会计报名中级会计资格中级会计职称初级会计职称考试中级会计职称考试09年中级会计职称考试轻松过关名师课堂闫华红田明王燕会计答疑会计试题会计职称模拟试卷会计职称考前串讲会计职称历年试题会计资讯会计职称考试报名会计职称称准考证会计名师会计职称培训会计从业资格试题09年会计从业资格考试2009年会计报名2009年会计职称考试规律总结职称考试应试技巧会计职称考试答案会计职称考试试题会计职称考试时间中级职称初级职称培训初级职称报名中级职称报名中级职称培训职称考试初级会计中级会计初级会计初级中级 会计考试报名会计职称考试报名会计职称报名时间会计中级职称报名注会成绩查询注会考试成绩查询会计考试复习资料会计考试教材会计考试辅导视频会计考试历年试题会计考试真题会计考试答疑会计辅导名师最好的会计网校会计辅导权威网校最好的会计网会计远程教育权威会计网校会计人网上家园注册会计师教材会计论坛注册会计师会计在线学习北京会计培训注税考试报名注税考试辅导教材注税考试辅导课程高会考试报名高会考试辅导教材高会考试辅导课程高级会计师会计考试论坛中级财务管理注会经济法中级经济法经济法基础初级会计实务公司战略与风险管理注会税法经济法基础中级会计实务注会政策改革注会会计注会财务成本管理注会审计会计中级报名指南注会会计


Name:
URL:
Email:
Comments:

CAPTCHA Image Validation