Wednesday, November 11, 2009

Event Receivers: How to add event receivers to a sharepoint list

Scenario: How to add custom event receivers to a specific sharepoint list using SharePoint Object Model

Approach:

SPList list = web.Lists["MyList"];

string assemblyName = "CustomSharePointEventReceivers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d517db3ed1131947";

string className = "CustomSharePointEventReceivers.MyEventReceivers";
list.EventReceivers.Add(SPEventReceiverType.ItemAdding, assemblyName, className);
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, assemblyName, className);
list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, assemblyName, className);



Note: In general, custom event receivers to a specific list will be added through Sharepoint features by defining a feature event receivers by extending SPFeatureReceiver. In the SPFeatureReceiver, override all the 4 methods i.e, FeatureInstalled,FeatureActivated, FeatureDeactivating and FeatureUninstalling. In these overriden methods, write above code piece.

Event Receivers: Delete all event receivers associated to a list

scenario: How to delete all the event receivers associated to a list?

Approach:


List eventreceivers = new List();

foreach (SPEventReceiverDefinition EventReceiver in list.EventReceivers)
{
eventreceivers.Add(EventReceiver);
}

foreach (SPEventReceiverDefinition er in eventreceivers)
{
er.Delete();
}


Note: We can not have only 2nd foreach loop alone. The current list of event receivers associated to a list gets updated everytime a delete operation is performed. So, an exception will be raised if you use only delete operation.

Change Workflow Task Status from any SharePoint custom component

Scenario: I have a custom workflow running. I want to change status a task from another sharepoint custom component like webpart or so.

Approach:
If we update the workflow task directly by changing the status field value to Completed or to any other status, then usually workflow raises an exception "This task is currently locked by a running workflow and cannot be edited." To get rid of this error, you can use following routine:


private void CompleteTask(string taskTitle)
{
try
{
Hashtable taskHash = new Hashtable();
taskHash[SPBuiltInFieldId.TaskStatus] = "Completed";

string currentuser = SPContext.Current.Web.CurrentUser.Name.ToLower();
Guid siteID = SPContext.Current.Site.ID;
Guid webID = SPContext.Current.Web.ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteID))
{
using (SPWeb web = site.OpenWeb(webID))
{
web.AllowUnsafeUpdates = true;
SPList wfTasksList = web.Lists["WorkflowTasks"];
SPQuery queryWFTasks = new SPQuery();
queryWFTasks.Query = <<>>;
queryWFTasks.ViewAttributes = "Scope=\"RecursiveAll\"";

SPListItemCollection wfTaskItems = wfTasksList.GetItems(queryWFTasks);

if (wfTaskItems.Count != 0)
{
foreach (SPListItem item in wfTaskItems)
{
if (item.Title.ToLower().Equals(taskTitle.ToLower()))
{
SPWorkflowTask.AlterTask(item, taskHash, true);
break;
}
}
}

web.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
// Log the exception here
}
}

SharePoint Workflow : Get From Email Address Configured in Central Admin

Scenario: I want to send email from workflow SendEmail activity. How to get From email address configured in central administration for my sharepoint application.

Note: For every sharepoint application, we can configure out-going email address information in central admin. This can be done in following steps:
a. Go to central admin site -> Application Management
b. Under "SharePoint Web Application Management" section, check for the link "Web application outgoing e-mail settings" and click on it.
c. Select the Web Application for which you want to set the out going email informatino.
d. Fill the following fields:
  • Outbound SMTP server:

  • From address:

  • Reply-to address:

  • Character set:

Approach:
In the SendEmail activity execute code, you write following instruction to get email set in above "From address:" field:

workflowProperties.Site.WebApplication.OutboundMailSenderAddress

How to get SharePoint user information from Person or Group field in SharePoint List

Scenario: I have a SharePoint list with various fields. One of them is Person field, in which I am storing the value selected through People Picker. How to get the Person value from this field through SharePoint Object Model.

Approach:


// Step1: Get SharePoint Item object
SPListItem Item = SPContext.Current.Web.Lists["MyList"].Item[0];

// Step2: Get user field object by passing field display name
SPFieldUser userField = (SPFieldUser)Item.Fields.GetField("Created By");

// Step3: Get user field value object
// SPBuiltInFieldId.Author refers to Created By field's internal name
SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(Item[SPBuiltInFieldId.Author].ToString());

// Step4: Get user object
SPUser userVendor = fieldValue.User;

Never use Thread.Sleep in SharePoint Workflows

From last 2 months, i was very busy in developing custom workflows. So, I didn't get chance to blog my experience during all these days. I really got great experience by working on a custom workflow. I am trying to put my experience in various posts including this post.

Coming to the main point, never ever use Thread.Sleep in SharePoint workflows

Reason: If we deploy the custom workflow with Thread.Sleep instructions, then IISReset will keep these instructions out of memory and the workflow will struck there.
Alternative: Use appropriate inbuilt or custom workflow activities.

Sunday, September 13, 2009

SharePoint Custom Workflow Error (related to Serialization): WinWF Internal Error, terminating workflow

I created a custom workflow using VS 2008 for MOSS 2007.
In my SP site, I created a custom list CONTACTS with following columns:
Region - Single Line Text
Dept1 - Person Group
Dept2 - Person Group
Dept3 - Person Group

