Friday, August 13, 2010

How to access SharePoint User Profile from C# code

Step 1: Refer the following dlls in the code:

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;



Step 2: Create the instance of SPSite object:

using (SPSite ospSite=new SPSite("http://servername:portname")
{}

where http://servername:portname is your sharepoint application url.
Here we have used using to create the instance of SPSite since 'using' automatically disposes the object when the block gets finished.

Withing 'using' block , add the following codes:


Step 3: Create the instance of servercontext object:

ServerContext ospServerContext = ServerContext.GetContext(ospSite);


Step 4: Create the instance of userporfile object propertycollection object:

UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);
UserProfile ospUserProfile = ospUserProfileManager.GetUserProfile(UniqueId);
Microsoft.Office.Server.UserProfiles.PropertyCollection propColl = ospUserProfile.ProfileManager.PropertiesWithSection;

here uniqueid is the id by which each profile is recognized individually. Eacn user profile has a uniqueId many ny 5-2-1 id if it is an AD account or GUID.


Step 5: Check whether the USerprofile object is null or not

if (ospUserProfile != null && propColl != null)
{}

Step 6: Iterate thorugh all the proerties in property collection:

foreach (Property prop in propColl)
{}

In the for loop you can get the property name and value like this:

To get property name: prop.Name
To get property value: ospUserProfile[prop.Name].Value

To set a value to a proerty : ospUserProfile[prop.Name].Value ="SOME VALUE";

To save the user profile after updation: ospUserProfile.Commit();

This will get the userporfile of a user and update the profile.


The whole code is as follows:

using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server;
using System.IO;
using System.Data;
using Microsoft.Office.Server.UserProfiles;

namespace Program1
{

public static void Main(string args[])
{
using (SPSite ospSite = new SPSite(webApp))
{
try
{
ServerContext ospServerContext = ServerContext.GetContext(ospSite);
UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);
UserProfile ospUserProfile = ospUserProfileManager.GetUserProfile(uniqueId);
Microsoft.Office.Server.UserProfiles.PropertyCollection propColl = ospUserProfile.ProfileManager.PropertiesWithSection;

if (ospUserProfile != null && propColl != null)
{
foreach (Property prop in propColl)
{
Console.WriteLine("property Name : " + prop.Name);
Console.WriteLine("proerpty Value : " + ospUserProfile[prop.Name].Value);

//If updation is required
ospUserProfile[prop.Name].Value="SOME VALUE";

}
ospUserProfile.Commit();
}
}
catch(Exception ex){
Console.WriteLine(ex.Message);
}
}
}
}

How to set Item Level Permission in to Sharepoint List

SPList.RoleAssignments Property :
Gets the collection of role assignments for the list.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

SPRoleAssignment.RoleDefinitionBindings Property : Gets the collection of role definition bindings for the role assignment.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

SPPrincipal Class :
Represents a user or group that can be assigned permissions in Windows SharePoint Services to control security.
Namespace: Microsoft.SharePoint
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)

I have written a function that will take the following parameters:

1. string Site url
2. string Library name
3. string Old user name (format : <domainname>\<username>
4. string new user name (format : <domainname>\<username>

My whole intension of function is to revoke permission of the item from old user and assign it to new user. You may or may not require the new user parameter if you are only revoking access.

public static void SetItemPermission(string SitePath, string LibName, string OldUser, string NewUser)
{

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite WebApp = new SPSite(SitePath))
{
using (SPWeb Site = WebApp.OpenWeb())
{
SPList list = Site.Lists[LibName];
SPQuery newSPQuery = new SPQuery();
newSPQuery.Query = "<where><contains><fieldref name="\">" +
"<value type="\">" + OldUser + "</value>" + "</contains></where>";
try{
SPListItemCollection listItemCol = list.GetItems(newSPQuery);
if (listItemCol.Count > 0)
{
SPUser user = null, _newUser = null;
SPRoleAssignment role = null;
foreach (SPListItem item in listItemCol)
{
user = Site.Users[OldUser];
SPPrincipal principal = (SPPrincipal)user;
item.RoleAssignments.Remove(principal);
role = new SPRoleAssignment(NewUser, "", "", "");
role.RoleDefinitionBindings.Add(Site.RoleDefinitions["Contribute"]);
item.RoleAssignments.Add(role);
}
item.SystemUpdate(false);
}
}}catch(Exception ex){}
}
}
});


}
#endregion

How to check whether SPList exists in Sharepoint?

Sometimes we require to check whether SPList exists or not. There is no direct method to check for it. Instead we have to use try-catch block to catch the exception and to determine the list existence:

The code is:


using (SPSite ospSite = new SPSite("http://<servername>:<portname>"))
{
using (SPWeb ospWeb = ospSite.OpenWeb())
{
try
{
SPList ospList = ospWeb.Lists["ListName"];
if (ospList != null)
return true;
}
catch(Exception ex)
{
return false;
}
}
}


This code block creates an instance of SPList object. If ospList object is not null that is list is there so it returns true.
If list does not exists, an exception will be raised and false will be returned from catch block

How to get distinct value from CAML query

Many times, we face a challenge to get unique rows froma CAML query. The main problem is that CAML does not have any feature to get the distinct rows in one go.

Way Around:

We all know that CAML query returns SPListItemCollection and we can convert the outcome to data table also.
We can convert the resultant datatable to dataview and again convert the dataview to datatable by using ToTable and arguments :
Distinct = true
and column name

So..
suppose we have SPWeb object as 'web' so

DataTable DT= web.GetSiteData(qry);
DataView v = new DataView(tbl);
return v.ToTable(true, "Type");


This code snippets returns the distinct rows by comparing column name "Type".

How to use RunWithElevatedPrivileges in Sharepoint

