Wednesday, September 21, 2011

onTaskCreated activity do not fire

Recently I created parallel task approval workflow and I needed to use the onTaskCreated activity. Till that my workflow worked fine and since I added this activity to the project the workflow stopped working properly. I search for the solution on the Internet and it turns out that this is Microsoft bug and it seems to be permanent. More about it you can read here: http://support.microsoft.com/kb/970548

There are two ways how to achieve the same functionality.
First one is to create event receiver in the task list. Second one is to add Delay activity after CreateTask activity and then perform some code(Delay activity ensure that task will be created and you can work with them then).

I used event receiver to substitute the onTaskCreated activity. How I did it you can look here on my blog: http://david-row.blogspot.com/2011/09/how-to-create-workflow-history-event.html
Anyway even that Microsoft offers workaround, it will cause more work than just drag and drop activity to your workflow. Also you have divided one project to the two and sometime it can be really bothering to make some changes in them.

I also tried second way with Delay activity but it doesn't seems to be good solution. As I wrote above I was creating parallel task approval process and problem was that somebody could approve task when Delay activity was still running. This cause that approval this task was not registered by workflow. So if I would be sure that nobody would approve task for example in first hour I could use this solution. Even you can set timer job of the workflow on 1 minute it still doesn't seems to be good solution to me.

This is just my opinion and you can also read more on this blog: http://www.elumenotion.com/Blog/Lists/Posts/Post.aspx?ID=69

Ok then, I hope this can help somebody to choose which way to substitute onTaskCreated activity. Both solutions have their pros and cons... Maybe Microsoft will solve some bugs in next version of SharePoint :)

How to deploy SharePoint 2010 workflow

Once you are done with testing your workflow on test server you would probably need to deploy this workflow to bring it alive :)

First easy way (which wasn't work for me) is to create wsp package:

  • After you built your project, you can right click on the project in Visual Studio and choose Package option
  • Find wsp file in debug folder of your project (usually C:\Users\user1\Documents\Visual Studio 2010\Projects\MyWorflow\MyWorkflow\bin\Debug). If you want to you can rename MyWorflow.wsp to MyWorkflow.cab and look what VS did for you :)
  • Upload a new solution - Open solution gallery in browser (Site Actions->Site Settings->Under Galleries section choose Solutions) and upload wsp file you have just created. Do not forget activate solution.
  • By now you should see a new feature in Site collection features, but before adding workflow to your list you should check if a new assembly is installed otherwise workflow would be codeless :). You can find it here C:\Windows\assembly\. If the assembly file contain your dll everything is right. If there is not and if you are administrator you can drag and drop dll into assembly file or use gacutil to install dll.
  • Now you can add a new workflow to your list and you should see your workflow name in "Select a workflow template" box. In this point this technique stops work for me
Second way which saves me is little bit more complicated but not too much :)

Till now I don't know why the first method didn't work, but I have tried it with event receiver and it worked fine. Anyway is nice to know that SharePoint offers more than just one way to deploy solutions.
If anyone has experience with this do not hesitate to comment it ;)

View workflow history list

Maybe you would need to view or work with data from your workflow history and for this is useful to know where all logs are stored in SharePoint. Because this list is hidden you need to use way around. Each site where runs some workflow has own history log list.
The URL can look like this: http://[spServer]/[spSite]/Lists/Workflow%20History/[ViewName].aspx

Default view namey is AllItems. This view probably doesn't match your expectation because contain some columns with GUIDs and shows all items of each workflow.
I needed to view just this columns -  User ID, Date Occurred and Description so I have created a new view and used this view in URL.
This will provide you user friendly view but still doesn't solve problem with all items because usually you need to view just some particular items. Here is the method I have used in workflow to get link which shows you just particular item.


        /// <summary>
        /// Returns workflow history list URL and replace space with '%20'
        /// </summary>
        /// <returns>Returns workflow history list URL</returns>
        private string getWorkflowHistoryListUrl()
        {
            string url = this.spRootSite + this.workflowProperties.HistoryListUrl.Replace(" ", "%20");
            //Specify the view
            url += "/UserView.aspx?";
            //Column which contain ID of particular list item where workflow runs
            url += "FilterField1=Item&";
            //Item ID 
            url += "FilterValue1=" + this.workflowProperties.ItemId;


            return url;
        }

If you use better solution, please comment it ;)
At the end, do not forget that SharePoint deletes all records of canceled or completed workflows which are older than 60 days. If you would want to remain history list you can use this link for further information: http://technet.microsoft.com/en-us/library/ee662522.aspx

