Friday, December 30, 2011

New blog

Hi everyone,
Recently I have created a new blog focused only on .NET. So since now all .NET stuffs will be available there ;)
http://david-rehak-dotnet.blogspot.com/
Enjoy it!

Tuesday, November 15, 2011

Http error 500.19 internal server error

One day my virtual machine crashed. When I started server again instead home page in browser I saw just this error message: Http error 500.19 internal server error
In this case the Microsoft help was really helpful (maybe first time and hope not for last time :-D ). It navigated me to the first support page http://support.microsoft.com/kb/943891 and then to the second page http://support.microsoft.com/kb/942055. There I read this possible solution: Delete the malformed XML element from the ApplicationHost.config file or from the Web.config file.
As it shows the problem was really with web.config file. For some reason data was unreadable and I had to use my back up of this file. Since than it works fine.
I also found some other recommendations on threads, but at first I would recommend to check applicationHost.config and web.config files first.
Hope it can help somebody who "google it" first as me :-D

Thursday, November 10, 2011

How to get item URL

This code snippet gets URL of each SPListItem in the list. PAGETYPE sets which form should be picked (edit, display, new form).

using (SPSite site = new SPSite("http://spserver/"))
           {
               using (SPWeb web = site.OpenWeb())
               {
                   SPList list = web.Lists["Orders"];
                   foreach (SPListItem item in list.Items) 
                   {
                       Console.WriteLine(web.Url + "/" +list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url + "?ID=" + item.ID);
                   }
               }
           }

SPBuiltInFieldId Class

This is very useful class which avoid you to write field name directly like this: item["Title"].ToString(). With SPBuiltInFieldId class you can write:   item[SPBuiltInFieldId.Title].ToString(). There are also IDs of other columns such are Created By, Modified By etc.
I cant say how many times I was thinking how to exactly write those columns so this class makes it easier :)
Here is the link to better understanding:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spbuiltinfieldid.aspx

Programmatically get URL to open InfoPath file in browser