In this workflow, I need to retrieve users from CONTACTS list and create tasks for the users included within the groups associated to Dept columns.
I created custom workflow and ran it by associating to another list.
I got following error:
"WinWF Internal Error, terminating workflow Id# d4a5785f-22bf-42e8-bfca-d561bdb44ed7 System.Workflow.Runtime.Hosting.PersistenceException: Type 'Microsoft.SharePoint.SPUserCollection' in Assembly 'Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' is not marked as serializable. ---> System.Runtime.Serialization.SerializationException: Type 'Microsoft.SharePoint.SPUserCollection' in Assembly 'Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' is not marked as serializable. at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type) at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context) at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo() at System.Runtime.Seri... ...alization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter) at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph) at System.Workflow.ComponentModel.Activity.Save(Stream stream, IFormatter formatter) at System.Workflow.Runtime.Hosting.WorkflowPers... Workflow Infrastructure 98d4 Unexpected ...istenceService.GetDefaultSerializedForm(Activity activity) at Microsoft.SharePoint.Workflow.SPWinOePersistenceService.SaveWorkflowInstanceState(Activity instanceState, Boolean unlock) at System.Workflow.Runtime.WorkflowExecutor.Persist(Activity dynamicActivity, Boolean unlock, Boolean needsCompensation) --- End of inner exception stack trace --- at System.Workflow.Runtime.WorkflowExecutor.Persist(Activity dynamicActivity, Boolean unlock, Boolean needsCompensation) at System.Workflow.Runtime.WorkflowExecutor.ProtectedPersist(Boolean unlock)"

What I understood from above exception in the SharePoint Logs:
The exception raised by WF is because of SPUserCollection object is not marked as serializable.
I made following changes to my code:
a. Marked my custom workflow class as serializable as all the objects within WF must be serializable. I did this by placing the attribute on top of the class as below:
[Serializable()]
public partial class SampleWorkflow : SequentialWorkflowActivity
{
}
b. Removed declaration of SPUserCollection objects as these obj are not serializable. To store user information for each department, i created separate hashtable and stored the data while retrieving the user information, instead of storing SPUser or SPUserCollection objects.

Reference Blog Posts, which helped me in solving this problem:
http://social.msdn.microsoft.com/Forums/en-US/sharepointworkflow/thread/01cde268-5148-4ff7-847e-1d03803c91c2
http://social.msdn.microsoft.com/Forums/en-US/sharepointworkflow/thread/9bd91cba-558c-456a-8f3c-e0e829145ec6/
http://blogs.msdn.com/sharepoint/archive/2006/11/28/developing-workflows-in-vs-part-5-code-your-workflow.aspx

Friday, September 4, 2009

Building ASP.NET DatePicker

Following link has simple way of creating a datepicker in ASPX pages.
http://www.codedigest.com/Articles/ASPNET/247_DatePicker_Control_in_ASPNet.aspx

Debugging tips for SharePoint

Today, I came across with very good post regarding debugging tips for SharePoint.
http://blog.thekid.me.uk/archive/2007/07/25/debugging-tips-for-sharepoint-and-wss-exceptions.aspx
Most of the tips you may know already but this list has collection of tips.
Enjoy debugging.

Tuesday, August 18, 2009

Looking for answers - SharePoint Questions

Today, I came across with following questions:
a. Alert mail is not sending for new items created in a survey list when branching logic is enabled. But, receiving alert mails for edit & delete items mails when branching logic is enabled. Not sure why? How to resolve this.

b. There is a document library with folders and sub folders. How to create a view targetting to a sub-folder? Ofcourse, we can restrict the users on folder view but want to create a view to display files within a folder.

Please leave a comment if anyone knows answer for above questions.

Wednesday, August 12, 2009

Form based authentication in SharePoint - MUST READ

While I was browsing through MSDN site, I found MUST READ articles for FBA with SharePoint:

SharePoint Integrating with the 2007 Microsoft Office System

Office SharePoint Server 2007 and Windows SharePoint Services 3.0 users who also have the 2007 Microsoft Office system of applications installed enjoy a high level of integration between the 2007 Office system and SharePoint Products and Technologies. Many of those integration features, however, depend on Windows authentication. Without Windows authentication, some integration points do not work, and others are changed considerably. To help minimize user confusion, SharePoint Products and Technologies offer a mode in which certain menu items that require Windows authentication are removed. In the Central Administration Web site, on the Authentication Provider page, this mode is controlled via the Enable Client Integration box.

When you configure a zone to use forms authentication, the Enable Client Integration box is cleared by default. If a zone is configured in this way, the following changes occur in functionality:


  • Support for remote interfaces is turned off. That includes WebDAV, SOAP, and Microsoft Office FrontPage remote procedure calls (RPC). Some functionality is not available, such as Web folders or the Web services for accessing content in that site.
  • Some toolbar items no longer appear:
    • New Document
    • Open in Outlook
    • Open In Windows Explorer
    • Export to Spreadsheet
    • Open with Database Program
    • Explorer View option is hidden.
    • Create an Access View option is hidden.
  • In picture libraries, the following functionality is removed:
    • Upload Multiple
    • Edit Picture
    • Download
    • Send To
  • On the Edit Control Block (ECB) menu, the drop-down menu that appears when you click items in document libraries, the following items are removed:
    • Edit in Word
    • Edit in Excel
    • Edit in PowerPoint
    • Discuss
    • Connect To Outlook
  • In slide libraries the following functionality is removed:
    • Publish Slide
    • Send to PowerPoint

