Code Snippets

Update a Infopath request form from Sharepoint Workflow

Posted on August 19, 2010. Filed under: Code Snippets | Tags: , , , , |

Use the below method in SharePoint workflow to modify a field value in your request form.

private void updateInfoPathRequestForm(string xpathNode, string nodeValue)
        {
            SPUserToken token = workflowProperties.Web.CurrentUser.UserToken;
            using (SPSite _site = new SPSite(workflowProperties.Site.ID, token))
            {
                _site.AllowUnsafeUpdates = true;
                using (SPWeb _web = _site.OpenWeb(workflowProperties.Web.ID))
                {
                    SPListItem item = _web.Lists[workflowProperties.List.ID].Items[workflowProperties.Item.UniqueId];
                    string checkinComment = string.Empty;
                    _web.AllowUnsafeUpdates = true;
                    try
                    {
                        if (item.File.CheckOutStatus != SPFile.SPCheckOutStatus.None) { item.File.UndoCheckOut(); }
                        item.File.CheckOut();

                        MemoryStream myInStream = new MemoryStream(item.File.OpenBinary(), true);
                        XmlDocument doc = new XmlDocument();

                        doc.Load(myInStream);
                        myInStream.Close();
                        XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(doc.NameTable);
                        XmlElement root = doc.DocumentElement;
                        nameSpaceManager.AddNamespace(“my”, root.NamespaceURI);

                        XmlNode nodeNav = root.SelectSingleNode(xpathNode, nameSpaceManager);
                        nodeNav.InnerText = @nodeValue;

                        checkinComment = “Workflow Edits”;
                        Stream myOutStream = new MemoryStream(Encoding.Utf8.GetBytes(doc.OuterXml), true);
                        item.File.SaveBinary(myOutStream, true);
                        myOutStream.Close();
                    }
                    catch (Exception ex)
                    {
                        //Write the Exception to the Portal Log.
                        PortalLog.LogString(“xxxxxxRequestWorkflow-Exception Occured on custom method-updateInfoPathRequestForm. Exception: {0} || {1}”, ex.Message, ex.StackTrace);
                        
                        //throw new SPException(“”);
                    }
                    finally
                    {
                        item.File.CheckIn(checkinComment);
                    }
                    _web.AllowUnsafeUpdates = false;
                }
                _site.AllowUnsafeUpdates = false;
            }
        }

The only issues i would assume would be the encoding styles while you are writing back the stream to the form, which may effect some out of date character set or lang pack character set

Advertisements
Read Full Post | Make a Comment ( None so far )

How to read repeating fields from Info Path request form

Posted on January 8, 2010. Filed under: Code Snippets | Tags: , , , |

This custom method can be used to read a single field or repeating fields of a Info Path request form from a sharepoint workflow.

//xpathNode – The actual Xpath node value in the datasource of your info path form
//mutiplenodes – a bool variable that defines whether you are parsing a single node or trying to parse subsequent child nodes under the parent “xpathNode”
//childNode – repeating childnode xpath value under the parent “xpathNode”  in the info path request form.
  
private string parseInfoPathRequestForm(string xpathNode, bool mutlipleNodes, string childNode)
        {
            SPFile requestForm = workflowProperties.Item.File;
            byte[] requestFormData = requestForm.OpenBinary();
            XPathDocument inForm = null;
            string parseNode = xpathNode;
            string parseNodeValue = string.Empty;

            try
            {
                using (MemoryStream ms = new MemoryStream(requestFormData))
                {
                    inForm = new XPathDocument(ms);
                    ms.Close();
                }
                XPathNavigator inFormNav = inForm.CreateNavigator();
                inFormNav.MoveToFollowing(XPathNodeType.Element);
                XmlNamespaceManager nsManager = new XmlNamespaceManager(new NameTable());

                foreach (KeyValuePair<string, string> ns in inFormNav.GetNamespacesInScope(XmlNamespaceScope.All))
                {
                    if (ns.Key == String.Empty)
                    {
                        nsManager.AddNamespace(“def”, ns.Value);
                    }
                    else
                    {
                        nsManager.AddNamespace(ns.Key, ns.Value);
                    }
                }

                if (!mutlipleNodes)
                {
                    XPathNavigator nodeNav = inFormNav.SelectSingleNode(parseNode, nsManager);
                    if (nodeNav != null)
                        parseNodeValue = nodeNav.Value;
                }
                else if (mutlipleNodes)
                {
                    XPathNodeIterator reviewers = inFormNav.Select(parseNode, nsManager);
                    foreach (XPathNavigator person in reviewers)
                    {
                        parseNodeValue = parseNodeValue + “;” + person.SelectSingleNode(childNode, nsManager).Value;
                    }
                }
            }
            catch (Exception ex)
            {
                //Write the Exception to the Portal Log.
               
            }

            return (parseNodeValue);
        }

