Sunday, May 20, 2012

CREATE WORKFLOW WITH CUSTOM TASK FORM ASPX AND CONFIGURE ASSOCIATION FORM IN SHAREPOINT 2010


Download Exmple at here

Step implement

Design form AssociateForm.aspx

Edit code workflow

Demo application

Implement

Design form AssociateForm.aspx

Download example in article (CREATE WORKFLOW WITH CUSTOM TASK FORM IN SHAREPOINT 2010) then continue design .
Right click to Project | Add new Item | Application Page | name is AssociationForm.aspx
Cut AssociationForm.aspx to Form module
AssociationForm.aspx was cut
Change DynamicMasterPageFile to MasterPageFile by delete Dynamic character
Delete old code here
Change new code


/////////////////////////////////// *** All code *** ///////////////////////////////////
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AssociationForm.aspx.cs"
Inherits="MSTechSharing_TaskFormASPX.Layouts.MSTechSharing_TaskFormASPX.AssociationForm"
MasterPageFile="~masterurl/default.master" %>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div>
    AssociationForm
</div>
<table cellpadding="0" cellspacing="0" border="1"  >
    <tr>
        <td>
            UserTest
            <br/>
            <i><%=User1 %></i>
        </td>
        <td>
          
            <SharePoint:PeopleEditor ID="UserTest" runat="server" />
        </td>
    </tr>
</table>
    <asp:Button ID="AssociateWorkflow" runat="server" OnClick="AssociateWorkflow_Click" Text="Save" />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <asp:Button ID="Cancel" runat="server" Text="Cancel" OnClick="Cancel_Click" />
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    AssociationForm
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea">
    AssociationForm
</asp:Content>

/////////////////////////////////// *** End All code *** ///////////////////////////////////
Using and change class inherit from LayoutsPageBase -> WebPartPage
using System;
using System.Globalization;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WebPartPages;

Declare variable as follows:


private const int CreateListTryCount = 100;
        private string historyListDescription = "Custom History List";
        private string taskListDescription = "Custom Task List";
        private string listCreationFailed = "Failed to create list {0} as a list with same name already exists";
        private string workflowAssociationFailed = "Error occured while associating Workflow template. {0}";

        public string User1;
        SPWeb Web = SPContext.Current.Web;

Paste code to Page_Load method
Paste code below Page_Load method (image 10)


////////////////////////////////// *** All code *** //////////////////////////////////
using System;
using System.Globalization;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WebPartPages;

namespace MSTechSharing_TaskFormASPX.Layouts.MSTechSharing_TaskFormASPX
{
    public partial class AssociationForm : WebPartPage
    {
        private const int CreateListTryCount = 100;
        private string historyListDescription = "Custom History List";
        private string taskListDescription = "Custom Task List";
        private string listCreationFailed = "Failed to create list {0} as a list with same name already exists";
        private string workflowAssociationFailed = "Error occured while associating Workflow template. {0}";

        public string User1;
        SPWeb Web = SPContext.Current.Web;

        protected void Page_Load(object sender, EventArgs e)
        {
            InitializeParams();
            try
            {
                if (!string.IsNullOrEmpty(this.GetExistingAssociation().AssociationData))
                {
                    string[] input = this.GetExistingAssociation().AssociationData.Split('@');
                    if (input.Length >= 1)
                    {
                        User1 = input[0];
                    }
                }
            }
            catch
            {
            }
        }

        private void PopulateFormFields(SPWorkflowAssociation existingAssociation)
        {
            // Optionally, add code here to pre-populate your form fields.
        }

        // This method is called when the user clicks the button to associate the workflow.
        private string GetAssociationData()
        {
            //gets first user in list
            string usernameTest = UserTest.CommaSeparatedAccounts;  
            #region Grant read permission for users in current web
            try
            {
                SPWeb objWeb = SPContext.Current.Web;
                if (!string.IsNullOrEmpty(usernameTest))
                {
                    objWeb.EnsureUser(usernameTest);
                }
                objWeb.Update();
            }
            catch (Exception)
            {
                // Nothing
            }
            #endregion
            return usernameTest + "@";//If have many user, plus @ to separate user
        }