If you want to open InfoPath you can not use URL and name to open it(for example: http://spserver/formsite/infopathlibrary/myform.xml) This approach is for saving document and browser shows you save dialog. If you want to open InfoPath in browser you need to change URL quite a bit. Let's have a look like URL look like when InfoPath form is already open in browser: http://spserver/formsite/infopathlibrary/_layouts/FormServer.aspx?XmlLocation=/formsite/infopathlibrary/myform.xml&Source=http%3A%2F%2Fspserver%2FCZ%2Fformsite%2Finfopathlibrary%2FForms%2FAllItems%2Easpx&DefaultItemOpen=1
As you can see now the URL is a bit longer, but still you can simplify it to this:
http://spserver/formsite/_layouts/FormServer.aspx?XmlLocation=formsite/infopathlibrary/myform.xml&DefaultItemOpen=1
This URL also open InfoPath directly in browser. Now lets have a look how code which would generate this URL would look like(code is used in workflow, but for something else would be similar):
string itemUrl = this.workflowProperties.Item.Web.Url;
            itemUrl += "/_layouts/FormServer.aspx?XmlLocation=" + this.workflowProperties.Item.File.ServerRelativeUrl;
            itemUrl += "&DefaultItemOpen=1";
            itemUrl = itemUrl.Replace(" ", "%20");

I guess there is nothing to describe here, maybe just last line with replacing. This line replace all spaces with %20. Reason is simple, some browsers can not convert this unsafe character (I would recommend to create function to convert URL to safe URL) - for better understanding have a look here: http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

Programmatically get site URL

I guess that connection to the SharePoint list is one of the most needed requirement. How to connect to the SharePoint list I already described here, but one of the important thing when connection to the SharePoint list is needed is site URL. Site URL can be typed directly to the source code, but I wouldn't recommend this approach. Reason is simple - Application, workflow, event receiver, etc. are usually deployed first at developing server and then on the test server and finally on the production server (this is one of the developing method). Whenever application is moved to another server the rebuilding is needed because of direct URL typing. Wouldn't be better if any other changes wouldn't be required when location of solution is changed? I guess yes :)
And this is the way how to do it in a case of SPSite:
SPSite site = new SPSite(this.workflowProperties.Site.Url + this.workflowProperties.Web.ServerRelativeUrl);

Please don't hesitate to comment any other location independent approaches ;)

Wednesday, November 9, 2011

Programmatically change workflow status to custom status

Sometimes values like In progress, Completed, etc. are not enough and don't match our demands. So I am going to simply describe how to change workflow status to some custom status.
At first Elements.xml file of workflow has to be changed and new custom states have to be added. Put this xml definition into <MetaData>.

<ExtendedStatusColumnValues>
        <StatusColumnValue>Waiting for your approving</StatusColumnValue>
        <StatusColumnValue>Approved and waiting</StatusColumnValue>
  </ExtendedStatusColumnValues>
Then add a new setState activity to workflow and set methodInvoking. The method should look like this:

private void setStateApprovedAndWaiting_MethodInvoking(object sender, EventArgs e)
        {
            this.setStateToApprovedAndWaiting.State = (int)SPWorkflowStatus.Max + 1;


        }

First item in <ExtendedStatusColumnValues> corresponds with  SPWorkflowStatus.Max, other values are available since the exact number is added to the SPWorkflowStatus.Max.

For better understanding read this articles:
http://msdn.microsoft.com/en-us/library/cc514224(office.12).aspx#MOSS2007DevWorkflowSolutions_SettingOutcomeValues

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.workflow.spworkflowstatus.aspx

That all look very nice and simple. Sadly for me my experience wasn't that much simple. If I wanted to use member of SPWorkflowStatus to set workflow status I got this error message: Specified argument was out of the range of valid values.Till know I don't know why. I also had some complex workflow and when I tried to set state to some of my custom states using function above the error occurred. When I set state directly in setState activity the custom state was set. So I would recommend to check and find ID of custom state and then use this number instead of setting state property in the function.
Maybe somebody also had the same problem and solve it, if so please don't hesitate to comment :)
Happy codding....

Tuesday, November 8, 2011

Programmatically create workflow history event

Sometimes is needed to create workflow history event. This code creates a new history event for each item in the list (the items which are associated with some workflow, of course :) ). This code is not useful at all I think :) so change the code according to your requirements.


using (SPSite site = new SPSite("http://spServer/"))
           {
               using (SPWeb web = site.OpenWeb())
               {
                   SPList list = web.Lists["Tasks"];


                   foreach (SPListItem item in list.Items)
                   {
                       foreach (SPWorkflow wf in item.Workflows)
                       {
                           //Log to the history list
                           wf.CreateHistoryEvent((int)SPWorkflowHistoryEventType.TaskCreated, 0, wf.AuthorUser, "", "Task was created.", "");
                       }
                   }
               }
           }


Happy codding ;)

Programmatically create a new SPRoleDefinition

The source of this useful code is here http://blogs.msdn.com/b/josrod/archive/2007/10/05/create-a-new-sharepoint-permission-level-and-bind-it-to-an-existing-sharepoint-group.aspx
I just wanted to have it on my blog to keep it easy to find :)