Usage :
//Repeating section-
 _RequestReviewers = parseInfoPathRequestForm(“//my:ptFields//my:authorDetails//my:pickReviewers”, true, “my:reviewerSelector//my:contactSelector//my:Person//my:AccountId”); < Here pickReviewers is a repeating section with a contact selector (reviewerSelector) placed in that.>
//Single field –
_PublicationType = parseInfoPathRequestForm(“//my:ptFields//my:authorDetails//my:publicationType”, false, “”);

Read Full Post | Make a Comment ( 2 so far )

Update a SharePoint Workflow Task

Posted on August 4, 2009. Filed under: Code Snippets | Tags: , , |

private void updateTaskItem(SPWorkflowTaskProperties tProperties)
        {
            //Pull out the Task Items from the tasks list by passing
            //a query as variable to SPListItemCollection GetItems()
            Guid tListID = new Guid(workflowProperties.TaskListId.ToString());
            SPQuery tQuery = new SPQuery();
            //Query to pull the list item from the Tasks list. Items with Status ‘Completed’ will be left out.
            tQuery.Query = “<Where><Neq><FieldRef Name=’Status’/>” + “<Value Type=’CHOICE’>Completed</Value></Neq></Where>”;
           
                //Pull out the Tasks List using the ID provided in workflow properties
                SPList tasksList = workflowProperties.Web.Lists[tListID];
                //Querying the Tasks List returns a set of Tasks, store them.
                SPListItemCollection tCollection = tasksList.GetItems(tQuery);

                //Parse through each of the Task Item
                foreach (SPListItem tListItem in tCollection)
                {
                    //Condition Execution, Verify for the Right Task and modify the Status
                    if (tListItem.Title == tProperties.Title)
                    {
                        if (tListItem[“Status”] == “Not Started”)
                        {
                            tListItem[“Status”] = “Completed”;
                        }
                       
                        tListItem.Update();
                    }

                }

           }

Call this method by providing the respective Taskproperties in your MOSS Workflow to modify the status or any other field.

Read Full Post | Make a Comment ( None so far )

Getting User data from SPfield

Posted on August 4, 2009. Filed under: Code Snippets | Tags: , , |

private SPUser getUser(SPListItem item, SPField listUser)

{

string listUserValue = item[listUser.Title].ToString();

SPFieldUser field = (SPFieldUser)listUser;

SPFieldUserValue fieldValue = (SPFieldUserValue)field.GetFieldValue(listUserValue);

return fieldValue.User;

}

USAGE: string userEmail = getUser(listItem, listItem.Fields[“Modified By”]).Email;

lly any other data like displayname etc.,

Read Full Post | Make a Comment ( None so far )

Set Specific Item Permissions

Posted on August 4, 2009. Filed under: Code Snippets | Tags: , , |

/ Set specific permissions <frm workflow view>
System.Collections.Specialized.HybridDictionary itemPermissions = new System.Collections.Specialized.HybridDictionary();
itemPermissions[workflowProperties.Originator] = SPRoleType.Contributor; (or give him appropriate permissions )
itemPermissions[taskApprover] = SPRoleType.Contributor;
createTask.SpecialPermissions = itemPermissions;

Read Full Post | Make a Comment ( None so far )

    About

    Xperiments n Xperiences. For the Last 5 years I have been providing variuos portal solutions (SharePoint focused) to my clients and now I intend to publish few of those solutions 'Not As It Is', which might help you. – Mash

    RSS

    Subscribe Via RSS

    • Subscribe with Bloglines
    • Add your feed to Newsburst from CNET News.com
    • Subscribe in Google Reader
    • Add to My Yahoo!
    • Subscribe in NewsGator Online
    • The latest comments to all posts in RSS

    Meta

Liked it here?
Why not try sites on the blogroll...