        protected void AssociateWorkflow_Click(object sender, EventArgs e)
        {
            // Optionally, add code here to perform additional steps before associating your workflow
            try
            {
                CreateTaskList();
                CreateHistoryList();
                HandleAssociateWorkflow();
                SPUtility.Redirect("WrkSetng.aspx", SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current, Page.ClientQueryString);
            }
            catch (Exception ex)
            {
                SPUtility.TransferToErrorPage(String.Format(CultureInfo.CurrentCulture, workflowAssociationFailed, ex.Message));
            }
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            SPUtility.Redirect("WrkSetng.aspx", SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current, Page.ClientQueryString);
        }

        #region Workflow Association Code - Typically, the following code should not be changed

        private AssociationParams associationParams;

        [Serializable]
        private enum WorkflowAssociationType
        {
            ListAssociation,
            WebAssociation,
            ListContentTypeAssociation,
            SiteContentTypeAssociation
        }

        [Serializable]
        private struct AssociationParams
        {
            public string AssociationName;
            public string BaseTemplate;
            public bool AutoStartCreate;
            public bool AutoStartChange;
            public bool AllowManual;
            public bool RequireManagedListPermisions;
            public bool SetDefaultApprovalWorkflow;
            public bool LockItem;
            public Guid AssociationGuid;
            public WorkflowAssociationType AssociationType;
            public Guid TargetListGuid;
            public Guid TaskListGuid;
            public string TaskListName;
            public Guid HistoryListGuid;
            public string HistoryListName;
            public SPContentTypeId ContentTypeId;
            public bool ContentTypePushDown;
        }

        private void InitializeParams()
        {
            // Check if the page is loaded for first time
            if (ViewState["associationParams"] == null)
            {
                InitializeAssociationParams();
                ViewState["associationParams"] = this.associationParams;
                SPWorkflowAssociation existingAssociation = GetExistingAssociation();
                PopulateFormFields(existingAssociation);
            }
            else
            {
                this.associationParams = (AssociationParams)ViewState["associationParams"];
            }
        }

        private void InitializeAssociationParams()
        {
            this.associationParams = new AssociationParams();
            this.associationParams.AssociationName = Request.Params["WorkflowName"];
            this.associationParams.BaseTemplate = Request.Params["WorkflowDefinition"];
            this.associationParams.AutoStartCreate = (StringComparer.OrdinalIgnoreCase.Compare(Request.Params["AutoStartCreate"], "ON") == 0);
            this.associationParams.AutoStartChange = (StringComparer.OrdinalIgnoreCase.Compare(Request.Params["AutoStartChange"], "ON") == 0);
            this.associationParams.AllowManual = (StringComparer.OrdinalIgnoreCase.Compare(Request.Params["AllowManual"], "ON") == 0);
            this.associationParams.RequireManagedListPermisions = (StringComparer.OrdinalIgnoreCase.Compare(Request.Params["ManualPermManageListRequired"], "ON") == 0);
            this.associationParams.SetDefaultApprovalWorkflow = (StringComparer.OrdinalIgnoreCase.Compare(Request.Params["SetDefault"], "ON") == 0);
            this.associationParams.LockItem = (StringComparer.OrdinalIgnoreCase.Compare(Request.Params["AllowEdits"], "FALSE") == 0);
            this.associationParams.ContentTypePushDown = (StringComparer.OrdinalIgnoreCase.Compare(Request.Params["UpdateLists"], "TRUE") == 0);

            string associationGuid = Request.Params["GuidAssoc"];
            if (!String.IsNullOrEmpty(associationGuid))
            {
                this.associationParams.AssociationGuid = new Guid(associationGuid);
            }

            InitializeAssociationTypeParams();
            InitializeTaskListParams();
            InitializeHistoryListParams();
        }