Also, syncing SharePoint data with Microsoft Office Outlook no longer works.

When operating in this mode, users can still work with documents in SharePoint libraries, but they must right-click items and choose to save a copy to disk. They can then edit and update the document, and then upload it and check it back in when they are finished editing.

Some organizations might want to use forms authentication, but also require the same level of integration they get when using Windows authentication. There are a couple of possible workarounds in this scenario, but it is helpful to examine why this limitation exists.

When a user accesses a page on a site protected by forms authentication, the server looks for a valid authentication cookie. If no cookie is found, or if the cookie is not valid, the server redirects the browser to the logon page by using an HTTP 302 status code. At this page, the user is allowed to authenticate by using his or her credentials. After the credentials are validated, the server creates a valid authentication cookie and sends it back to the browser, with the originally requested page. The browser keeps the cookie in memory and sends it back to the server with every subsequent request to that Web server. With each request, the server checks the validity of the cookie to ensure that it is good (that it has not expired or been tampered with), and then processes the request.

Because the authentication cookie is in memory with the browser process, it introduces some limitations:

  • The cookie is retained only as long as the browser is open; when the browser is closed the cookie is destroyed with everything else in memory that the browser was using.
  • The cookie belongs to the browser's application process (such as the .exe file for the browser), and cannot be shared with other processes. Office system applications run in their own processes, for example, msword.exe for Microsoft Office Word. As such, a cookie that a user generated when logging into the site in the browser cannot be shared with Word.

The issues described in this article clarify why the Enable Client Integration option was developed: to help make the end-user experience more uniform and predictable in that environment; however, the user experience is somewhat different for users that are accustomed to SharePoint sites secured with Windows authentication. Even with those restrictions, there are still a few options that can be used to allow for using forms authentication and yet still provide many or all of the deep integration points with Office applications that are available when using Windows authentication.

Reference of above content: http://msdn.microsoft.com/en-us/library/bb977430.aspx#MOSSFBAPart3_IntegratingWithOffice2007

How To: Choose between InfoPath Browser Forms and Custom ASPX Forms

Choosing between InfoPath forms and ASPX pages, depends totally on the nature of the problems we are solving on one side and level of skill set we are investing in solving that problem on the other side. Usually, in most cases, any manager or developer would want to use InfoPath Forms part of Office 2007 because it’s quick and easy. But, as the requirements get more complex and requires more and more customization, one might feel its better to go with ASPX pages and Visual Studio 2005 and SharePoint designer. Technically, InfoPath Forms by itself is incomplete; It needs a container which is again an ASPX web form using the XmlViewer web part. If we go with custom ASPX form, then it has to be designed either using SharePoint designer or Visual Studio leveraging web parts to show the required forms. So for this, developing web parts and its complexity needs to be taken into consideration.
So, to decide on one, we may have to take the decision step by step.

If the requirement is for a single form and showing data from an external data store or from within SharePoint, then going with InfoPath Forms is recommended.

If it’s a single form and needs complex actions, to and fro between the form and the data store, then choosing custom aspx pages is recommended.

If the requirement needs wizard kind of feature i.e. which requires user to go through multiple screens, then custom aspx is the solution.

If the data submitted through the form has to be saved to multiple locations (database, SharePoint, file storage) then InfoPath Forms is a good solution.

If the requirement is for designing numerous forms which are simple enough and well documented, then InfoPath Forms should be considered. InfoPath can help deliver the solution in a short time period.

InfoPath browser based forms has few limitations on the repository of controls one can use. For example: combo box, master/detail view control and many advanced controls are not supported in browser based InfoPath Forms. Depending on these limitations we have to decide on InfoPath or ASPX. ASPX has no such limitations.

InfoPath forms is based on XML. The form is rendered using XSLT stylesheets and the data submitted through the form is available in XML format. The data is well structured to retrieve later on and dump the data/forms in some external system. This in combination with BizTalk server is a perfect architecture for document transition through multiple levels.

InfoPath forms certainly have an edge over ASPX forms as a quick and neat solution. It has some complex out of the box controls, like date picker, file attachment control, repeating sections. InfoPath forms can also have code-behind if needed to manipulate the data on the form or behind the form.

ASPX can have and do everything InfoPath Forms does, with an exception of additional development effort. Apart from it, the deployment process of aspx forms is much better and easier than InfoPath Forms.

Below are some of the excerpts from few blogs I follow which provides some valuable input comparing InfoPath and ASPX forms. Below are the Pros and Cons in using InfoPath Forms:

Pros:
  • Ideal for simple forms
  • Easy to build a form – no coding involved
  • InfoPath form itself is an xml document.
  • Support versioning
  • Works very nicely with SharePoint custom workflows as a workflow association tool.
  • Fully integrated in Microsoft Office 2007 suites like Outlook e-mail messages that can be deployed as Outlook e-mail messages, so colleagues can complete forms without leaving the familiar Outlook environment.
  • Firewall friendly. InfoPath Forms Services make it easy to extend forms solutions beyond firewall because of using many different Web browsers and mobile devices.
  • InfoPath can easily convert Word documents and Excel spreadsheets to forms and build templates to work with.
  • InfoPath provides data integrity and version control for document management purposes, and add structure to information gathering by converting legacy documents to rich InfoPath form templates.
  • Design of a form is much easier in InfoPath forms with a simple drag-and-drop interface and provides support for prebuilt template parts and shared data connections.
  • Creates PDF or XPS and other important document formats and is extensible by addition of a free plug-in to install third party tools and components for document, archival and records management
  • Fully integrated with MOSS 2007 and capable of using integrated workflow management tools in Office 2007
  • Fully Web browsed technology, includes a design checker to help ensure consistency for forms.
  • Support for information rights management to help manage permission control and building a powerful document management team site.
  • Fully centralized for entire organization and enables organizations to centrally

Cons:

  • A web browser-enabled InfoPath form does not support all features of InfoPath client.
  • Inflexible — Difficult or impossible to customize (well, you can argue that you can hack the xsl file of InfoPath)
  • No support for image buttons
  • No support for html
  • No support for tree control
  • Difficult to support Forms Based Authentication
  • By default, InfoPath cannot support SharePoint web services data connections in FBA.
  • Forms Services does not support username() function in FBA. This means that InfoPath form does not recognize the current user.
  • Difficult to perform automated web test against Forms Services.
  • Difficult to support automated deployment. Basically, you have to unzip the xsn file and programmatically modify the manifest.xsf file, and zip back to the xsn file for automated publishing.
  • The way that Forms Services supports deployment of InfoPath forms is quirky – It creates SharePoint solution packages with GUID and creates features with meaningless names on the SharePoint Features folder.

Note: The above content is taken from following link: http://sharenotes.wordpress.com/2008/06/02/how-to-choose-between-infopath-forms-and-custom-aspx-forms/

Below are the blog links which talk more about this topic:
http://www.jyhuh.com/blog/archive/2008/03/02/AspNet_vs_InfoPath_Forms_Services.aspx
http://office12.blogspot.com/2007/06/infopath-web-forms-vs-aspx.html

Wednesday, August 5, 2009

How do you authenticate a user request on a web site?

There are APIs provided in .NET Framework to check the authentication programatically:
System.Web namespace has following class which will help us in authenticating the request,
HttpContext.Current.Request.IsAuthenticated

If a web site is configured for anonymous authentication, then all the users are authenticated by default. For intranet/extranet sites, authentication plays a vital role. Where, we can use above property to check.

SharePoint site collection / site also has methods to authenticate user whether the user has enough access permissions on the site collection or a particular site. For more information, check WSS 3.0 or MOSS 2007 SDK.

Tuesday, August 4, 2009

10 Essential Resources for SharePoint Developers

1. Microsoft Office SharePoint Server (MOSS) SDK and ECM Starter Kit http://www.microsoft.com/downloads/details.aspx?familyid=6D94E307-67D9-41AC-B2D6-0074D6286FA9&displaylang=en

2. Windows SharePoint Services (WSS) SDK and Workflow Starter Kit http://www.microsoft.com/downloads/details.aspx?FamilyID=05e0dd12-8394-402b-8936-a07fe8afaffd&DisplayLang=en

Note: The MOSS SDK includes the WSS SDK documentation and a more robust starter kit

3. Visual Studio Extensions for SharePoint Services (November CTP)http://www.microsoft.com/downloads/details.aspx?familyid=19F21E5E-B715-4F0C-B959-8C6DCBDC1057&displaylang=en

4. Customizing and Branding Web Content Management-Enabled SharePoint Sites

5. MOSS for Content Management Server Developers (Beta)Three papers + an analysis tool:

6. Office Developer Screencasts (applies to all of Office) http://msdn2.microsoft.com/en-us/sharepoint/aa905382.aspx

7. SharePoint Developer Map (also includes InfoPath and 2007 Office System posters)http://www.microsoft.com/downloads/details.aspx?familyid=771aeb45-9d27-4d1f-acd1-9b950637d64e&displaylang=en

8. MOSS and WSS Online Clinics. Online clinics covering SharePoint technology are free for a limited time!!! Check 'em out:

9. MOSS portal on the Office Developer Centerhttp://msdn.microsoft.com/moss
Includes the Upgrade and Migration Center for SharePoint Developers http://msdn2.microsoft.com/en-us/office/aa905505.aspx

10. SharePoint Developer Centerhttp://msdn.microsoft.com/sharepoint

11. 7 Development Projects for SharePoint – online book http://download.microsoft.com/download/0/2/f/02f0f661-88e1-43c2-b523-88d2e9e6802f/7%20development%20projects%20with%20the%202007%20microsoft%20office%20system%20and%20windows%20sharepoint%20services%202007.pdf

12. MSDN Community ContentMSDN Community Content is a way of providing Wiki-style annotations to core Microsoft documentation. For example, you can add code samples, remarks or “gotchas,” translations, or other comments that enhance or supplement the core MSDN documentation.

