Monday, 20 August 2012

CREATE WORKFLOW WITH CUSTOM TASK FORM (ASPX PAGE) IN SHAREPOINT 2010


Article purpose:

When create new a requirement => will appear a register form (ASPX Form), after register successful, workflow auto run and send Task for any people, and that requirement when people receive it will open Task to Approve on form (ASPX Form)

Steps implement

CREATE NEW CONTENT TYPE FOR LIST TARGET

CREATE NEW LIST DEFINITION FOR LIST TARGET

CREATE NEW MODULE

CREATE NEW CUSTOM ASPX FORM (APPLICATION PAGE) FOR LIST TARGET

CREATE NEW CONTENT TYPE FOR LIST TASK

TẠO CUSTOM ASPX FORM (APPLICATION PAGE) FOR LIST TASK

CREATE NEW BASIC WORKFLOW

CREATE NEW EVENT RECEIVER TO ACTIVE WORKFLOW RUN WHEN ADD CONTENT TYPE ITEM


Implement

Open visual studio | New Project | Visual C# | Sharepoint | 2010 | Empty Sharepoint Project | name í MSTechSharing_TaskFormASPX

Choose “Deploy as a farm solution”

CREATE NEW CONTENT TYPE FOR LIST TARGET

Right click to project | New Item | Content type | name is MSTechSharing_TaskFormASPX_ContentTypeTargetList

Choose Content Type Item

Structure of Element.xml file content type as follows

CREATE NEW LIST DEFINITION FOR LIST TARGET

Right click to project | Add new item | List Definition From Content Type | Name is MSTechSharing_TaskFormASPX_ListDefinition_TargetList

Choose content type inherit from content type “MSTechSharing_TaskFormASPX_ContentTypeTargetList” had created above

Structure of List Definition as follows

change 100 number in Element.xml file of ListInstance1 if you want to your List is custom list

Must change 100 number in Element file of MSTechSharing_TaskFormASPX_ListDefinition_TargetList (image 10)

This is structure of Schema.xml in MSTechSharing_TaskFormASPX_ListDefinition_TargetList list

In tag <FieldRefs> </ FieldRefs> insert Fields as follows (option)


<!--Insert to here-->
          <FieldRef ID="FA564E0F-0C70-4AB9-B863-0177E6DDD247" Name="Title" Hidden="TRUE"  Required="FALSE"/>
          <FieldRef ID="{D37DE7CA-1296-47CF-91EB-2C8D09D94C00}" Name="Description" />         
           <!--End Insert to here-->

Insert the segment code to register form aspx when display you Add New Item


<!--Insert to here-->
        <XmlDocuments>
          <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
            <FormTemplates xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms">
              <Display>ListForm</Display>
              <Edit>ListForm</Edit>
              <New>ListForm</New>
            </FormTemplates>
          </XmlDocument>
          <XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url">
            <FormUrls xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url" >
              <New>Form/TargetList_AddNew.aspx</New>
            </FormUrls>
          </XmlDocument>
        </XmlDocuments>
        <!--End Insert to here-->
In tag  <Fields> </Fields> insert segment code as follows


<!--Insert to here-->
     
      <Field Type="Text" ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" ReadOnly="TRUE" Required="FALSE"Hidden="TRUE"
           SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Title"></Field>
      <Field ID="{d37de7ca-1296-47cf-91eb-2c8d09d94c00}" Type="Text" Name="Description" DisplayName="Description" />
     
      <!--End Insert to here-->

TẠO MỚI MODULE

Right click to Project | Add new Item | Module | name is Form then delete file Sample.txt

CREATE NEW CUSTOM ASPX FORM (APPLICATION PAGE) FOR LIST TARGET

Right click to Project | Add new Item | Application Page | name is TargetList_AddNew.aspx

Application Page structure as follows

Change DynamicMasterPageFile to MasterPageFile by delete Dynamic character


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TargetList_AddNew.aspx.cs"
Inherits="MSTechSharing_TaskFormASPX.Layouts.MSTechSharing_TaskFormASPX.TargetList_AddNew"PageFile="~masterurl/default.master" %>

Copy segment code into PlaceHolderMain (image 20)


<table style="width: 900px;">
        <tr>
            <td class="column1">
                Họ và tên
            </td>
            <td class="column2">
                <asp:TextBox ID="TextBox_HoTen" runat="server" Width="309px"></asp:TextBox>
            </td>
        </tr>
    </table>

Copy Target list to PlaceHolderAdditionalPageHead, PlaceHolderPageTitle, PlaceHolderPageTitleInTitleArea

Using and change class inherit from LayoutsPageBase to WebPartPage as follows:

using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;

Copy code Button_Submit_Click, Button_Cancel_Click, CloseForm below Page_Load method
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;