        private void InitializeAssociationTypeParams()
        {
            string listGuid = Request.QueryString["List"];
            string contentTypeId = Request.QueryString["ctype"];

            if (!String.IsNullOrEmpty(contentTypeId))
            {
                if (!String.IsNullOrEmpty(listGuid))
                {
                    this.associationParams.AssociationType = WorkflowAssociationType.ListContentTypeAssociation;
                    this.associationParams.TargetListGuid = new Guid(listGuid);
                }
                else
                {
                    this.associationParams.AssociationType = WorkflowAssociationType.SiteContentTypeAssociation;
                }
                this.associationParams.ContentTypeId = new SPContentTypeId(contentTypeId);
            }
            else
            {
                if (!String.IsNullOrEmpty(listGuid))
                {
                    this.associationParams.AssociationType = WorkflowAssociationType.ListAssociation;
                    this.associationParams.TargetListGuid = new Guid(listGuid);
                }
                else
                {
                    this.associationParams.AssociationType = WorkflowAssociationType.WebAssociation;
                }
            }
        }

        private void InitializeTaskListParams()
        {
            string taskListParam = Request.Params["TaskList"];

            if (this.associationParams.AssociationType == WorkflowAssociationType.SiteContentTypeAssociation)
            {
                this.associationParams.TaskListName = taskListParam;
            }
            else
            {

                if (taskListParam.StartsWith("z"))
                {
                    // Create a new list if the value starts with 'z'
                    this.associationParams.TaskListName = taskListParam.Substring(1);
                }
                else
                {
                    // Use existing list
                    this.associationParams.TaskListGuid = new Guid(taskListParam);
                }
            }
        }

        private void InitializeHistoryListParams()
        {
            string historyListParam = Request.Params["HistoryList"];

            if (this.associationParams.AssociationType == WorkflowAssociationType.SiteContentTypeAssociation)
            {
                this.associationParams.HistoryListName = historyListParam;
            }
            else
            {
                if (historyListParam.StartsWith("z"))
                {
                    // Create a new list if the value starts with 'z'
                    this.associationParams.HistoryListName = historyListParam.Substring(1);
                }
                else
                {
                    // Use existing list
                    this.associationParams.HistoryListGuid = new Guid(historyListParam);
                }
            }
        }

        private SPWorkflowAssociation GetExistingAssociation()
        {
            if (this.associationParams.AssociationGuid != Guid.Empty)
            {
                SPWorkflowAssociationCollection workflowAssociationCollection;
                switch (this.associationParams.AssociationType)
                {
                    case WorkflowAssociationType.ListAssociation:
                        workflowAssociationCollection = Web.Lists[this.associationParams.TargetListGuid].WorkflowAssociations;
                        break;
                    case WorkflowAssociationType.ListContentTypeAssociation:
                        workflowAssociationCollection = Web.Lists[this.associationParams.TargetListGuid].ContentTypes[this.associationParams.ContentTypeId].WorkflowAssociations;
                        break;
                    case WorkflowAssociationType.SiteContentTypeAssociation:
                        workflowAssociationCollection = Web.ContentTypes[this.associationParams.ContentTypeId].WorkflowAssociations;
                        break;
                    default:
                        workflowAssociationCollection = Web.WorkflowAssociations;
                        break;
                }
                return workflowAssociationCollection[this.associationParams.AssociationGuid];
            }
            return null;
        }

        private void CreateTaskList()
        {
            if (this.associationParams.TaskListGuid == Guid.Empty && this.associationParams.AssociationType != WorkflowAssociationType.SiteContentTypeAssociation)
            {
                this.associationParams.TaskListGuid = CreateList(this.associationParams.TaskListName, taskListDescription, SPListTemplateType.Tasks);
            }
        }

        private void CreateHistoryList()
        {
            if (this.associationParams.HistoryListGuid == Guid.Empty && this.associationParams.AssociationType != WorkflowAssociationType.SiteContentTypeAssociation)
            {
                this.associationParams.HistoryListGuid = CreateList(this.associationParams.HistoryListName, historyListDescription, SPListTemplateType.WorkflowHistory);
            }
        }

        private Guid CreateList(string name, string description, SPListTemplateType type)
        {
            string listName = name;
            for (int i = 0; i <= CreateListTryCount; i++)
            {
                if (Web.Lists.TryGetList(listName) == null)
                {
                    return Web.Lists.Add(listName, description, type);
                }
                listName = String.Concat(name, i.ToString(CultureInfo.InvariantCulture));
            }
            throw new Exception(String.Format(CultureInfo.CurrentCulture, listCreationFailed, name));
        }