13. F1 Help from Visual Studio Document ExplorerFollow the steps in this blog post to receive F1 Help directly from your code in Microsoft Visual Studio 2005.

http://blogs.msdn.com/randalli/archive/2006/07/28/sharepoint-development-tip-getting-context-sensitive-f1-help-directly-from-the-msdn-library.aspx

14. Project SDK DownloadI see a lot of questions about SharePoint integration with Project Server, and the Project SDK is also produced by my team. http://www.microsoft.com/downloads/details.aspx?FamilyID=2672f6f9-7028-4b30-99a2-18cb1eed1abe&DisplayLang=en

More from our SharePoint MVPs and Partners
SharePoint MVPs are also producing great lists of resources for SharePoint; here are two examples if you haven’t already seen them.

Note: I got this list from http://blogs.msdn.com/randalli/archive/2007/01/08/10-essential-resources-for-sharepoint-developers.aspx

How do you tell current sharepoint page is in edit/display/other modes?

Microsoft.SharePoint.WebControls.SPControlMode enumeration contains following values:
  • Display
  • Edit
  • Invalid
  • New

With following condition, you can check in which mode you are in:


if (SPContext.Current.FormContext.FormMode == Microsoft.SharePoint.WebControls.SPControlMode.Display)


{
// you are in display mode
}

Monday, August 3, 2009

Issue with workflows: Missing Completed Workflows History

Following blogs talked about the issue:
"I cannot find any workflow histories on approved documents that were approved 2 months or more ago. The document status says its approved but there are no histories showing under "Completed Workflows." Is there some kind of retention policy in MOSS 2007? This is causing a major auditing issue for us. Where can I retrieve this history information from? "

Blogs URLs:
http://social.msdn.microsoft.com/forums/en-US/sharepointworkflow/thread/b15b27e2-3033-418b-9731-968273d7423e/

http://www.sharepointblogs.com/llowevad/archive/2007/09/21/huge-workflow-issue-what-is-microsoft-thinking.aspx

Workflows: Major Microsoft.Windows.SharePoint.Workflow Objects

The Microsoft.SharePoint.Workflow namespace represents the workflow functionality contained in Windows SharePoint Services.

  • SPWorkflowTemplateCollection object: Represents the workflow templates currently deployed on a site.
  • SPWorkflowTemplate object: Represents a workflow template and contains properties you can use to get or set information about the template, such as the instantiation data and the history and task lists for the template.
  • To associate a workflow to a list or document library, use the AddWorkflowAssociation method of the SPList object.
  • To associate a workflow with a content type, use the AddWorkflowAssociation method of the SPContentType object.
  • To create the appropriate workflow association, use the CreateListAssociation, CreateListContentTypeAssociation, or CreateSiteContentTypeAssociation method of the SPWorkflowAssociation object itself.
  • Use the RemoveWorkflowAssociation method to remove a workflow association from a list.
  • Use the RemoveWorkflowAssociation method to remove a workflow association from a site or list content type.
  • Each SPWorkflowAssociation object represents a workflow template that is associated with a specific list or content type, and that contains properties that return custom information about that workflow's association with the specific list or content type. This information includes whether the workflow is enabled, whether the workflow can be started automatically, and the list or content type with which the workflow has been associated.
  • The SPWorkflowCollection represents the workflow instances that have run or are currently running on a given list item.
  • Each SPWorkflow object contains properties that return information about the workflow instance, such as whether the workflow has completed, its internal state, and its workflow history list.
  • Use the Workflows property to return an SPWorkflowCollection object that represents the workflows currently running for that list item.

Managing Running Workflow Instances Programmatically
Users interact with the workflows running on items individually, through the Windows SharePoint Services user interface. But Windows SharePoint Services provides functionality for you to centrally control the running instances of workflows across your site collection through the object model. Use the SPWorkflowManager object to manage the running instances of workflows across a site collection. The SPWorkflowManager object has no equivalent in the user interface. Use the SPWorkflowManager object to:

  • Start, run, or cancel workflows.
  • Return all the workflows currently running on a specific item.
  • Perform other workflow administration operations.

Workflows: Workflow Association and Initiation Forms [WSS 3.0]

Association and initiation forms are displayed for users to complete before any workflow actually starts. You can use these forms to enable users to set parameters and other information for the workflow in advance. Association forms address how the workflow applies to a specific list, library, or content type; initiation forms address how the workflow applies to a specific SharePoint item.

Association forms are displayed to administrators when they first decide to add—or associate—a workflow with a particular list, document library, or content type. You can use association forms to let an administrator specify parameters, default values, and other information for the workflow as it applies to items on the list, library, or content type with which the administrator is associating it.

Initiation forms are displayed to users when they start a workflow on a specific SharePoint item. You can use initiation forms to let users override or append the association parameters set by administrators, or specify additional parameters or information about the workflow as it applies to the specific SharePoint item. Not all workflows need initiation forms.

The initiation form can be the same form as the association form. For example, using the same form for each workflow form enables you to let administrators set certain default parameters during workflow association, and then let the user who actually starts the workflow instance on a particular item review and overwrite those default parameters.

Specifying Association Forms
You specify a workflow's association form in the workflow template definition XML. To do this, set the value of the AssociationURL attribute of the Workflow element to the custom form page you want to use for workflow association. For example:
AssociationURL="MyWkflAssociationPage.aspx"