namespace MSTechSharing_TaskFormASPX.Layouts.MSTechSharing_TaskFormASPX
{
    public partial class TargetList_AddNew : WebPartPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void Button_Submit_Click(object sender, EventArgs e)
        {
            SPList spList = SPContext.Current.List;
            SPListItem spListItem = spList.Items.Add();
            spListItem["Title"] = txtDescription.Text + "";
     spListItem["Description"] = txtDescription.Text + "";
            spListItem.Update();
            spList.Update();
            CloseForm();
        }

        protected void Button_Cancel_Click(object sender, EventArgs e)
        {
            CloseForm();
        }

        private void CloseForm()
        {
            if ((SPContext.Current != null) && SPContext.Current.IsPopUI)
            {
                this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                this.Context.Response.Flush();
                this.Context.Response.End();
            }
            else
            {
                string str = this.Page.Request.QueryString["Source"];
                if ((str != null) && (str.Length > 0))
                {
                    SPUtility.Redirect(string.Empty, SPRedirectFlags.UseSource, this.Context);
                }
            }
        }
    }
}

Cut TargetList_AddNew.aspx into Form Module

You see the path auto insert to file Element.xml of Form module

Deploy Project create new Item content type as follows

Result as follows:

CREATE NEW CONTENT TYPE FOR LIST TASK

Right click to project | Add new item | Content type | MSTechSharing_TaskFormASPX_ContentTypeTask
Choose Task Content Type
You see default number string of content type Task is 0x010800 you must change to 0x01080100

After change number then delete Inherits= “True” properties (image 30)

After number string was changed and Inherits= “True” properties was deleted, result as follows

Below close tag </FieldRefs> insert code to know path of Form Display and Edit of Task form

CREATE NEW CUSTOM ASPX FORM (APPLICATION PAGE) FOR LIST TASK

Right click to project | New Item | Application Page | Name is CustomFormTaskList.aspx

Change DynamicMasterPageFile to MasterPageFile by delete Dynamic character

Copy code into PlaceHolderMain


<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<!--Insert code to here-->
    <table style="width: 500px;" class="lcttable">
        <tr>
            <td>
                Description
            </td>
            <td>
                <%=Description%>
            </td>
        </tr>
        <tr>
            <td>           
            </td>
            <td>
                <asp:Button ID="Button_Ok" runat="server" Text="OK" Width="100px" OnClick="Button_Ok_Click" />
                <asp:Button ID="Button_Cancel" runat="server" Text="Cancel" Width="100px" OnClick="Button_Cancel_Click" />
            </td>
        </tr>
    </table>
    <!--End Insert code to here-->
</asp:Content>

Copy Custom Form Task List to PlaceHolderAdditionalPageHead, PlaceHolderPageTitle, PlaceHolderPageTitleInTitleArea


<%@ 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="CustomFormTaskList.aspx.cs"
    Inherits="MSTechSharing_TaskFormASPX.Layouts.MSTechSharing_TaskFormASPX.CustomFormTaskList"
    MasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    Custom Form Task List
</asp:Content>
<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<!--Insert code to here-->
    <table style="width: 500px;" class="lcttable">
        <tr>
            <td>
                Description
            </td>
            <td>
                <%=Description%>
            </td>
        </tr>
        <tr>
            <td>           
            </td>
            <td>
                <asp:Button ID="Button_Ok" runat="server" Text="OK" Width="100px" OnClick="Button_Ok_Click" />
                <asp:Button ID="Button_Cancel" runat="server" Text="Cancel" Width="100px" OnClick="Button_Cancel_Click" />
            </td>
        </tr>
    </table>
    <!--End Insert code to here-->
</asp:Content>
<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
    Custom Form Task List
</asp:Content>
<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server"> 
   Custom Form Task List
</asp:Content>

Using and change class inherit from LayoutsPageBase -> WebPartPage

Copy code as follows

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;