        private void HandleAssociateWorkflow()
        {
            switch (this.associationParams.AssociationType)
            {
                case WorkflowAssociationType.ListAssociation:
                    AssociateListWorkflow();
                    break;
                case WorkflowAssociationType.WebAssociation:
                    AssociateSiteWorkflow();
                    break;
                case WorkflowAssociationType.ListContentTypeAssociation:
                    AssociateListContentTypeWorkflow();
                    break;
                case WorkflowAssociationType.SiteContentTypeAssociation:
                    AssociateSiteContentTypeWorkflow();
                    break;
            }
        }

        private void AssociateSiteContentTypeWorkflow()
        {
            SPContentType contentType = Web.ContentTypes[this.associationParams.ContentTypeId];
            SPWorkflowAssociation association;
            if (this.associationParams.AssociationGuid == Guid.Empty)
            {
                association = SPWorkflowAssociation.CreateWebContentTypeAssociation(
                                                  Web.WorkflowTemplates[new Guid(this.associationParams.BaseTemplate)],
                                                  this.associationParams.AssociationName,
                                                  this.associationParams.TaskListName,
                                                  this.associationParams.HistoryListName);
                PopulateAssociationParams(association);
                contentType.WorkflowAssociations.Add(association);
            }
            else
            {
                association = contentType.WorkflowAssociations[this.associationParams.AssociationGuid];
                association.TaskListTitle = this.associationParams.TaskListName;
                association.HistoryListTitle = this.associationParams.HistoryListName;
                PopulateAssociationParams(association);
                contentType.WorkflowAssociations.Update(association);
            }

            if (this.associationParams.ContentTypePushDown)
            {
                contentType.UpdateWorkflowAssociationsOnChildren(false);
            }
        }

        private void AssociateListContentTypeWorkflow()
        {
            SPContentType contentType = Web.Lists[associationParams.TargetListGuid].ContentTypes[associationParams.ContentTypeId];
            SPWorkflowAssociation association;
            if (associationParams.AssociationGuid == Guid.Empty)
            {
                association = SPWorkflowAssociation.CreateListContentTypeAssociation(
                                                  Web.WorkflowTemplates[new Guid(this.associationParams.BaseTemplate)],
                                                  this.associationParams.AssociationName,
                                                  Web.Lists[this.associationParams.TaskListGuid],
                                                  Web.Lists[this.associationParams.HistoryListGuid]);
                PopulateAssociationParams(association);
                contentType.WorkflowAssociations.Add(association);
            }
            else
            {
                association = contentType.WorkflowAssociations[this.associationParams.AssociationGuid];
                association.SetTaskList(Web.Lists[this.associationParams.TaskListGuid]);
                association.SetHistoryList(Web.Lists[this.associationParams.HistoryListGuid]);
                PopulateAssociationParams(association);
                contentType.WorkflowAssociations.Update(association);
            }

            if (this.associationParams.ContentTypePushDown)
            {
                contentType.UpdateWorkflowAssociationsOnChildren(false);
            }
        }

        private void AssociateListWorkflow()
        {
            SPList targetList = Web.Lists[this.associationParams.TargetListGuid];
            SPWorkflowAssociation association;
            if (associationParams.AssociationGuid == Guid.Empty)
            {
                association = SPWorkflowAssociation.CreateListAssociation(
                                                  Web.WorkflowTemplates[new Guid(this.associationParams.BaseTemplate)],
                                                  this.associationParams.AssociationName,
                                                  Web.Lists[this.associationParams.TaskListGuid],
                                                  Web.Lists[this.associationParams.HistoryListGuid]);
                PopulateAssociationParams(association);
                targetList.WorkflowAssociations.Add(association);
            }
            else
            {
                association = targetList.WorkflowAssociations[this.associationParams.AssociationGuid];
                association.SetTaskList(Web.Lists[this.associationParams.TaskListGuid]);
                association.SetHistoryList(Web.Lists[this.associationParams.HistoryListGuid]);
                PopulateAssociationParams(association);
                targetList.WorkflowAssociations.Update(association);
            }

            SetDefaultContentApprovalWorkflow(targetList, association);
        }