using (SPSite topLevelSite = new SPSite("http://davidrehak-vsrv/newrole/"))
            {
                using (SPWeb rootWeb = topLevelSite.OpenWeb())
                {
                    if (!rootWeb.IsRootWeb && !rootWeb.HasUniqueRoleDefinitions)
                        rootWeb.RoleDefinitions.BreakInheritance(true, false);


                    string permissionLevelName = "Davids role";


                    // Create a new Permission Level
                    SPRoleDefinition newPermissionLevel = new SPRoleDefinition();
                    newPermissionLevel.Name = permissionLevelName;
                    newPermissionLevel.Description = "David's Permission Level";
                    newPermissionLevel.BasePermissions =
                            SPBasePermissions.AddListItems |
                            SPBasePermissions.BrowseDirectories |
                            SPBasePermissions.EditListItems |
                            SPBasePermissions.DeleteListItems |
                            SPBasePermissions.AddDelPrivateWebParts;


                    // Add the permission level to web
                    rootWeb.RoleDefinitions.Add(newPermissionLevel);


                    // Bind to the permission level we just added
                    newPermissionLevel = rootWeb.RoleDefinitions[permissionLevelName];


                    // Create a new role Assignment using the SharePoint Group "Foo"
                    SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)rootWeb.SiteGroups["Foo"]);


                    // Add the Permission Level to the Foo SharePoint Group
                    roleAssignment.RoleDefinitionBindings.Add(newPermissionLevel);


                    // Add the new Role Assignment to the web
                    rootWeb.RoleAssignments.Add(roleAssignment);
                }
            }

Permission level cannot be found and multilanguage sharepoint

Ok there is the scenario: You want to create application which sets permission to the some user. To achieve your goal you can use SPRole class,  SPRoleDeffinition class and Web.RoleDefinitions property. If developing server is in English and production server in another language you probably get this error message "Permission level cannot be found." . The cause of this error is simple - If you need to get "Full Control" role definition for web, you just type SPRoleDefinition roleDef = web.RoleDefinitions["Full Control"];  and as you can see the name of role definition is in English and over my expectation the name is changed with language version :(

So how to solve this situation? (Please keep in mind, I didn't found any better solution so do not hesitate to comment it. I am always open to learn something new :) )

  1. You can write your code just for particular language version. 
    • I would create dictionary for each language version and check current language version (SPContext.Current.Web.Language)
  2. Get ID of SPRoleDefinition and use it instead of name
            using (SPSite site = new SPSite("http://serverName/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    for (int i = 0; i < web.RoleDefinitions.Count; i++ )
                    {
                        Console.WriteLine(web.RoleDefinitions[i].Name + " " + i);
                    }
                }
            }
I am sorry to everybody who tried the second solution. This really is not the way because the RoleDefinition ID can be different too. So as far as I know the only way to achieve this is the first point. Kind of bothering, isn't it?

That all I found so maybe it can be useful.... ;)

Wednesday, November 2, 2011

How to get SPUser or SPGroup from Person or Group field

Ok, here is the thing - you have person or group field in SharePoint list and you want to programmatically get the user or person.

This code snippet gets SPUser from User or Group field in the list when multiple choice and Groups are not allowed in the field:
//get SPUser
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
SPUser user = userFieldValue.User;


This part of code would help you to get SPUser when multiple choice is allowed and groups are not allowed:

//Multiple choices are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValueCollection userFieldValueCollection = (SPFieldUserValueCollection)userField.GetFieldValue(item["Users"].ToString());
foreach (SPFieldUserValue userFieldValue in userFieldValueCollection)
{
    Console.WriteLine("     " + userFieldValue.User.LoginName);
}


And when group is allowed  you can use this code(In this part I'm not quite sure about solution. I wrote it, It's working, but maybe there is better approach so if you know better do not hesitated to comment it :) ):

//Group or User are allowed
SPFieldUser userField = (SPFieldUser)item.Fields.GetField("Users");
SPFieldUserValue userFieldValue = (SPFieldUserValue)userField.GetFieldValue(item["Users"].ToString());
//Tries to get SPUser
if (userFieldValue.User != null)
{
   SPUser user = userFieldValue.User;
}
//if the field contain group
else
{
  SPGroup group = web.SiteGroups.GetByID(userFieldValue.LookupId);
}


Happy coding ;)

Tuesday, November 1, 2011

ListViewByQuery Control

Recently I needed to develop some cross site list view and this two links really helped me out of it.
Creating list view webpart:
http://brandingsharepointsites.wordpress.com/2011/07/29/display-sharepoint-list-view-or-document-library-view-from-different-site-collection/
Sorting, filtering and grouping functions:
http://karinebosch.wordpress.com/sharepoint-controls/the-listviewbyquery-control/