namespace MSTechSharing_TaskFormASPX.Layouts.MSTechSharing_TaskFormASPX
{
    public partial class CustomFormTaskList : WebPartPage
    {
        public string Description;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SPListItem spListItem = SPContext.Current.ListItem;
                string urlLink = spListItem["WorkflowLink"].ToString().Split(',')[0];
                int idItem = Convert.ToInt32(urlLink.Split('=')[1]);
                SPSite ObjSite;
                SPWeb ObjWeb;
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (ObjSite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (ObjWeb = ObjSite.RootWeb)
                        {
                            SPList objList = ObjWeb.GetListFromUrl(urlLink);
                            SPListItem target = objList.GetItemById(idItem);
                            Description = target["Description"] + "";
                            string action = Page.Request.QueryString["action"] + "";
                            if (action == "display")
                            {
                                Button_Cancel.Visible = false;
                                Button_Ok.Visible = false;
                            }                           
                        }
                    }
                });
            }
            catch
            {
                // Nothing
            }
        }

        protected void Button_Ok_Click(object sender, EventArgs e)
        {
            try
            {
                SPListItem spListItem = SPContext.Current.ListItem;
                if (spListItem.ParentList.ContentTypes[SPBuiltInContentTypeId.SummaryTask] != null)
                {
                    spListItem.ParentList.ContentTypes.Delete(SPBuiltInContentTypeId.SummaryTask);
                }
                if (spListItem.ParentList.ContentTypes[SPBuiltInContentTypeId.Task] != null)
                {
                    spListItem.ParentList.ContentTypes.Delete(SPBuiltInContentTypeId.Task);
                }
                spListItem["PercentComplete"] = 1F;
                spListItem.Update();

                CloseForm();
            }
            catch
            {
                // Nothing
            }
        }

        protected void Button_Cancel_Click(object sender, EventArgs e)
        {
            SPListItem spListItem = SPContext.Current.ListItem;
            spListItem["PercentComplete"] = 0;
            spListItem.Update();
            CloseForm();
        }

        private void CloseForm()
        {
            if ((SPContext.Current != null) && SPContext.Current.IsPopUI)
            {
                this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                this.Context.Response.Flush();
                this.Context.Response.End();
            }
            else
            {
                string str = this.Page.Request.QueryString["Source"];
                if ((str != null) && (str.Length > 0))
                {
                    SPUtility.Redirect(string.Empty, SPRedirectFlags.UseSource, this.Context);
                }
            }
        }
    }
}

Cut CustomFormTaskList.aspx from Layouts Folder to Form module

CREATE NEW BASIC WORKFLOW

Right to Project | Add New Item | Sequential Workflow | Name is MSTechSharing_TaskFormASPX_Workflow

Choose List Workflow (image 40)

Uncheck as below image

Design workflow as follow

Configurate properties for createTaskWithContentType1 (reference how to create workflow sequential at here part How to create workflow approval)

Configure properties for onTaskChanged1

Configure properties for logToHistoryListActivity1

Double click to createTaskWithContentType1

Paste code to createTaskWithContentType1_MethodInvoking (note: ID content type of list task is same)

private void createTaskWithContentType1_MethodInvoking(object sender, EventArgs e)
        {
            createTaskWithContentType1_TaskId1 = Guid.NewGuid();
            createTaskWithContentType1_ContentTypeId1 = "0x0108010059177a2760644cd3b054dd3f929e0380";
            createTaskWithContentType1_TaskProperties1.AssignedTo = "win-67038mbkel7\\administrator";
            createTaskWithContentType1_TaskProperties1.Title = "Custom From ASPX Task List ";
        }

Double click to onTaskChanged1

paste code to onTaskChanged1_Invoked

private void onTaskChanged1_Invoked(object sender, ExternalDataEventArgs e)
        {
            onTaskChanged1_AfterProperties1.PercentComplete = 1F;
        }

//All Code
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;

namespace BasicWFASPXTaskForm.BasicWFASPXTaskForm_Workflow
{
    public sealed partial class BasicWFASPXTaskForm_Workflow : SequentialWorkflowActivity
    {
        public BasicWFASPXTaskForm_Workflow()
        {
            InitializeComponent();
        }

        public Guid workflowId = default(System.Guid);
        public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();
        public Guid createTaskWithContentType1_TaskId1 = default(System.Guid);
        public SPWorkflowTaskProperties createTaskWithContentType1_TaskProperties1 = newMicrosoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public String createTaskWithContentType1_ContentTypeId1 = default(System.String);
        public SPWorkflowTaskProperties onTaskChanged1_AfterProperties1 = newMicrosoft.SharePoint.Workflow.SPWorkflowTaskProperties();
        public SPWorkflowTaskProperties onTaskChanged1_BeforeProperties1 = newMicrosoft.SharePoint.Workflow.SPWorkflowTaskProperties();

        private void createTaskWithContentType1_MethodInvoking(object sender, EventArgs e)
        {
            createTaskWithContentType1_TaskId1 = Guid.NewGuid();
            createTaskWithContentType1_ContentTypeId1 = "0x01080100349325c1e86c4e8c992a9a1c041fbcd1";
            createTaskWithContentType1_TaskProperties1.AssignedTo = "win-67038mbkel7\\administrator";
            createTaskWithContentType1_TaskProperties1.Title = "Custom ASPX From Task List";
        }

        private void onTaskChanged1_Invoked(object sender, ExternalDataEventArgs e)
        {
            onTaskChanged1_AfterProperties1.PercentComplete = 1F;
        }
    }
}
//////////////////////////////////// ***End  All Code  ***////////////////////////////////////