        private void SetDefaultContentApprovalWorkflow(SPList targetList, SPWorkflowAssociation association)
        {
            if (targetList.EnableMinorVersions)
            {
                if (targetList.DefaultContentApprovalWorkflowId != association.Id && this.associationParams.SetDefaultApprovalWorkflow)
                {
                    if (!targetList.EnableModeration)
                    {
                        targetList.EnableModeration = true;
                        targetList.DraftVersionVisibility = DraftVisibilityType.Approver;
                    }
                    targetList.DefaultContentApprovalWorkflowId = association.Id;
                    targetList.Update();
                }
                else if (targetList.DefaultContentApprovalWorkflowId == association.Id && !this.associationParams.SetDefaultApprovalWorkflow)
                {
                    targetList.DefaultContentApprovalWorkflowId = Guid.Empty;
                    targetList.Update();
                }
            }
        }

        private void AssociateSiteWorkflow()
        {
            if (this.associationParams.AssociationGuid == Guid.Empty)
            {
                SPWorkflowAssociation association = SPWorkflowAssociation.CreateWebAssociation(
                                                  Web.WorkflowTemplates[new Guid(this.associationParams.BaseTemplate)],
                                                  this.associationParams.AssociationName,
                                                  Web.Lists[this.associationParams.TaskListGuid],
                                                  Web.Lists[this.associationParams.HistoryListGuid]);
                PopulateAssociationParams(association);
                Web.WorkflowAssociations.Add(association);
            }
            else
            {
                SPWorkflowAssociation association = Web.WorkflowAssociations[this.associationParams.AssociationGuid];
                association.SetTaskList(Web.Lists[this.associationParams.TaskListGuid]);
                association.SetHistoryList(Web.Lists[this.associationParams.HistoryListGuid]);
                PopulateAssociationParams(association);
                Web.WorkflowAssociations.Update(association);
            }
        }

        private void PopulateAssociationParams(SPWorkflowAssociation association)
        {
            association.Name = this.associationParams.AssociationName;
            association.AutoStartCreate = this.associationParams.AutoStartCreate;
            association.AutoStartChange = this.associationParams.AutoStartChange;
            association.AllowManual = this.associationParams.AllowManual;
            association.LockItem = this.associationParams.LockItem;
            association.ContentTypePushDown = this.associationParams.ContentTypePushDown;

            if (association.AllowManual)
            {
                association.PermissionsManual = SPBasePermissions.EmptyMask;
                if (this.associationParams.RequireManagedListPermisions)
                {
                    association.PermissionsManual |= (this.associationParams.TargetListGuid != Guid.Empty) ? SPBasePermissions.ManageLists : SPBasePermissions.ManageWeb;
                }
            }
            association.AssociationData = GetAssociationData();
        }
        #endregion
    }
}

////////////////////////////////// ***  End All code *** //////////////////////////////////

Edit code workflow

Edit approver
Paste code to createTaskWithContentType1_MethodInvoking method
string[] arrayUser = onWorkflowActivated1.WorkflowProperties.AssociationData.Split('@');
            string userApproved = arrayUser[0];

Change Approver

private void createTaskWithContentType1_MethodInvoking(object sender, EventArgs e)
        {
            string[] arrayUser = onWorkflowActivated1.WorkflowProperties.AssociationData.Split('@');
            string userApproved = arrayUser[0];
            createTaskWithContentType1_TaskId1 = Guid.NewGuid();
            createTaskWithContentType1_ContentTypeId1 = "0x0108010059177a2760644cd3b054dd3f929e0380";
            createTaskWithContentType1_TaskProperties1.AssignedTo = userApproved;
            createTaskWithContentType1_TaskProperties1.Title = "Custom From ASPX Task List ";
        }

Open file Element.xml of workflow: plus properties AssociationUrl=”path to form AssociationForm.aspx (copy that path in file Element.xml of module Form)”

Demo application

Deploy project | Open sharepoint site | choose workflow setting
Choose workflow content type
Click to workflow name
Click next
Type approver name then click Save
Create new item
Click to In Progress

Approver was assigned then edit item

Click OK to approve
After approved status of workflow is completed
Item is completed

0 comments:

Post a Comment