Wednesday, 5 September 2012

Add the user to a Group

SPSite site = new SPSite(@"http://madhanpc:8089");
        SPWeb web = site.OpenWeb();
        web.AllowUnsafeUpdates = true;
        //Get the group that we want to add the user
        SPGroup grp = web.Groups["Viewers"];
        try
        {
            //Get the user that we want to add to the group
            SPUser usr = web.AllUsers[@"madhanpc\emp1"];
            //Now we add the user to the group collection and update
            grp.AddUser(usr);
            grp.Update();
            Response.Write("User is added successfully..");
        }
        catch (Exception ex)
        {
            Response.Write("User is not added " + ex.Message);
        }

Display Document Libraries

      SPSite siteCollection = new SPSite("Http://Mohan");
        SPWebCollection sites = siteCollection.AllWebs;
        foreach (SPWeb site in sites)
        {
            //SPListCollection:- object that represents the collection of lists in a site
            SPListCollection lists = site.Lists;
            foreach (SPList list in lists)
            {
                if (list.BaseType == SPBaseType.DocumentLibrary)
                {
                    //SPDocumentLibrary:- Represents a document library in Windows SharePoint Services. displays the name of the site and list, as well as the file name, for each item in every document library.
                    SPDocumentLibrary docLibrary = (SPDocumentLibrary)list;
                    if (!docLibrary.IsCatalog && list.BaseTemplate != SPListTemplateType.XMLForm)
                    {
                        //SPListItemCollection :- Represents a collection of SPListItem objects. To return the collection of items for a list or document library
                        SPListItemCollection docLibItems = docLibrary.Items;
                        foreach (SPListItem docLibItem in docLibItems)
                        {
                            Label1.Text += docLibItem.Name + "<br>";
                            //Label1.Text +=  " Docuement title -- " + docLibItem["Title"] + "<BR>";
                        }
                    }
                }
            }
        }

Adding Item to a task list

//Adding the items to task(Custome task list earliar created)list
        SPSite rootSite = new SPSite("Http://Mohan/site1");
        SPWeb web = rootSite.OpenWeb();
        //Security setting that allows you to add to / modify the site
        web.AllowUnsafeUpdates = true;
        SPList taskList = web.Lists["Custom Task List"];
        //Adding new task
        SPListItem newTask = taskList.Items.Add();
        newTask["Title"] = "Work on SPS 2010/13";
        newTask["PercentComplete"] = 0.1;
        newTask.Update();
        Response.Write("items manupulation completed..");

Creating the Task List

        //Adding new list -- taking the task list as template and creating new list item
        // Create site1 and implement
        SPSite rootSite = new SPSite("Http://Mohan/Asite");
        SPWeb web = rootSite.OpenWeb();
        //Security setting that allows you to add to / modify the site
        web.AllowUnsafeUpdates = true;
        SPListTemplate sourceTemplate = web.ListTemplates["Tasks"];
        Guid newListGuid = web.Lists.Add("Custom Task List", "Custom Task List", sourceTemplate);
        SPList newList = web.Lists[newListGuid];
        newList.Description = "Modified Custom Task List";
        newList.Update();
        Response.Write("Is added succes fully..");

Accessing List Item Values

//Accessing List Item Values
        //Create one site and a task with some items
        SPSite rootSite = new SPSite("Http://Mohan");
        SPWeb web = rootSite.AllWebs["Site1"];
        //SPList :- Represents a list on a SharePoint Web site.
        SPList taskList = web.Lists["task1"];
        //SPListItem :- Represents an item or row in a list. 
        foreach (SPListItem item in taskList.Items)
        {
            Response.Write("Item Name " + item.Name + "Assigner To " + item["AssignedTo"] + "Due Date " + item["DueDate"] + "<br>");
        }
        //Create one links item and add no items for test
        SPList lst = web.Lists["Links1"];
        foreach (SPListItem item1 in lst.Items)
        {
            Response.Write("Url Name " +  item1.Name + "<br>");
        }

Get all Users, Groups and Roles from SharePoint

First :
Get all users, groups, roles from SharePoint.

Second:
When the users exist in you selected SPWeb object, all specific information should me inserted into generic class UserListCollection.

Third :
Example class below shows the algorithms, how you get the user information from ArrayList object and cast the object into UserListCollection.