Open file Element.xml of Workflow and change as follow (image 50)

CREATE NEW EVENT RECEIVER TO CALL WORKFLOW RUN WHEN ADD CONTENT TYPE ITEM

delete Feature2 when workflow was created (no require)

Open Feature1 change scope from web to site

Move feature workflow to right

Right click to Feature1 | Add Event Receiver

Using : using Microsoft.SharePoint.Workflow; and declare 3 variable


private string _workflowName = "MSTechSharing_TaskFormASPX - MSTechSharing_TaskFormASPX_Workflow";
        private string _contentTypeName = "MSTechSharing_TaskFormASPX - MSTechSharing_TaskFormASPX_ContentTypeTargetList";
        private string nameWorkflowOnContentType = "Wf CustomASPXTaskForm";


////////////////////////////////////// *** All code *** //////////////////////////////////////
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Workflow;

namespace MSTechSharing_TaskFormASPX.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("c52f6eae-fc7e-47a5-89e1-3b2b0fa32c2b")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        private string _workflowName = "MSTechSharing_TaskFormASPX - MSTechSharing_TaskFormASPX_Workflow";
        private string _contentTypeName = "MSTechSharing_TaskFormASPX - MSTechSharing_TaskFormASPX_ContentTypeTargetList";
        private string nameWorkflowOnContentType = "Wf CustomASPXTaskForm";


        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

            using (SPSite site = ((SPSite)properties.Feature.Parent))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPContentType theCt = web.ContentTypes[_contentTypeName];

                    SPWorkflowTemplate theWf = null;
                    foreach (SPWorkflowTemplate tpl in web.WorkflowTemplates)
                    {
                        if (tpl.Name == _workflowName)
                        {
                            theWf = tpl;
                        }
                    }

                    SPWorkflowAssociation wfAssociation = theCt.WorkflowAssociations.GetAssociationByName(nameWorkflowOnContentType, web.Locale);

                    if (wfAssociation != null)
                    {
                        theCt.WorkflowAssociations.Remove(wfAssociation);
                    }
                    theCt.UpdateWorkflowAssociationsOnChildren(true, true, true, false);

                    // Name of workflow on ContentType that is associated to definition workflow

                    wfAssociation = SPWorkflowAssociation.CreateWebContentTypeAssociation(theWf, nameWorkflowOnContentType,"Task MSTechSharing_TaskFormASPX", "History MSTechSharing_TaskFormASPX");
                    wfAssociation.AutoStartCreate = true;
                    wfAssociation.AutoStartChange = true;

                    if (theCt.WorkflowAssociations.GetAssociationByName(wfAssociation.Name, web.Locale) == null)
                    {
                        theCt.WorkflowAssociations.Add(wfAssociation);
                    }
                    else
                    {
                        theCt.WorkflowAssociations.Update(wfAssociation);
                    }
                    theCt.UpdateWorkflowAssociationsOnChildren(true, true, true, false);

                }
            }

        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            using (SPSite site = ((SPSite)properties.Feature.Parent))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPContentType theCt = web.ContentTypes[_contentTypeName];

                    SPWorkflowAssociation wfAssociation = theCt.WorkflowAssociations.GetAssociationByName(_workflowName, web.Locale);
                    if (wfAssociation != null)
                    {
                        theCt.WorkflowAssociations.Remove(wfAssociation);
                    }
                    theCt.UpdateWorkflowAssociationsOnChildren(true, true, true, false);
                }
            }
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}

////////////////////////////////////// *** End All code *** //////////////////////////////////////
Deploy project, you see list definition was created as follows

Create new item

Workflow run automatically

Edit Item

Appear ASPX form in list Task

After approve (OK) status of workflow is completed

Note:

Error can not Add solution => change name of content type
Error can not Actived solution => change Name WF, Name content type in event receiver same with in xml file of workflow and content type target list
Error failing in started => insert ContentType;# to  <AssociationCategories>ContentType;#List</AssociationCategories>
Error can not display Form ASPX=> delete List contain that Form then deploy

REF:

Friday, 17 August 2012

Adding Custom control in SharePoint 2010


1.Search for session in web config file of u r vertual dir
Maek enableSessionState="true"
eg: <pages enableSessionState="true" enableViewState="true" enableViewStateMac="true" validateRequest="false" pageParserFilterType="Microsoft.SharePoint.ApplicationRuntime.SPPageParserFilter, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" asyncTimeout="7">

2. Make following line commented
<!--<remove name="Session" />-->

3. Make trust level full in bellow of  </siteMap> tag
    <trust level="Full" originUrl="" />
4. Put your custom control dlls into SharePoint vertual directory bin folder