Thanks a lot :)

LCDI - Locale IDs Assigned by Microsoft

This site just contains list of Windows locale IDs:
http://msdn.microsoft.com/en-us/goglobal/bb964664

File or arguments not valid for site template or how to create site from web template

This short code snippet creates a new SharePoint site from site template:

using (SPSite site = new SPSite("http://spserver/"))
            {
                SPWeb web = site.OpenWeb();
                SPWebTemplateCollection Templates = site.GetCustomWebTemplates(web.Language);
                SPWebTemplate siteTemplate = Templates["mySiteTemplate.stp"];


                //Checks whether site requested is exist or not
                if (web.Webs["test"].Exists)
                {
                    web.Webs.Delete("test");
                }


                //Creates a new site
                web.Webs.Add("test", "This is test site", "", Convert.ToUInt32(web.Language), siteTemplate, true, false);
            }


If you would receive this error message: File or arguments not valid for site template "someTemplate"
You can check two things to fix this error:
The first one is to use correct function to get web templates from your site. If you would use GetWebTemplates(unit LCID) function you will get default site templates and if you need to use site template which you were created you should use GetCustomWebTemplates(unit LCID).
The second is to use correct site template name. Check this link to find out how to get the proper site template name.

Hope it helps ;)

Get correct SharePoint web template name

You can use this URL, if you would need to find out the name of your web template:
http://[server]/_layouts/templatepick.aspx
Just the [server] replace with your server name. Then view source code and the name you are looking for is value of "value" attribute inside "option" tag in the list box.

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 :)

Wednesday, August 17, 2011

IE throw this error message: You may be trying to access this site from a secured browser on the server. Please enable scripts and reload this page.

After you install Windows Server 2008 and SharePoint server 2010 your Internet Explorer (in my case it was IE8) may throw this error message after you try to open SharePoint site in it. Solution is quite easy, just go to the Start -> Administrative Tools -> Server Manager -> on the right side click on the Configure IE ESC -> Choose Off for Administrators and submit it
That should be all you need to do.

Thursday, August 11, 2011

How to programmatically ensure full permission to the list, document etc.

Sometimes we need to grant full permission to the list, library etc. even user has not access to that list. Let's imagine this situation. You have Site A with list "Orders" on it and also you have site B. On site B is web part which shows data in "Orders" list, but if user has no-permission to the Site A or "Orders" list you can't use code below because you wold get an error that user has no-permission to the site:

                   SPSite site = new SPSite("http://spsite/siteA");
                    SPWeb web = site.OpenWeb();
                    SPList list = web.Lists["Orders"];


                    foreach (SPItem i in list.Items)
                    {
                        someTable.Add(i["Name"].toString());
                    }

Solution for this is more than simple. All you have to do is use SPSecurity class and RunWithElevatedPrivileges method. This method will grant you full control rights. Using this method and code above would look like this:

                SPSecurity.RunWithElevatedPrivileges(delegate()
               {      

                    SPSite site = new SPSite("http://spsite/siteA");
                    SPWeb web = site.OpenWeb();
                    SPList list = web.Lists["Orders"];


                    foreach (SPItem i in list.Items)
                    {
                        someTable.Add(i["Name"].toString());
                    }
              });

Easy, isn't it? Here is the link to the source to get more informations: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx

Tuesday, August 9, 2011

"Object reference not set to an instance of an object." - working with SharPoint fields

When you somehow work with data in SharePoint list the important thing is that you should beware of empty fields.
This code seems to be ok and it would perfectly work until one of the "Name" fields wouldn't be empty:

                         foreach (SPListItem row in list.Items)
                        {
                            Console.WriteLine("Value of field is: {0}", row["Number"].ToString());
                        }