Hope it helps somebody...

How to create workflow history event

When you need to create a new workflow history event you can use one of these two functions
CreateHistoryEvent(Int32, Object, SPMember, String, String, String)
CreateHistoryEvent(SPWeb, Guid, Int32, SPMember, TimeSpan, String, String, String)

second one is static so do not misinterpret parameters as I did first time :)

To create history event via function is helpful when you don't work directly with workflow code and so you can't use logToHistoryList activity.
This can be helpful when onTaskCreated activity doesn't work for example.(It can happen when you use replicator activity to creates tasks.) Microsoft describe solution for this here: http://support.microsoft.com/kb/970548 Obviously it is bug but it wasn't solve yet.
In brief: You need to create event receiver for Task list and then you can create workflow history event for example.
Here is one way how to achieve this:


using (SPSite site = new SPSite("http://sharepointserver/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //Gets list where workflow runs
                    SPList workflowList = web.Lists["workflowList"];
                    //Loop through item in workflow list
                    foreach (SPListItem item in workflowList.Items)
                    {
                        //Find out which workflow item creates the task
                        if (properties.ListItem["Workflow Item ID"].ToString() == item["ID"].ToString())
                        {
                            try
                            {
                                //Log to the history list
                                //Use the foreach loop if there is just one workflow
                                //otherwise you should find correct workflow
                                foreach (SPWorkflow wf in item.Workflows)
                                {
                                    wf.CreateHistoryEvent((int)SPWorkflowHistoryEventType.TaskCreated, 0, wf.AuthorUser, "", "Task was succesfully assigned to.", "");
                                }
                                //Work is done. Get out from loops
                                return;
                            }
                            catch (Exception ex)
                            {
                                //Some exception handling 
                            }
                        }
                    }
                }
            }

Ok this is all. As I describe above this is just one of the ways how to write this code, so if you know better one do not hesitate to comment it. About bug with onTaskCreate activity I want to post later so this post is more focused on useful using of CreateHistoryEvent method.
Happy coding :)

Tuesday, September 20, 2011

Get SPUser from Person/Group field

This code snippet could help you easily gets the User from Person/Group field in SharePoint list.


SPFieldUserValue userField = (SPFieldUserValue)list.Fields["Assigned To"].GetFieldValue(item["Assigned To"].ToString());
SPUser user= userField.User;


If your requirements would be higher, have a look here:
http://david-rehak-sharepoint.blogspot.com/2011/11/how-to-get-spuser-or-spgroup-from.html



Happy coding ;)

Blank page - SP2010 Site settings

Few weeks ago I needed to develop something on the new SharePoint server. Everything looked fine and there was not any problem till I needed to open Site settings in browser. When I was trying to open it the blank page was viewed. There was not any content at all or error message and it looked to me really strange.
To solve this problem was quite simple. You should check Alternate Access Mapping in Central Administration and if the server name in your URL is not there you should rewrite it or add a new record to the Alternate Access Mapping. This was exactly my problem 'cause I used IP address in URL (like this http://10.251.27.150/SitePages/Home.aspx) and in the Alternate Access Mapping was just record about server name (like this http://newSPServer).
I am not SharePoint administrator but this could help somebody, I hope ;)

The Web application at http://server/ could not be found. - Error

When you create SharePoint console application or create webParts, you usually need to use SPSite class to operate with list, web, etc. Recently I got this exception message and it cause me a small headache to fix it.

The Web application at http://sharepointserver/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

Even this message looks like it shows you where the real problem is, the source can be actually somewhere else. I collected some information how to fix it so you can check it first before you will start search somewhere  ;)

1) Try to check if you typed correct server name as message recommend to you.

2) Check if you have set correctly your platform target in project properties

  • Open project properties (Right click on project -> Properties) -> In the left pane select Build folder -> and there select the Platform target to x64


3) Problem can be with alternate access mapping

  • (If you use SP2010) Open Central Administration -> Application Management -> Under Web Application section click on the Configure alternate access mapping
  • Check if Internal URL contain the URL you have used in your source code otherwise you can create a new record
4) Check if the user is farm server administrator

  • Open Central Administration -> Security -> Manage the farm administrators group -> And add the user there

If those steps would not help you can also check these points if the user

  • has Read and Write permissions on the content database
  • is site collection administrator
  • is in WSS_ADMIN_WPG group on the server
If the problem remain try to log as administrator and run your application. If it is work, probably the problem is with the user permission.

Ok then, this is all I found about this exception and I hope it can help somebody as it helps me :)