Thursday, 16 August 2012

Using the AJAX Control Toolkit with SharePoint 2010


The AJAX Control Toolkit offers so much useful functionality, however for some reason Microsoft refuses to integrate it as part of their product. This has caused problems with SharePoint 2003 – 2010, however as SharePoint now has standard Ajax integration we are now faced with another problem.

With previous versions of SharePoint you would need to add the AJAX references to the Web.config file as well as register the AJAX assemblies. In addition you would need to do the same for the AJAX Control Toolkit as well as incorporating a script manager into your master pages.Well with SharePoint 2010, the AJAX stuff is already there, but the script managers do not work with the AJAX Control Toolkit. Here is how I finally managed to get this working:

Registering the AJAX Control Toolkit

First you need to download the AJAX Control Toolkit binaries. After some headaches I found out that the latest release does not work with SharePoint 2010. You get a bunch of ‘sys’ errors after implementation. You will therefore need to download the 30930 version which can be foundhere.
Copy the “AjaxControlToolkit.dll” file into the “<Drive>\inetpub\wwwroot\wss\VirtualDirectories\80\bin” SharePoint directory (obviously if you didn’t use port 80, the path would have a different port number).
Open up your Web.config file and find the <assemblies> section add the following entry (notice that the version includes *.28736, this took me a while to figure out):
<add assembly=”AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e” />
Also add the following entry in the Web.config file in the <SafeControls> section:
<SafeControl Assembly=”ajaxcontroltoolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e, processorArchitecture=MSIL”Namespace=”AjaxControlToolkit” TypeName=”*” />

Adding the AJAX Control Toolkit to Visual Studio 2010

Open up VSTO and start a new Web Part project. When you have the project open, add a new reference to the project by browsing to the “AjaxControlToolkit.dll” file in the “<Drive>\inetpub\wwwroot\wss\VirtualDirectories\80\bin”  directory.
Once you have this added to your project, go ahead and add the following line to your user control:
<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”asp”%>
Now, add a new Tab to your Toolbox, then right click and ‘choose items’. Browse to the “AjaxControlToolkit.dll” file in the “<Drive>\inetpub\wwwroot\wss\VirtualDirectories\80\bin”  directory and add the controls. You should see the following results:

WAIT! There’s more

OK, you have everything in place and you start to build a Web Part with the AJAX Toolkit Controls and find that the control is being rendered, but it is not functioning. You get a Javascript error pointing to your AJAX files being out of date. This is because SharePoint 2010 now has a ScriptManager added to every Master Page by default. You need to open up the Master Page you’re using (typically with SharePoint Designer) and remove the existing<asp:ScriptManager> tag and replace it with the following:
<asp:ToolkitScriptManager ID=”ToolkitScriptManager1″ runat=”server” />
as well as adding the following assembly reference:
<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”asp”%>
Woohoo. You now have the Toolkit fully functional in SharePoint 2010. Hope this helps you save some of the headaches I went through.

Wednesday, 8 August 2012

Workflow task form


As mentioned in part 1 of the tutorial, we can use custom task forms instead of the default task forms provided by SharePoint. Default forms have fixed number of fields which cannot be altered. Using custom forms, we can gather the required information from the user and they also make the process more dynamic and flexible.
In this part of the tutorial, we will see how to use InfoPath 2010 to design custom workflow task forms. InfoPath provides a richer interaction experience in which the user can interact with the workflow.
To handle the custom task forms in InfoPath, SharePoint 2010 links the hyperlink that displays a workflow form to an ASPX page that contains an Office Forms Services Web Part. The logic to handle the forms is written in this Web Part. This Web Part is configured such that it can receive as well as submit data. So, if we want to show some information on the InfoPath form, from a SharePoint List (or library) we create a Receive data connection in the InfoPath form. Similarly, to copy data from the InfoPath form to the SharePoint List (or library), we create a Submit data connection.
We specify the custom forms we want to use in the workflow template definition (i.e., Elements.xml) rather than the workflow itself. This involves setting two elements: the form URL and the URN of the custom InfoPath 2010 form. The form URL needs to be associated with a proper workflow process, e.g., association, initiation, modification, etc. This linking is important so that the appropriate ASPX hosting page is included in SharePoint. Next, you add an element specifying the URN for the custom InfoPath 2010 form for that type of workflow process.
Before we proceed any further, we will add a few more columns to the SharePoint List. The updated list has the following columns:
  1. Title
  2. Technology
  3. TotalExperience
  4. CandidateStatus
  5. InitialRemarks
  6. TechnicalInterviewRemarks
  7. HRRemarks
  8. InitialClearanceBy
  9. InitialClearanceOn
  10. TechnicalClearanceOn
  11. HRInterviewBy
  12. HRClearanceOn
  13. TechnicalInterviewAssignedTo