Problem is that SharePoint doesn't save empty field as empty string if you would create a new item and left "Number" field empty. So if there is no condition you would get this error:  Object reference not set to an instance of an object. because of the field which user didn't fill, the new instance of object wasn't created. (at least, it's what I think, but anybody who knows real reason can comment it ;) )
For me was the best practice to check every field which user isn't enforced to fill and could be empty.
You can use this code to check values:

                        foreach (SPListItem row in list.Items)
                        {
                            //Checks if "Number" field contain any data
                             if (row["Number"] != null)
                                Console.WriteLine("Value of field is: {0}", row[myLookupColumnName].ToString());
                        }


or another way how to treat empty field is to use try and catch block like this:

                        foreach (SPListItem row in list.Items)
                        {
                            //Tries to catch exception
                            try
                            {
                                Console.WriteLine("Value of field is: {0}", row[myLookupColumnName].ToString());
                            }
                            catch (NullReferenceException ex)
                            {
                                Console.WriteLine("The field was empty. Error: " + ex.Message);
                            }
                        }

If somebody use another way how to check data in field I would be glad to hear it :)
Happy coding
David

Friday, August 5, 2011

How to programmatically manipulate with Lookup field

Lookup field allows us to create relation between two lists, but this is not what I want to write about. Here is some source where you can find how to create Lookup field.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=574
More information about Lookup field you would find if you would search on the Internet.
But for now let's focus at programmatical part of lookup field.

Data in lookup field are represented as String. This String looks like this: ID;#FieldValue
You could write your own class to work with this field but why to code something if there is everything done already :)
We'll need to use SPFieldLookup, SPFieldLookupValue and SPFieldLookupValueCollection classes.
SPFieldLookup- represents a lookup field
SPFieldLookupValue - contains the value for an SPFieldLookup object
SPFieldLookupValueCollection - contains the values for an SPFieldLookup object that can contain multiple values

Ok then, it should be enough for the start and lets focus at implementation of this classes. As always you can choose some different ways how you will treat your lookup field.

  • If you know that the field is definitely type of Lookup and there is no Multiple selection checked and field is filled(is required field box checked), you can use this simple short code:
            //Open site
            using (SPSite site = new SPSite("http://MySharePointSite"))
            {
                //Open web
                using (SPWeb web = site.OpenWeb())
                {
                    //Get your list
                    SPList list = web.Lists["TestList"];
                   //Loop through all items in the list
                    foreach (SPListItem row in list.Items)
                    {
                        SPFieldLookupValue myLookup = new SPFieldLookupValue(row["MyLookUpColumn"].ToString());
                        Console.WriteLine("Id of my lookup is {0} and value is {1}.", myLookup.LookupId, myLookup.LookupValue);
                    }
                }
            }


  • In a case you use multiple selection, you would probably want to get all items in your lookup field. For that purpose you can use SPFieldLookupValueCollection class which will enable you to go through all items in your lookup field. Here is the code:


            //Open site
            using (SPSite site = new SPSite("http://MySharePointSite"))
            {
                //Open web
                using (SPWeb web = site.OpenWeb())
                {
                    //Get your list
                    SPList list = web.Lists["TestList"];
                    //Loop through all items in the list
                    foreach (SPListItem row in list.Items)
                    {
                        //Creates new SPFieldLookupValueCollection instance from our look up field
                        SPFieldLookupValueCollection myLookupCollection = new SPFieldLookupValueCollection(row["MyLookUpColumn"].ToString());
                        //Loop through all items in collection
                        foreach (SPFieldLookupValue myLookup in myLookupCollection)
                        {
                            Console.WriteLine("Id of my lookup is {0} and value is {1}.", myLookup.LookupId, myLookup.LookupValue);
                        }
                    }
                }
            }



  • What should you do if you don't know if your field is type of Lookup? Even here is simple solution because you can go through all fields in your list and check for particular dataType. Actually this doesn't involve just Lookup field because you can use it whenever you need to find out what data types are in your list. It is simple like this:


          //Open site
            using (SPSite site = new SPSite("http://MySharePointSite"))
            {
                //Open web
                using (SPWeb web = site.OpenWeb())
                {
                    //Get your list
                    SPList list = web.Lists["TestList"];
                    //Title of our lookup column
                    string myLookupColumnName = string.Empty;
                    //Name of field to check if it is type of lookup
                    string fieldToCheckForLookup = "TestLookup";
                    //Loop through all fields in list
                    foreach (SPField field in list.Fields)
                    {
                        //Find Lookup field type
                        if (field is SPFieldLookup)
                            if (field.Title == fieldToCheckForLookup)
                            {
                                //do something clever with our lookup field
                                Console.WriteLine("Our field is type of lookup.");
                                myLookupColumnName = field.Title;
                            }
                    }


                    if (myLookupColumnName != string.Empty)
                        foreach (SPListItem row in list.Items)
                        {
                            //Tries to get data from field
                            try
                            {
                                //Creates new SPFieldLookupValueCollection instance from our look up field
                                SPFieldLookupValueCollection myLookupCollection = new SPFieldLookupValueCollection(row[myLookupColumnName].ToString());
                                //Loop through all items in collection
                                foreach (SPFieldLookupValue myLookup in myLookupCollection)
                                {
                                    Console.WriteLine("Id of my lookup is {0} and value is {1}.", myLookup.LookupId, myLookup.LookupValue);
                                }
                            }
                            catch(Exception ex)
                            {
                                Console.WriteLine("An error occured: " + ex.Message);
                            }
                        }
                    else
                        Console.WriteLine("{0} field was not type of lookup.", fieldToCheckForLookup);
                }
            }