Note: Windows SharePoint Services 3.0 supports absolute or server-relative paths in the workflow template definition. You must express all form path URLs in one of these formats. For example, you can use an absolute path, such as "http://site/library/page.aspx", or a server-relative path, such as "/layouts/page.aspx". Windows SharePoint Services does not support link fix-up in workflow template definitions.

Association Form Processing
When an administrator selects a workflow to associate with a given list, library, or content type, Windows SharePoint Services displays the Add a New Workflow page. The administrator can use this page to specify settings common to all workflows, such as the workflow definition and initiation conditions, and whether the workflow runs on items, folders, or both.

When the administrator clicks the Next button on this page, Windows SharePoint Services examines the AssociationURL attribute of the Workflow element, in the workflow template definition, to determine the proper form to load.

To provide custom data to the association form, you can store this information in the AssocationData element. For example, you could use this element to store default values you want to pass to the association form when it is displayed. The AssocationData element can contain any valid XML. Your form can then load that association data from the workflow template.

Because the workflow association is not created until the custom association form is submitted, Windows SharePoint Services also passes the following query parameters to the custom association form:


<input type="hidden" name="WorkflowDefinition" value=<% _STSWriteHTML(Request.Form["WorkflowDefinition"]); %>>
<input type="hidden" name="WorkflowName" value=<% _STSWriteHTML(Request.Form["WorkflowName"]); %>>
<input type="hidden" name="AddToStatusMenu" value=<% _STSWriteHTML(Request.Form["AddToStatusMenu"]); %>>
<input type="hidden" name="AllowManual" value=<% _STSWriteHTML(Request.Form["AllowManual"]); %>>
<input type="hidden" name="RoleSelect" value=<% _STSWriteHTML(Request.Form["RoleSelect"]); %>>
<input type="hidden" name="AutoStartCreate" value=<% _STSWriteHTML(Request.Form["AutoStartCreate"]); %>>
<input type="hidden" name="AutoStartChange" value=<% _STSWriteHTML(Request.Form["AutoStartChange"]); %>>
<input type="hidden" name="GuidAssoc" value=<% _STSWriteHTML(Request.Form["GuidAssoc"]); %>>


The workflow developer must program what happens when the administrator submits changes to the form. In general, the custom workflow association form must perform the following actions:



  • Examine the value of the GuidAssoc parameter to determine whether the user is adding a new workflow association or editing an existing workflow association.
  • If the user is adding a new workflow association, call the AddWorkflowAssociation method to create a new workflow association.
  • If the user is editing an existing workflow association, call the UpdateWorkflowAssociation method to update that workflow association.
  • Create the task list for the workflow, if it does not already exist.
  • Use the data collected from the user to set properties of the SPWorkflowAssociation object, as appropriate.
  • Create the workflow history list, if necessary.
Specifying Initiation Forms
If you want your workflow to have an initiation form, you must set the InstantiationURL attribute of the Workflow element in the workflow template definition. Set this element to the form you want to use to collect the workflow initiation data, as shown in the following example.
InstantiationURL="MyWkflInitiationPage.aspx"

Initiation Form Processing

When a user starts a workflow on a specific item, Windows SharePoint Services examines the InstantiationURL attribute of the Workflow element, in the workflow template definition, to determine the proper form to load.

Windows SharePoint Services loads the specified form, passing to it the following query parameters in the URL:

  • List The GUID of the list to which the item belongs.
  • ID The ID of the list item on which the workflow is started.
  • Source The page from which the user started the workflow.
  • TemplateID The GUID of the workflow association.

In addition, you can program your form to load the association form data for this workflow association. This information is contained in the AssociationData property of the SPWorkflowAssociation object that represents the workflow association.

The workflow developer must program what happens when the user submits changes to the page. In general, the form must perform the following actions:

  • Locate the SPWorkflowManager object for the current site.
  • Use the SPWorkflowManager object to invoke the StartWorkflow method, passing the appropriate SPListItem and SPWorkflowAssociation objects. Use the eventData parameter to pass the initiation form data in string format.
  • Return the user to the source page from which he or she started the workflow.

When the M:Microsoft.SharePoint.Workflow.SPWorkflowManager.StartWorkflow(Microsoft.SharePoint.SPListItem,Microsoft.SharePoint.Workflow.SPWorkflowAssociation,System.String) method is called, the workflow manager creates an instance of the workflow on the SharePoint item. The workflow manager then passes the data gathered using the initiation form to the OnWorkflowActivated event of the workflow itself.

Any Windows SharePoint Services workflow must start with an OnWorkflowActivated activity. The OnWorkflowActivated activity contains a property, WorkflowProperties, that returns an SPWorkflowActivationProperties object. This object represents the initial properties of the workflow as it starts, such as the user who added the workflow and the list and item to which the workflow was added. In addition, the AssociationData property returns a System.Collections.Hashtable object that represents the custom data provided by the workflow initiation form.