Design

Let us start by designing an InfoPath form for our first task, i.e., Initial Clearance.
Open Microsoft InfoPath Designer 2010; double-click on a blank form in the new tab. This opens a window with a blank form. For the Initial Clearance Task, we will give the user an option to approve or reject a candidate. If the user chooses to approve the candidate, then he/she will have to assign a Technical Interview Panel and an HR Interview Panel, else the user enters the comments for rejection and the workflow is terminated.
Design the table structure you want to use for your task form. You can use predefined structures available in Page Layouts of the Page Design tab. Click on the Show Fields button in the Data tab of the InfoPath Designer.
Drag-drop the controls on the form as required. At the bottom of the page, we will have a button control which will fire the Submit rule in InfoPath.
To add values to the Status dropdown list, right click on the Status dropdown list and select Drop-Down List Box Properties. Using Properties, you can add or modify the values as required. Rename the fields appropriately as we will be using these names in our code-behind file in Visual Studio.
We also have a Contact Selector on our InfoPath form. To configure the Contact Selector to use the user available in SharePoint, right click the control and go to Properties. In the SharePoint Server tab, enter the URL of the SharePoint site. This way the control will be able to pick up the users from SharePoint.
Fig 1.1
We will have to close the window after the user clicks on the Complete Task button. So, in Rules Explorer, click the Add button once again and select the “Close the form” option. You can preview the form and make changes accordingly. Refer to Fig. 1.1 for the completed InfoPath Form.

Implementation

Step 1

In Visual Studio 2010, open the Solution we created in the previous part. Right click on the workflow (RecruitmentWorkflow) folder and click Add -> New Item. Select module from the SharePoint 2010 node. We will name it Forms. Now right click the newly created module and add an existing item. Browse the InfoPath form we created and add that to the Forms module. If you observe the Elements.xml file inside the Forms module, Visual Studio has added a new node under the module corresponding to the newly added InfoPath form.
Fig 1.2
In the main feature manifest file (Feature1.Template.xml), refer Fig. 1.2, add the following nodes inside the property node, if they are missing.
<Property Key="GloballyAvailable" Value="true"/>
<Property Key="RegisterForms" Value="Forms\*.xsn"/>

Step 2

We need to configure the Elements.xml file of the workflow, add details like URN of the InfoPath Form, Association Data, etc. Before doing that, we need to change the InfoPath Form and publish our InfoPath Form.
To configure the settings, in File menu, select the Info tab. In the “Form Information” panel, select “Advanced form options”. In the “Security and Trust” tab, uncheck the “Automatically determine security level” checkbox and select the “Domain” radio button. Click OK and close the form.
To publish the InfoPath Form, in the File menu, in the Publish tab, click on the “Network Location” button. Browse the path on the file system, and click the Next button. In the next window of the wizard, clear the textbox (very important as SharePoint does not recognize the form as published if this textbox is not empty, hence it will not render the form). This will pop-up an alert message; click OK and continue. Complete the publishing process by clicking the “Publish” button.
To find the URN of the InfoPath Form, go to the File menu of the published InfoPath Form (make sure it is the published InfoPath Form), on the right hand side panel, click the “Form Template Properties” button. It opens up a pop-up window, the ID field in this window is the URN of the InfoPath Form.
In the Elements.xml file, we need to set TaskListContentTypeId to the following:
TaskListContentTypeId="0x01080100C9C9515DE4E24001905074F980F93160"
This content type, included in Microsoft SharePoint Server 2010, specifies the custom task display and edits the forms that include an Office Forms Server control for rendering the InfoPath Forms.
Next, add an element to the Metadata element of the workflow template definition. This element is in the form of<TaskN_FormURN>URN Value</TaskN_FormURN>, where N represents the integer value we assign to that task type within the workflow, and URN Value is the URN string we get from the InfoPath Form.
In addition to this, we also need to add the Association Data to our elements file. We will pass the dummy data to the workflow as we do not have any data to be passed to the workflow during association. Add the below code after the Categories node in Elements.xml. Refer Fig. 1.3 for Elements.xml after configuration.
<AssociationData>
              <Data></Data>
</AssociationData>
Fig 1.3

Step 3