I think there is more ways how to work with lookup field but this definitely works for me :)
Ok, that should be all. If you would find it interesting or helpful I would be glad, but if there is something you don't agree with please comment it or let me know ;)
David

Thursday, August 4, 2011

Add, update and delete item from the SharePoint list

It certainly isn't anything new and everything you can find at Microsoft documentation, but I just wanted to group some often used pieces of code onto one place. So it's mostly my knowledge base :)

ADD ITEM
------------------------------------

            //Open site
            using (SPSite site = new SPSite("http://yourSPSite"))
            {
                //Open web
                using (SPWeb web = site.OpenWeb())
                {
                    //Get your list
                    SPList list = web.Lists["TitleOfYourList"];
                    SPListItem listItem;
                    //Add new item to the list
                    listItem = list.Items.Add();
                    //Fill values in a new item
                    listItem["Title"] = "New title";
                    //Save it
                    listItem.Update();
                }
            }


UPDATE ITEM
------------------------------------

            //Open site
            using (SPSite site = new SPSite("http://yourSPSite"))
            {
                //Open web
                using (SPWeb web = site.OpenWeb())
                {
                    //Get your list
                    SPList list = web.Lists["TitleOfYourList"];


                    foreach (SPListItem item in list.Items) 
                    {
                        if (item["Title"].ToString() == "YourTitleToUpdate") 
                        {
                            //Change something
                            item["Title"] = "YourNewTitle";
                            //Save it
                            item.Update();
                        }
                    }
                }
            }


DELETE ITEM
------------------------------------
This part is little bit tricky and maybe it will not look like as you are expecting.
If you would use foreach loop to go through your items you would see error message like this: Collection was modified; enumeration operation may not execute. because whenever item is deleted the number of items in foreach loop is changed.
If you would use for loop and count upward you wouldn't get error message but if you would want to delete all items from the list some items would be skipped and remained in the list.
You should use for loop and count downward then you will be able to delete all items or just item depending on your condition.


            //Open site
            using (SPSite site = new SPSite("http://yourSPSite"))
            {
                //Open web
                using (SPWeb web = site.OpenWeb())
                {
                    //Get your list
                    SPList list = web.Lists["TitleOfYourList"];


                    //Count downward to go through all items
                    for (int i = list.Items.Count - 1; i >= 0; i--)
                    {
                        //Delete just the items with title "Test"
                        if (list.Items[i].Title == "Test")
                        {
                            Console.WriteLine("Deleting " + list.Items[i].Title);
                            list.Items.Delete(i);
                        }
                    }
                }
            }