[This article is taken from Microsoft's WSS 3.0 SDK for easy access]



Issue/Error: "A 32-bit version of SharePoint Server is not installed. Please install a 32-bit version of SharePoint Server"

When I was trying to create workflow project by using Visual Studio 2008, I faced above issue.

WSS Extensions from Microsoft (released in Feb 2009):
http://www.microsoft.com/downloads/details.aspx?FamilyID=b2c0b628-5cab-48c1-8cae-c34c1ccbdc0a&DisplayLang=en

Note: Installing above extensions didn't work for me. Try your luck.

Alternative Solution: WSPBuilder
Instal WSPBuilder extension for Visual Studio installed (www.codeplex.com/wspbuilder)

  • In Visual Studio 2008, File > New > ProjectSelect WSPBuilder and then Select then WSPBuilder Project with WorkflowClick OK
  • In the Solution Explorer window Right Click on the Projet Name (for example, WSPBuilderProject1)> Add > Sequential Workflow
  • In the add New Item Window that just open, select Workflow categorie and the Sequential Workflow And then , click on the Add button.Witch templates do you prefer : With code separation or with code ?

I hope the issue resolved by now.

Friday, July 31, 2009

Workflows: Comparing the Visual Studio Designer for Windows Workflow Foundation and SharePoint Designer 2007

The following sections offer a detailed comparison between the capabilities offered by the Visual Studio Designer for Windows Workflow Foundation and Office SharePoint Designer 2007, and the workflows you can create with each.

Visual Studio 2005 Designer

  • Can write workflows for Windows SharePoint Services or SharePoint Server
  • Code-behind file enables developer to write custom Visual C# or Visual Basic .NET code to express business logic
  • Generates workflow markup file
  • Workflow is authored as a template, which can be associated with multiple sites and lists
  • Workflow markup file, or markup and code-behind files, are compiled into workflow assembly
  • Workflow template must be associated with each list on which it is to be available
  • Can use any forms technology. For example, ASP forms for Windows SharePoint Services workflows, or InfoPath forms for SharePoint Server workflows
  • Can include workflow modifications
  • Can use custom symmetrical InfoPath forms, which enables Office client integration of custom workflow forms
  • Can author custom activities for inclusion in workflows
  • Package workflow assembly and workflow definition as a SharePoint feature, and deploy to the site
  • Can use Initiation form to gather information from the user when starting the workflow
  • Can use custom forms for users to interact with SharePoint tasks
  • Visual Studio debugging available
  • Can author both sequential and state workflows

SharePoint Designer 2007

  • Can write workflows for Windows SharePoint Services or SharePoint Server
  • No code-behind file; workflow rules file declaratively encapsulates business logic
  • Generates workflow markup file
  • Workflow is authored against and data-bound to specific list at design time
  • Workflow markup, workflow rules, and supporting file are stored, uncompiled, in a specific document library on the site
  • Association happens when the workflow is authored against the specific list; no later association is necessary or possible
  • Automatically generates ASP.NET forms, which you can then customize
  • Workflow modifications are not available
  • InfoPath forms integration not available
  • Must use activities provided
  • Automatically handles deployment to specific list
  • Can use Initiation form to gather information from the user when starting the workflow
  • Can use custom forms for users to interact with SharePoint tasks
  • No step-by-step debugging available
  • Can author only sequential workflows

Workflows: Workflow Architecture

The workflow functionality in Windows SharePoint Services 3.0 is built on the Windows Workflow Foundation (WF), a Microsoft Windows platform component that provides a programming infrastructure and tools for development and execution of workflow-based applications. WF simplifies the process of asynchronous programming to create stateful, long-running, and persistent workflow applications. The WF run-time engine manages workflow execution and allows workflows to remain active for long periods of time and to survive restarting the computer. Run-time services offer functionality such as transactions and persistence to manage errors gracefully and correctly.

The WF run-time engine provides the services that every workflow application needs, such as sequencing, state management, tracking capabilities, and transaction support. The WF run-time engine serves as a state machine responsible for loading and unloading workflows, as well as managing the current state of any workflows that are running. WF allows any application process or service container to run workflows by hosting WF — that is, loading WF within its process. Windows SharePoint Services hosts the WF run-time engine. In place of the pluggable services that are included with WF, Windows SharePoint Services provides custom implementations of the following services for the engine: transaction, persistence, notifications, roles, tracking, and messaging. Developers can then create workflow solutions that run within Windows SharePoint Services.

Following Figure shows the workflow architecture in Windows SharePoint Services. Windows SharePoint Services hosts the WF run-time engine within its process, and provides custom implementations of the necessary services. The functionality of the WF run-time engine, as well as the hosting functionality Windows SharePoint Services provides, is exposed through the Windows SharePoint Services object model.

Workflows: Workflows in WSS 3.0 and MOSS 2007


Workflow Templates and Instances
In Windows SharePoint Services, workflows that are available on a site or list are referred to as workflow templates; a workflow that is actually running on a specific SharePoint item is called a workflow instance. So, on a given list, several instances of the same workflow template may be running at the same time, each on a different SharePoint item. More than one workflow can be running on a given SharePoint item at a time.
Points of User Interaction with Workflows
Let's look more closely at the various stages at which users can interact with workflows in Windows SharePoint Services and SharePoint Server.

A. Association
Association occurs when a site administrator makes the workflow template available on a specific document library, list, or content type. At this stage, the site administrator customizes the workflow for this specific document library, list, or content type by specifying the following parameter information:

  • A unique name for the workflow
  • How the workflow is applied to a given item: either automatically when the item is created or changed, or manually; and which roles, such as Administrator or Contributor, can start a workflow
  • The Task list, in which the workflow can create tasks
  • The History list in which the workflow can store history events, as defined by the workflow

In addition, the workflow developer can enable the site administration to further customize the workflow by setting parameter information specific to the particular workflow. The administrator may have to specify parameters, default values, and other information for the workflow as it applies to items on the list, library, or content type with which the administrator is associating it.
Associating a workflow actually occurs outside the workflow itself; no workflow instance is actually started during association. Rather, Windows SharePoint Services stores the association information in a special internal workflow association table. Then, when the workflow instance is actually started, Windows SharePoint Services uses the association data (and the initiation data, if any) to set the parameters of the new workflow instance.

B. Initiation
Whereas association deals with the workflow as it applies to a specific list, library, or content type, initiation deals with the workflow as it applies to a specific SharePoint item.
Initiation occurs when a user actually starts a workflow instance on a specific item. The user supplies information custom to that specific workflow on that item, if necessary, and then starts the workflow.
Workflow developers can use initiation to let users override or append the association parameters set by administrators, or specify additional parameters or information about the workflow as it applies to the given SharePoint item. Not all workflows need initiation. In fact, a workflow set to start automatically cannot have initiation parameters.
The Windows SharePoint Services workflow project for the Visual Studio 2008 Designer for Windows Workflow Foundation includes an activity that acts as the event handler when the workflow is initiated. This activity is the first activity in any Windows SharePoint Services workflow.

C. Modification
Modifications enable users to alter the parameters or flow of a workflow instance as it is running. As a developer, you may have points in your workflow at which you would like to enable users to alter the workflow while it is running on an item. For example, you might want to enable a user to assign a task to another person, or even add a specific task to the workflow. The options you present to users to change the workflow as it is running on an item are called modifications.
The Windows SharePoint Services workflow project for the Visual Studio 2008 Designer for Windows Workflow Foundation includes an activity to enable a workflow modification, as well as an activity that acts as an event handler when a workflow modification is enabled.

D. Tasks
Workflow activities that are performed by people are represented as tasks in Windows SharePoint Services workflows.
As workflow author, you can specify the task schema. For example, the task listing could include the following:

  • Task title
  • Name of person to whom the task is assigned
  • Task status
  • Task priority
  • Task date due
  • A link to the referenced item

The user can then edit the task as necessary. The workflow instance is notified of changes to workflow tasks and can choose to respond to them as specified in the workflow.
The Windows SharePoint Services workflow project for the Visual Studio 2008 Designer for Windows Workflow Foundation includes activities that create, delete, and update tasks, as well as activities that act as event handlers when tasks are created, updated, or deleted.

Thursday, July 30, 2009

One webpart for Intranet, Extranet & Internet

Today, I came across with a scenario "One webpart for Intranet, Extranet & Internet".

Requirement: "The web part supports multiple data sources. All data sources are not common for Intranet, Extranet & Internet versions. Based on the version, we have to show only corresponding data sources."

Example:We have a news web part with following data sources support:
  • news pages from an intranet site which are created with a News content type.
  • current/local site collection which has pages of a particular content type (this content type is similar to News content type but with few more fields additional)
  • RSS Feed - This is generic RSS feed support. So, RSS defined in intranet, extranet or internet sites should be handled in similar manner. Ofcourse, RSS content xml format is not different than general RSS content xml format.
For INTRANET, News web part should show all the above data sources.
For INTERNET & EXTRANET, News web part should show the data sources mentioned in (b) and (c).
NOTE: The configuration should be hidden from end user who can see web part toolpane.

Solution:
Step1: Add a property in newswebpart.webpart file (this is an xml file) under ///
Step2: Add a browsable property in the web part C# file. Don't forget to set
WebBrowsable(false) for this property. This allows us to hide the configuration for data source support in web part toolpane.

Step3: Include a condition in web part tool pane display data sources based on the value of the property set.

Note: We can implement above in other ways also but I opted above to allow configuration from webpart xml file instead of modifying in the C# code or from web part toolpane.

Wednesday, July 29, 2009

Call JavaScript function from C#

Following describes the steps to call a javascript from C# code:
Let us assume that javascript function is residing in an external javascript file, then follow below steps:

Step1: Register the javascript file

this.Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "NewsWebPart.js", siteCollectionRootUrl + "_LAYOUTS/Monsanto/MPS/NewsWebPart/js/NewsWebPart.js");

You can check the syntax for RegisterClientScriptInclude in .NET API.

Step2: Create HTML Generic Control for script tag and add attribute values.
HtmlGenericControl inlineScript = new HtmlGenericControl("script");
inlineScript.Attributes.Add("type", "text/javascript");
inlineScript.Attributes.Add("language", "javascript");


Step3: Call the javascript function
inlineScript.InnerHtml = "MakeConnectionRotateRequest("
+ "'" + SourceUrl + "'");";


In the above, you can see the javascript call by including parameter values from C# variables.

Step4: Include the HTML Generic control in the page
this.Controls.Add(inlineScript);