If you are well versed with InfoPath 2010, you can create views in the same form for the various tasks that we have in our workflow. Alternatively, you can create a new form for each task and add it to the solution in a similar manner. Adding new forms will only change the MetaData element of the Elements.xml file (additional URNs will have to be added corresponding to the new InfoPath Forms).
We have created different forms for the tasks in our example. The next task (if Initial Clearance is approved) will be the Technical Clearance Task. Now, we want to show the comments of Initial Clearance in the Technical Clearance task, so that the Technical Panel has additional information about the candidate.
To achieve this, we must be able to send information from a Workflow to the InfoPath Form. This can be done using the Data connection in the InfoPath. We need to create an XML file named “ItemMetadata.xml” which will contain the names of the fields we want to be available in InfoPath. Then we create a new Data Connection in InfoPath for receiving the data. The name of columns in ItemMetaData.xml should start with “ows_”. You pass multiple values to the InfoPath form using a single ItemMetaData.xml file. Refer Fig. 1.4.
Fig 1.4
To add this XML file to the InfoPath Form, in InfoPath Designer, select the Data tab and add a new data connection by clicking the Data Connection button. In the pop-up window, click the Add button, select Receive Data in the next window, and click the Next button. Select the XML Document option, in the next window, browse the XML file, click Next, and finish the configuration with the default values selected.
In the Fields Explorer window, the drop-down shows two connections now. You can choose to drag and drop fields from the newly configured data connection onto the InfoPath form. Refer Fig. 1.5.
Fig 1.5

Step 4

In Visual Studio, the MethodInvoking event of the Create Task activity in the Initial Clearance State will be called when the task is created. We specify the details of the task in this event. For the task to be associated with a specific InfoPath Form, we need to configure the TaskType property of the TaskProperties field of this task. For our example, we will have the following code. Here, we correspond the TaskType to the number we have associated with the URN while entering it in Elements.xml.
//Task Type corresponds to TaskURN specified in Elements.xml
this.createTaskInitialClearanceTaskProperties.TaskType = 1;
Make sure that the URN specified in Elements.xml maps to the same task in the code-behind file; else the workflow will encounter an error while opening the task form.
To send data from SharePoint to the InfoPath form, we have setup a receive data connection in InfoPath Forms. We can achieve this by setting up the ExtendedProperties of the Task property field in the same event, i.e., the MethodInvoking event. ExtendedProperties is a hashtable (Key-Value pair) and the key in our case will be the name of field we have used in ItemMetaData.xml and the value will be the value of the remarks of the previous stage.
The Invoked event of the EventDriven activity will be called after the user has performed the task. Once the task has been completed, we need to access the values entered by the user on the InfoPath Task forms. We can access these values by using the ExtendedProperties property of the AfterProperties field of this task. Below are the code snippets for all the events and methods associated with the Technical Clearance task.
Here is the MethodInvoking Event:
private void createTaskTechnicalClearance_MethodInvoking(object sender, EventArgs e)
{
    try
    {
        //Create a new TaskId for the Task
        this.createTaskTechnicalClearanceTaskId = Guid.NewGuid();

        //TaskProperties field is used to configure the Task Details.
        this.createTaskTechnicalClearanceTaskProperties.Title = "Technical Clearance";

        //You can assign a Task to an user or to a group.
        //Here we assign the task to HR-Group

        SPListItem listItem = this.workflowProperties.Item;
        //Write the remarks value to the list item
        if (listItem != null)
        {
            //Check if TechnicalInterviewAssignedTo Field has
            //a value, and Assign this Task to the value of this Field
            if (listItem.Fields.ContainsField("TechnicalInterviewAssignedTo"))
            {
                this.createTaskTechnicalClearanceTaskProperties.AssignedTo = 
                   listItem["TechnicalInterviewAssignedTo"].ToString();
            }

            //To send InitialRemarks to the InfoPath Form,
            //we add it to the ExtendedProperty of the TaskProperties
            //ExtendedProperties is a hashtable (Key-Value pair). 
            //The Key will be the name of field we have used
            //in ItemMetaData.xml and Value will be the value of remarks
            if (listItem.Fields.ContainsField("InitialRemarks"))
            {
                if (this.createTaskTechnicalClearanceTaskProperties.
                     ExtendedProperties.ContainsKey("InitialComments"))
                {
                    this.createTaskTechnicalClearanceTaskProperties.
                      ExtendedProperties["InitialComments"] = 
                      listItem["InitialRemarks"].ToString();
                }
                else
                {
                    this.createTaskTechnicalClearanceTaskProperties.
                      ExtendedProperties.Add("InitialComments", 
                      listItem["InitialRemarks"].ToString());
                }
            }
        }

        //Task Type corresponds to TaskURN specified in Elements.xml
        this.createTaskTechnicalClearanceTaskProperties.TaskType = 2;

        this.createTaskTechnicalClearanceTaskProperties.DueDate = 
                       DateTime.Today.AddDays(2.0);
    }
    catch (Exception ex)
    {
        //throw ex;
    }
}
Invoked Event:
private void onTaskChangedTechnicalClearance_Invoked(
        object sender, ExternalDataEventArgs e)
{
    try
    {
        this.onTaskChangedTechnicalClearanceAfterProperties = 
           this.onTaskChangedTechnicalClearance.AfterProperties;
        this.onTaskChangedTechnicalClearanceBeforeProperties = 
           this.onTaskChangedTechnicalClearance.BeforeProperties;

        //Set the PercentComplete property to 1.0 (i.e. 100%)
        //to indicate that the task has been completed.
        this.onTaskChangedTechnicalClearanceAfterProperties.PercentComplete = (float)1.0;

        //Get the value of Remarks Column (InfoPath Form)
        //by using the ExtendedProperties property
        string remarks = this.onTaskChangedTechnicalClearance
                 BeforeProperties.ExtendedProperties["Remarks"].ToString();

        SPListItem listItem = this.workflowProperties.Item;

        //Write the remarks value to the list item
        if (listItem != null && 
             listItem.Fields.ContainsField("TechnicalInterviewRemarks"))
        {
            listItem["TechnicalInterviewRemarks"] = remarks;
        }
    }
    catch (Exception ex)
    {
        //throw ex;
    }
}
Condition handling - TechnicalClearanceApprovalProcess:
private void TechnicalClearanceApprovalProcess(object sender, ConditionalEventArgs e)
{
    try
    {
        if (this.onTaskChangedTechnicalClearanceAfterProperties.PercentComplete == 
           (float)1.0 && this.onTaskChangedTechnicalClearanceAfterProperties.
                         ExtendedProperties["Status"].ToString().Contains("Approved"))
        {
            e.Result = true;
        }
        else
        {
            e.Result = false;
        }
    }
    catch (Exception ex)
    {
        //throw ex;
    }
}