The SPSecurity class provides a static method named RunWithElevatedPrivileges that enables code to execute as system code running under the identity of SHAREPOINT\system. This allows code to run in an escalated security context to perform actions as the system.

This method should be used with care and should not expose direct access to system resources, but rather should be used when you need to perform actions on behalf of the system. The method is simple. You can either create a delegate to a public void method or simply write code within an inline delegate.

The signature looks like the following:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Code runs as the "SharePoint\system" user
});


Note that :
Code running with the escalated privilege should use a new SPSite object for code running as the system and use the SPContext.Current property to access the actual calling user’s identity.

To modify WSS content under the System credentials, you need to create a new SPSite site collection that generates a new security context for objects referenced from the site, as in the following example. You cannot switch the security context of the SPSite once it has been created, but must instead create a new SPSite reference to switch user contexts. The following code uses the system credentials to add a list item using the profile data of the current Web user:

SPSecurity.RunWithElevatedPrivileges(
delegate() {
using (SPSite site = new SPSite(web.Site.ID)) {
using (SPWeb web2 = site.OpenWeb()) {
SPList theList = web2.Lists["visitors"];
SPListItem record = theList.Items.Add();
record["User"] = SPContext.Current.Web.CurrentUser;
record.Update();
}
}
);

How to add a SPGroup to a Site Collection- Sharepoint

Groups cannot directly be added to a site-they must be added to the site collection.
If you try to add a group to the site’s Groups collection, you get an exception stating, “You cannot add a group directly to the Groups collection. You can add a group to the SiteGroups collection.”

This situation occurs because the SPGroup is always created at the Site Collection level and assigned to the site. The following code is valid and adds the LitwareSecurityGroup to the site collection groups.

// Adds a new group to the site collection groups:
site.SiteGroups.Add("LitwareSecurityGroup", site.CurrentUser,site.CurrentUser, "A group to manage Litware Security");

However, this still does not associate the group with our site, nor would it be useful within the site without any permissions. To add the group to the site, create a new SPRoleAssignment by associating an SPRoleDefinition with the SPGroup, and then add that role assignment to the site, as in the following code sample:


SPGroup secGroup = site.SiteGroups["LitwareSecurityGroup"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(secGroup);
SPRoleDefinition roleDefinition = site.RoleDefinitions["Full Control"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
site.RoleAssignments.Add(roleAssignment);

How to get list of SPGroups in Sharepoint Site Collection

Sharepoint Gropus (or SPGroups) are never created in the context of the site-they are always created in the context of the site collection and assigned to a site.

We can get list of groups of a site by suing site.Groups


SPSite siteCollection = new SPSite("http://localhost/litware/sales/");
SPWeb site = siteCollection.OpenWeb();

foreach(SPGroup group in site.Groups){
Console.WriteLine(group.Name);
}

How to check whether a List is a Document Library?

Many times, we face a situation where we iterate through list collection. Now if we need to check whether a list is a SPDocumentLibrary or not, we can check it in very simple manner:

Suppose we need to display list of document libraries present in a site in a dropdown control named 'lstTargetLibrary', we will iterate through list collection and check for List type:


SPWeb site = SPContext.Current.Web;
foreach (SPList list in site.Lists) {
if (list is SPDocumentLibrary && !list.Hidden) {
SPDocumentLibrary docLib = (SPDocumentLibrary)list;

lstTargetLibrary.Items.Add(
new ListItem(docLib.Title, docLib.ID.ToString()));
}
}

How to Upload a File to a SharePoint Site from a Local Folder

This code sample will show how to upload a file from your local pc to Sharepoint site using object mode:

1. Create a project and import namespaces :

using System.IO;
using Microsoft.SharePoint;


2. The UploadFile funtion code:

public void UploadFile(string srcUrl, string destUrl)
{
if (! File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not exist",
srcUrl), "srcUrl");
}

SPWeb site = new SPSite(destUrl).OpenWeb();

FileStream fStream = File.OpenRead(srcUrl);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();

EnsureParentFolder(site, destUrl);
site.Files.Add(destUrl, contents);
}


The UploadFile method accepts two parameters. The srcUrl parameter specifies the path of the source location in the file system of the local computer, and the destUrl parameter specifies the absolute URL of the destination. A System.IO.FileStream object is used to read the source file into a byte array for use with the Add method of the SPFileCollection class.

To upload a file from a local folder on the same server that is running Windows SharePoint Services, you can use a System.IO.FileStream object instead. In this case, add a using directive for the System.IO namespace, in addition to directives for System and Microsoft.SharePoint. The following example uses the Click event handler to call an UploadFile method, which in turn calls the previously described EnsureParentFolder method.

How to delete a List from Sharepoint ?

This small code snippets will demonstrate how to delete a SPList from a sharepoint site.

To delete a list, you must specify the GUID of the list as the parameter for the Delete method. Use the ID property of the SPList class to find the GUID.

SPWeb mySite = SPContext.Current.Web;
SPListCollection lists = mySite.Lists;

SPList list = lists[ListName];
System.Guid listGuid = list.ID;

lists.Delete(listGuid);

Difference between Update and SystemUpdate in Sharepoint

We all know that whenever we add a list item or do some modification, we update the list. Here we have two options:

1. List.Update() and 2. List.SystemUpdate()

The main difference betwwen two is that,

List.Update() creates automatically new version of list item as Update method is called.


List.SystemUpdate() avoids SharePoint 2007 to change modified date and modifier fields. Argument false tells that no new versions are expected.

SystemUpdate takes an boolean argument that set whether new version need to be created or not.

Example using SystemUpdate() :

SPList list = web.Lists["myList"];
SPListItem item = list.Items[0];
item["myField"] = "my value";

item.SystemUpdate(false);
list.Update();