using System;
using System.Collections;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Framework.Business.Components
{ 
            /// <summary>
            /// UsersCollection is object to get all users by selected web object.
            /// </summary> 
            public class UsersCollection
            {
                        private ArrayList    _usersListCollection;   //All incomming users.
                        private SPWeb       _selectedWeb;           //Web position.
                        private string         _groupName;            //Group name.
  
                        private const string _allGroups  = "ALL_GROUPS";

                        /// <summary>
                        /// SPWebLocation property.
                        /// </summary>
                        public SPWeb SPWebLocation
                        {
                                   get{return _selectedWeb;}
                                   set{_selectedWeb = value;}
                        }

                        /// <summary>
                        /// SPGroupName property.
                        /// </summary>
                        public string SPGroupName
                        {
                                   get{return _groupName;}
                                   set{_groupName = value;}
                        }

                        /// <summary>
                        /// To run the example you need to initialize the UsersCollection object with two instance website and GroupName objects.
                        /// </summary>
                        /// <param name="webSite">SPWeb object</param>
                        /// <param name="groupName">string group name</param>
                        public UsersCollection(SPWeb webSite ,string groupName)
                        {    
                                   //Check if the SPWeb object is not null.
                                   if(webSite != null)
                                   {
                                               if(groupName == null || groupName.Length == 0)
                                               {     
                                                           this.SPGroupName = _allGroups;
                                               }
                                               _usersListCollection = new ArrayList();

                                   }
                                   else
                                   {
                                               Console.WriteLine("ERROR WEB LOCATION: Your web location have a null value.");
                                   }
                        }

                        /// <summary>
                        /// This public method get all users from SharePoint web location and get user related information.
                        /// </summary>
                        public ArrayList GetUsersByGroup()
                        {
                                   if(this.SPGroupName == _allGroups)
                                   {
                                               foreach(SPGroup singleGroup in this.SPWebLocation.Groups)
                                               {
                                                           UsersList(singleGroup);
                                               }
                                   }
                                   else
                                   {
                                               SPGroup singleGroup = this.SearchGroup(this._groupName);
                                               if(singleGroup != null)
                                               {
                                                           this.UsersList(singleGroup);
                                               }
                                               else
                                               {
                                                           Console.WriteLine("ERROR WEB GROUP: " +  this._groupName + " GROUP NOT EXIST.");
                                               }
                                   }
                                   return _usersListCollection;
                        }

                        /// <summary>
                        /// This private method get users by selected SPGroup object.
                        /// </summary>
                        /// <param name="group">SPGroup object</param>
                        private void UsersList(SPGroup group)
                        {
                                   foreach(SPUser singleUser in group.Users)
                                   {
                                               foreach(SPRole singleRole in singleUser.Roles)
                                               {
                                                           _usersListCollection.Add(new UserListCollection(
                                                               singleUser.LoginName,singleRole.Name,group.ParentWeb.Title));
                                               }
                                   }
                        }

                        /// <summary>
                        /// This method search for SPGroup name.
                        /// </summary>
                        /// <param name="group">string</param>
                        /// <returns>SPGroup object</returns>
                        private SPGroup SearchGroup(string group)
                        {
                                   SPGroup groupObject = null;
                                   foreach(SPGroup singleGroup in this.SPWebLocation.Groups)
                                   {
                                               if(group == singleGroup.Name)
                                               {
                                                           groupObject = singleGroup;
                                               }
                                   }
                                   return groupObject;
                        }
            }
   
            /// <summary>
            /// Generic class UserListCollection
            /// </summary> 
            public class UserListCollection
            {
                        private string _userName = "";
                        private string _userRole = "";
                        private string _userWeb = "";

                        /// <summary>
                        /// Generic username.
                        /// </summary>
                        public string UserName
                        {
                                   get { return _userName; }
                                   set { _userName = value; }
                        }


                        /// <summary>
                        /// Generic user role.
                        /// </summary>
                        public string UserRole
                        {
                                   get { return _userRole; }
                                   set { _userRole = value; }
                        }

                        /// <summary>
                        /// Generic SharePoint web name.
                        /// </summary>
                        public string WebName
                        {
                                   get { return _userWeb; }
                                   set { _userWeb = value; }
                        }

                        /// <summary>
                        /// This constructor insert three values.
                        /// </summary>
                        /// <param name="userName">Name of NT user account.</param>
                        /// <param name="userGroup">SharePoint web group name.</param>
                        /// <param name="userWeb">SPSite web name.</param>
                        public UserListCollection(string userName, string userGroup, string userWeb)
                        {
                                   this.UserName   = userName;
                                   this.UserRole     = userGroup;
                                   this.WebName   = userWeb;
                        }
            }

            /// <summary>
            /// Example to run UsersCollection class.
            /// </summary>
            class Example
            {
                        /// <summary>
                        /// Example to get all users info with generic UsersCollection class.
                        /// </summary>
                        public static void GetUsers()
                        {
                                   //Url location object.
                                   Uri url = new Uri("http://localserver/");

                                   SPGlobalAdmin globalAdmin = new SPGlobalAdmin();
                                   SPVirtualServer  virtualServer = globalAdmin.OpenVirtualServer(url);

                                   //Get all users by site position and group.
                                   UsersCollection user = new UsersCollection(
                                               virtualServer.Sites[0].AllWebs[0],"Reader");

                                   ArrayList usersArray = user.GetUsersByGroup();
                                   for(int i = 0;i < usersArray.Count;i++)
                                   {
                                               //Generic class
                                               UserListCollection userExample = (UserListCollection)usersArray[i];
                                               Console.WriteLine("UserName: " + userExample.UserName);
                                               Console.WriteLine("Role: " + userExample.UserRole);
                                               Console.WriteLine("Web: " + userExample.WebName);
                                   }
                        }
            }
}