Tuesday, June 5, 2012

WorkFlow SharePoint 2010


using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Workflow;
using System.Collections;
namespace test.Layouts.test
{
    public partial class test6 : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnClick_Click(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Announcements"];
                    SPListItem item = null;
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><Contains><FieldRef Name='Title'/><Value  Type='Text'>Microsoft</Value></Contains></Where>";
                    query.RowLimit = 2;

                    SPListItemCollection items = list.GetItems(query);
                    if (items.Count > 0)
                    {
                        item = items[0];
                        lbl1.Text = item["Title"].ToString();

                        if (items[1] != null)
                        {
                            item = items[1];
                            lbl2.Text = item["Title"].ToString();
                        }
                        else { lbl2.Text = "Title Null"; }
                    }
                }
            }
        }
        protected void btnClick1_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList announcements = web.Lists["Announcements"];
                        SPList tasks = web.Lists["Tasks"];
                        SPList history = web.Lists["Workflow History"];
                        SPWorkflowTemplateCollection templateColl = web.WorkflowTemplates;
                        //int i = 0;
                        //foreach (SPWorkflowTemplate template1 in templateColl)
                        //{
                        //    lbl2.Text += i + ". " + template1.Name + " # ";
                        //    i++;
                        //}
                        SPWorkflowTemplate template = web.WorkflowTemplates.GetTemplateByName("Approval - SharePoint 2010", web.Locale);
                        SPWorkflowAssociation association = SPWorkflowAssociation.CreateListAssociation(template, "Announcements Approval", tasks, history);
                        announcements.WorkflowAssociations.Add(association);
                        //announcements.WorkflowAssociations.Remove(association);
                        announcements.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick2_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPWorkflowAssociationCollection workflowsToUpdate = null;

                        SPList announcements = web.Lists["Announcements"];
                        SPList tasks = web.Lists["Tasks"];
                        SPList history = web.Lists["Workflow History"];
                        SPWorkflowTemplate template = web.WorkflowTemplates[new Guid("8AD4D8F0-93A7-4941-9657-CF3706F00409")]; //Approval - SharePoint 2010

                        workflowsToUpdate = announcements.WorkflowAssociations;
                        lbl1.Text += "Workflows associations in workflowsToUpdate: " + workflowsToUpdate.Count + " # ";

                        SPWorkflowAssociation workflow1 = SPWorkflowAssociation.CreateListAssociation(template, "Workflow 1", tasks, history);
                        announcements.WorkflowAssociations.Add(workflow1);
                        lbl2.Text += "Workflows associations in workflowsToUpdate after adding 'Workflow 1': " + workflowsToUpdate.Count + " # ";

                        SPWorkflowAssociation workflow2 = SPWorkflowAssociation.CreateListAssociation(template, "Workflow 2", tasks, history);
                        announcements.WorkflowAssociations.Add(workflow2);
                        lbl3.Text += "Workflows associations in workflowsToUpdate after adding 'Workflow 2': " + workflowsToUpdate.Count + " # ";
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick3_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        //foreach (SPWorkflowTemplate wfTemplate in web.WorkflowTemplates)
                        //{
                        //    if (wfTemplate.Id.Equals(new Guid("3BC0C1E1-B7D5-4e82-AFD7-9F7E59B60409"))) // .Name.Contains("Approval - SharePoint 2010"))
                        //    {
                        //        lbl1.Text += wfTemplate.Name + " @@ "; // .Id + " @@ "; // wfTemplate.Name.Contains("Approval");
                        //    }
                        //    else
                        //    {
                        //        lbl2.Text += wfTemplate.Name + " # "; ;
                        //    }
                        //}
                        SPWorkflowTemplate template = web.WorkflowTemplates.GetTemplateByBaseID(new Guid("8AD4D8F0-93A7-4941-9657-CF3706F00409"));
                        if (template == null || !template.Name.Contains("Approval")) //Announcements Approval
                        {
                            throw new ArgumentException("Expected to find the Approval workflow " + "template. Please verify the template ID and server type.");
                        }
                        else
                        {
                            lbl3.Text = template.Name + " # ";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick4_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPWorkflowTemplate template = web.WorkflowTemplates[new Guid("8AD4D8F0-93A7-4941-9657-CF3706F00409")];
                        lbl1.Text += template.Name + " # ";
                        if (template == null)
                        {
                            throw new ArgumentException("The specified template could not be found.");
                        }
                        template = web.WorkflowTemplates[39];
                        lbl2.Text += template.Name + " # ";
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick5_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList announcements = web.Lists["Announcements"];

                        bool isRunning = false;
                        while (!isRunning)
                        {
                            SPWorkflowAssociation association = announcements.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);
                            lbl2.Text = association.RunningInstances.ToString();
                            isRunning = (association.RunningInstances > 0);
                            System.Threading.Thread.Sleep(100);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick6_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite adminSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb adminWeb = adminSite.OpenWeb())
                    {
                        SPUser user1 = adminWeb.Users["Domain\\user1"];
                        SPUser user2 = adminWeb.Users["Domain\\user2"];

                        using (SPSite user1Site = new SPSite(SPContext.Current.Site.ID, user1.UserToken))
                        {
                            using (SPWeb user1Web = user1Site.OpenWeb())
                            {
                                user1Web.AllowUnsafeUpdates = true;
                                lbl1.Text += user1.UserToken.ToString() + " # ";
                                SPList list = user1Web.Lists["Announcements"];
                                SPListItem item = list.GetItemById(1);
                                item["Title"] += " [updated by user1]";
                                item.Update();
                                user1Web.AllowUnsafeUpdates = false;
                            }
                        }
                        using (SPSite user2Site = new SPSite(SPContext.Current.Site.ID, user2.UserToken))
                        {
                            using (SPWeb user2Web = user2Site.OpenWeb())
                            {
                                lbl2.Text += user1.UserToken.ToString() + " # ";
                                SPList list = user2Web.Lists["Announcements"];
                                SPListItem item = list.GetItemById(2);
                                item[Title] += " [updated by user2]";
                                item.Update();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick7_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["Announcements"];
                        SPListItem item = list.GetItemById(1);

                        bool isRunning = false;
                        while (!isRunning)
                        {
                            SPWorkflowAssociation assoc = list.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);
                            lbl1.Text = item[list.WorkflowAssociations[assoc.Id].Name].ToString();
                            if (assoc.RunningInstances > 0)
                            {
                                lbl1.Text = "Workflow already started # ";
                                isRunning = true;
                            }
                            else if (Convert.ToInt32(item[list.WorkflowAssociations[assoc.Id].Name]) == 15)
                            {
                                lbl1.Text = "Workflow Cancled # ";
                                isRunning = true;
                            }
                            else
                            {
                                //site.WorkflowManager.StartWorkflow(item, assoc, String.Empty);
                                site.WorkflowManager.StartWorkflow(item, assoc, assoc.AssociationData, SPWorkflowRunOptions.Synchronous);
                                System.Threading.Thread.Sleep(1000);
                                item.EnsureWorkflowInformation();

                                isRunning = (assoc.RunningInstances > 0);
                                System.Threading.Thread.Sleep(100);

                                SPWorkflowTask task = item.Tasks[0];
                                String title = task["Title"].ToString();
                                if (title == null || !title.StartsWith("Please approve"))
                                {
                                    throw new System.FormatException("Unexpected task title: This task was not assigned " + "by the SharePoint 2010 Approval workflow.");
                                }
                                else
                                {
                                    lbl2.Text = "Workflow Started # ";
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick8_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList announcements = web.Lists["Announcements"];
                        SPList tasks = web.Lists["Tasks"];
                        SPList history = web.Lists["Workflow History"];
                        SPWorkflowTemplate template = web.WorkflowTemplates.GetTemplateByName("Approval - SharePoint 2010", web.Locale);
                        SPWorkflowAssociation workflow = SPWorkflowAssociation.CreateListAssociation(template, "My Basic Workflow", tasks, history);
                        announcements.WorkflowAssociations.Add(workflow);
                        site.WorkflowManager.StartWorkflow(announcements.GetItemById(2), workflow, String.Empty, SPWorkflowRunOptions.Synchronous);
                        lbl1.Text += "Workflow Started for Item 1";
                        site.WorkflowManager.StartWorkflow(announcements.GetItemById(3), workflow, String.Empty, SPWorkflowRunOptions.SynchronousAllowPostpone);
                        lbl2.Text += "Workflow Started for Item 2";
                        site.WorkflowManager.StartWorkflow(announcements.GetItemById(4), workflow, String.Empty, SPWorkflowRunOptions.Asynchronous);
                        lbl3.Text += "Workflow Started for Item 3";
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick9_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists["Announcements"];
                        SPListItem item = list.GetItemById(4);
                        //SPWorkflowAssociation assoc = list.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);
                        //SPWorkflowAssociationCollection objWorkflowAssociationCollection;
                        //SPWorkflowManager objWorkflowManager;

                        SPWorkflowAssociation assoc = list.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);

                        //foreach (SPWorkflowAssociation objWorkflowAssociation in objWorkflowAssociationCollection)
                        //{
                        //    SPWorkflowAssociation assoc = list.WorkflowAssociations.GetAssociationByName("Announcements Approval", web.Locale);                           

                        //    if (objWorkflowAssociation.BaseId == wfguid)
                        //    {
                        //        FCTimerJobListItem["wfguid"] = objWorkflowAssociation.BaseId.ToString();
                        //        FCTimerJobListItem.Update();
                        //        objWorkflowManager.StartWorkflow(ResignationListItem, objWorkflowAssociation, objWorkflowAssociation.AssociationData, true);

                        //        site.WorkflowManager.StartWorkflow(item, assoc, assoc.AssociationData, true);
                        //    }
                        //}

                        if (assoc.Id != null)
                        {
                            //site.WorkflowManager.StartWorkflow(item, assoc, assoc, String.Empty);
                            site.WorkflowManager.StartWorkflow(item, assoc, assoc.AssociationData, SPWorkflowRunOptions.Synchronous);
                        }
                        else
                        {
                            lbl2.Text = "No Workflow was associated with selected list item " + assoc.Id + " # ";
                        }
                        System.Threading.Thread.Sleep(5000);
                        item.EnsureWorkflowInformation();
                        SPWorkflowTask task = item.Tasks[0];

                        task[SPBuiltInFieldId.ExtendedProperties] += "ows_Color='Blue'";
                        Hashtable properties = SPWorkflowTask.GetExtendedPropertiesAsHashtable(task);
                        if (properties["Color"].ToString() != "Blue")
                        {
                            throw new Exception("The extended property 'Color' " + "was not set to the expected value 'Blue'.");
                        }
                        else
                        {
                            lbl2.Text = "Color is " + properties["Color"].ToString() + " # ";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lbl3.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
        protected void btnClick10_Click(object sender, EventArgs e)
        {
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList docs = web.Lists["Shared Documents"];
                        SPList tasks = web.Lists["Tasks"];
                        SPList history = web.Lists["Workflow History"];
                        SPWorkflowTemplate template = web.WorkflowTemplates.GetTemplateByBaseID(new Guid("8AD4D8F0-93A7-4941-9657-CF3706F00409"));  //Approval - SharePoint 2010
                        //SPWorkflowAssociation workflow = SPWorkflowAssociation.CreateListAssociation(template, "Document Approval", tasks, history);
                        SPWorkflowAssociation workflow = docs.WorkflowAssociations.GetAssociationByName("Document Approval", web.Locale);
                        //docs.WorkflowAssociations.Add(workflow);
                        String data = String.Format("<dfs:myFields xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\' xmlns:dms=\'http://schemas.microsoft.com/office/2009/documentManagement/types\' xmlns:dfs=\'http://schemas.microsoft.com/office/infopath/2003/dataFormSolution\' xmlns:q=\'http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields\' xmlns:d=\'http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields\' xmlns:ma=\'http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes\' xmlns:pc=\'http://schemas.microsoft.com/office/infopath/2007/PartnerControls\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\"><dfs:queryFields></dfs:queryFields><dfs:dataFields><d:SharePointListItem_RW><d:Approvers><d:Assignment><d:Assignee><pc:Person><pc:DisplayName>{0}</pc:DisplayName><pc:AccountId>{1}</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person></d:Assignee><d:Stage xsi:nil=\'true\' /><d:AssignmentType>Serial</d:AssignmentType></d:Assignment></d:Approvers><d:ExpandGroups>true</d:ExpandGroups><d:NotificationMessage /><d:DueDateforAllTasks xsi:nil=\'true\' /><d:DurationforSerialTasks xsi:nil=\'true\' /><d:DurationUnits>Day</d:DurationUnits><d:CC /><d:CancelonRejection>false</d:CancelonRejection><d:CancelonChange>false</d:CancelonChange><d:EnableContentApproval>false</d:EnableContentApproval></d:SharePointListItem_RW></dfs:dataFields></dfs:myFields>", "TRAINING0\\latheef.hyder", "TRAINING0\\latheef.hyder");
                        site.WorkflowManager.StartWorkflow(docs.GetItemById(8), workflow, data);
                        lbl1.Text += "Workflow Started # ";
                        lbl2.Text += data + " # "; // SerialtrueDayfalsefalsefalse # 
                    }
                }
            }
            catch (Exception ex)
            {
                lbl4.Text = ex.Message.ToString() + " # " + ex.StackTrace.ToString();
            }
        }
    }
}
The Workflow status are constants (integers), So you'll need to refer to a list like:
1. Status: Value
2. Not Started: 0
3. Failed On Start: 1
4. In Progress: 2
5. Error Occurred: 3
6. Canceled: 4
7. Completed: 5
8. Failed On Start(Retrying): 6
9. Error Occurred (Retrying): 7
10. Canceled: 15
11. Approved: 16
12. Rejected: 17

No comments:

Post a Comment

Featured Post

Azure OpenAI Chat in C# and Python

Azure OpenAI Chat in C#: // Install the .NET library via NuGet: dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.5   using System; u...

Popular posts