Happy coding ;)
David

Check if current user has permission level greater or equal to given value

Microsoft SharePoint 2007 is a little bit complicated with permissions. Roles are one important part about it. Roles define user's permission to the site or files. MS SharePoint contains five permission level by default(Full Control, Design, Contribute, Read, Limited Access). Also you can create your own groups and set them their permission level. I will not describe Microsoft SharePoint permission logic here because you can easily google it and you would found a lot of useful sources.
Here is the some for the start:
http://office.microsoft.com/en-us/windows-sharepoint-services-help/permission-levels-and-permissions-HA010100149.aspx
http://msdn.microsoft.com/en-us/library/ms252445(v=vs.80).aspx
http://office.microsoft.com/en-us/sharepoint-server-help/about-managing-sharepoint-groups-and-users-HA010021579.aspx

Let's imagine hypothetical project. You should create webPart which would view some data (data source is SP list somewhere) and that data should be editable for users who has at least Contribute permission level to the site. So whenever you render webPart you need to check user's permission level at first. This code should help you to check if the permission level of current user is greater or equal to another permission level.


bool isCurrentUserRolesGreaterOrEqualThan(string role)
        {
            //User's permission level
            bool limitedAccess = false;
            bool read = false;
            bool contribute = false;
            bool design = false;
            bool fullControl = false;
           
            //Current web
            SPWeb web = SPContext.Current.Web;
           
            //Gets all user's roles
            SPRoleDefinitionBindingCollection usersRoles = web.AllRolesForCurrentUser;
           
            //Role definitions to compare with user's roles
            SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions;


            //Checks user's permission level-Read, Contribute, Design, Full Control, and Limited Access
            if (usersRoles.Contains(roleDefinitions["Read"]))
                read = true;
            if (usersRoles.Contains(roleDefinitions["Contribute"]))
                contribute = true;
            if (usersRoles.Contains(roleDefinitions["Design"]))
                design = true;
            if (usersRoles.Contains(roleDefinitions["Full Control"]))
                fullControl = true;
            if (usersRoles.Contains(roleDefinitions["Limited Access"]))
                limitedAccess = true;


            //Compares given role with user's permission level
            if (role == "Limited Access")
                if (limitedAccess || read || contribute || design || fullControl)
                    return true;
            if(role == "Read")
                if (read || contribute || design || fullControl)
                    return true;
            if(role == "Contribute")
                if (contribute || design || fullControl)
                    return true;
            if(role == "Design")
                if (design || fullControl)
                    return true;
            if(role == "Full Control")
                if (fullControl)
                    return true;


            SPUser currentUser = web.CurrentUser;
            if (currentUser.IsSiteAdmin)
            {
                return true;
            }              


            return false;
        }

OK. And that's all :) I hope it could help somebody...
Happy coding
David

Microsoft SharePoint 2007 - Current user's groups

This isn't anything new, but maybe it could help someone. Sometimes your application requires to get membership of current user. In that case you could use code bellow.

            //searching result
            bool containsGroupName = false;


            //current context
            SPContext currentContext;
            try
            {
                //Gets the current context
                currentContext = SPContext.Current;
            }
            catch (InvalidOperationException)
            {
                currentContext = null;
            }
            if (currentContext != null && currentContext.Web.CurrentUser != null)
            {
                //loop through user's groups and comparing if some group contain required name
                SPGroupCollection usersGroups = currentContext.Web.CurrentUser.Groups;
                foreach (SPGroup group in usersGroups)
                {
                    if ("GroupToFind" == group.Name)
                        containsGroupName = true;
                }
            }

Friday, July 22, 2011

Update item inside onItemChanged Activity - Disable event firing

