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;
                }
            }