Monday, 6 August 2012

Delegate Controls in SharePoint 2010


Delegate Controls in SharePoint 2010
SharePoint provides a mechanism that allows developers to customize out-of-the-box functionality in pages, without the need for modifying the pages that come with SharePoint. This mechanism is provided with delegate controls. I am going to show you how to create a delegate control that you can use to override the Global Navigation bar at the top of standard SharePoint pages.

Definition

First off, it’s important to understand what a delegate control is, so we can properly create and apply it in the specific situation we are developing for. A delegate control defines a region in an aspx page that allows the content to be replaced with our custom content. This custom content is created via a SharePoint feature, and when deployed and activated, replaces the standard content at runtime.

Development

The Global Navigation bar is located at the top of all the pages in a site, and the master page uses a delegate control in a placeholder to determine what to render at runtime. Here is the markup for the delegate control:
<SharePoint:DelegateControl runat=”server” ControlId=”GlobalNavigation”/>

Note that the ControlId value determines what delegate control is, so for our example the Global Navigation bar has a ControlId value of GlobalNavigation.
Once we know the name of the delegate control we are working with, we are ready to write code for our delegate control.
Open Visual Studio 2010 and create a new Empty SharePoint project. Map a folder to the CONTROLTEMPLATES directory in the SharePoint root (the 14 hive). Add a new SharePoint 2010 User Control by right-mouse clicking the CONTROLTEMPLATES mapped directory, from the Solution Explorer. Give the user control an appropriate name (I named itucGlobNavDelegateControl). Once the control is created, open it in the Designer and add some markup:
Custom Delegate Control
You will also need to create an Elements.xml file, so add a module to the project, which will create the Elements.xml file as part of it (you can delete the Sample.txt file created).
Delete the markup between the Elements tags, and add the following markup:
<Control Id = “GlobalNavigation” Sequence=”90”
 ControlSrc=”~/_ControlTemplates/ucGlobNavDelegateControl.ascx” />

This markup associates the delegate control we are creating with the delegate control placeholder defined in the master pages in a SharePoint site collection. Note that the ControlId value equalsGlobalNavigation, which specifies that our custom delegate control is overriding the Global Navigation control. The Sequence value must be less than 100, since SharePoint will render the control with the lowest sequence (the default control is set at 100). The ControlSrc value indicates the location to our custom delegate control.

Deployment

Deploying our custom delegate control is done using a feature, so create a feature in Visual Studio and name it MyCustomGlobalNavigationFeature. Add the module you created to it, and set the feature scope to Web. Compile and deploy the project to your SharePoint site.
Once your feature is deployed successfully, you should be able to verify that your feature has been deployed and activated in your site by managing the Site Features, under Site Settings. Look for your deployed feature, as shown here:
Activating Feature
If your feature is properly activated, you should now see the Global Navigation replaced by your custom delegate control:
SharePoint Page with Custom Delegate Control

Conclusion

And that’s all there is to it! Of course, the example here is basic, so there is a lot more that can be done with delegate controls. I am also including a screenshot of my Solution Explorer in Visual Studio, so you can get an idea of how my example project was structured:
Solution Explorer