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.