Sometimes you need to react on item changed event and maybe you want program some application logic then. But problem is when you want to update item inside onItemChanged activity, probably you would do something like that (or maybe just I did it at first time :) )


workflowProperties.Item["Title"] = "Title was changed";
workflowProperties.Item.Update();

This particular code would seems to work fine but new onItemChange event is fired over and over. And it really isn't good solution I think. If you don't want to save just simple string like I did above. And if you want to interact with some particular changes in item, it would probably cause some mess with your application logic because of executing onItemChanged code.

You could easily use SystemUpdate() function to prevent event firing
workflowProperties.Item.SystemUpdate();
but unlucky for me it doesn't work at all.

As always there is another solution to achieve this. You can make your own Event firing class to disable event firing.

namespace CustomNamespace
{
public class EventFiringOperations : SPItemEventReceiver
{
  public EventFiringOperations()
  {
  }


  public void disableEventFiring()
  {
    //Obsolete way
    //this.DisableEventFiring();
    //Better (VS2010) (Visual studio would tell you for sure ;) )
    this.EventFiringEnabled = false;
  }


  public void enableEventFiring()
  {
    //Obsolete
    //this.EnableEventFiring();
    //Better
    this.EventFiringEnabled = false;
  }
}


public class CustomClass
{
  //...
  EventFiringOperations eventFiring = new EventFiringOperations();
  eventFiring.disableEventFiring();
  item.Update();     //Now you can update :)
  eventFiring.enableEventFiring();
  //...
}
}

This won't help you only if you will update item inside onItemChanged activity code, but whenever you don't want to fire event when you updating item.
I have posted it here more for my benefit, but if anyone finds it useful then great.

Loop inside workflow doesn't execute a changed code

Recently I was solving this issue:
Simply I have two parallel while loops. Both use the same condition. First loop contain just onWorkflowItemChanged and second one contain code block after logToHistoryListActivity and then delayActivity.
When I deploy and run workflow everything seems work fine but when I change code at first time is used the new code (let's say I just comment part which write something to the list) but every other loop is different and and old code is executed (even I comment that part).

This problem takes me while to solve, but solution is very easy.
Everything what you need to do is reset time service. Here are commands to do that: 
SharePoint 2007: net stop SPTimerV3 / net start SPTimerV3
SharePoint 2003: net stop SPTimer / net start SPTimer
SharePoint 2010: net stop SPTimerV4 net start SPTimerV4

The reason why old error is executed is that DelayActivity hibernates workflow and sets a new timer job. But when I changed the code the old time job was executed. That is reason why you should reset time service and "delete" old timer jobs to prevent them occurring again.

Hope this helps somebody ;)

STSADM commands to install WSP file

Everyone who works with MS SharePoint need from time to time work with WSP files. Here are some useful STSADM commands.
The location of STSADM depend on your installation, but usually you can find it here: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN
-----------------------------------------
1. Add the solution
stsadm -o addsolution -filename {WSPFILENAME}
2. Deploy the solution
stsadm -o deploysolution -name {WSPFILENAME} -url {SITEURL}
3. Install the feature
stsadm -o installfeature -filename {FeatureFolder}\feature.xml
4. Activate the feature
stsadm -o activatefeature -id {FEATUREID} -url {SITEURL} -force
5. Deactive the feature
Stsadm.exe -o deactivatefeature -filename “C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\{YourFeatureName}\feature.xml” -url http://servername/
6.Uninstall the feature
stsadm -o uninstallfeature -filename
7.Retract Solution
stsadm -o retractsolution -name [-url] [-allcontenturls] [-time] [-immediate]
8.Delete Solution
stsadm -o deletesolution -name
9.Upgrade Solution
stsadm -o upgradesolution -name [solutionName] -filename [fullPathToTheSolution] -immediate -allowgacdeployment


-----------------------------------------
Source:
http://littletalk.wordpress.com/2008/12/16/steps-to-install-wsp-file-in-stsadm/
For more information review:
http://technet.microsoft.com/en-us/library/cc262643(v=office.12)