Thursday, December 17, 2009

Custom EnsureUser function

The functionality of web.EnsureUser("login name") function is to resolve the user from the sharepoint site. But there might be a case where the login name you are passsing as a parameter, which does not exist in the site, then it will give you a run time error.

But this function will work like a brilliant. It will check the user and if does not exist then add that to "Home Owners" group. You can specify your own group name also.

public SPUser CustomEnsureUser(string fullName,SPWeb web)
SPPrincipalInfo objInfo = SPUtility.ResolvePrincipal(web, fullName, SPPrincipalType.SecurityGroup | SPPrincipalType.User, SPPrincipalSource.All, null, false);
if objInfo == null)
throw new SPException(SPResource.GetString("User could not be found", new object[]{objInfo.LoginName}));

if (objInfo.PrincipalId < 0) { web.Groups["Home Owners"].AddUser(objInfo.LoginName, objInfo.Email, objInfo.DisplayName, string.Empty); } return web.SiteUsers[objInfo.LoginName]; }

Wednesday, December 16, 2009

How to open SharePoint Group easily in Out-Of-Box functionality.

Suppose you are creating a application ,where you are creating sharepoint custom groups day by day. After some days, suppose there are 5000 custom sharepoint groups and you need to Modify settings/update users/delete users in a specific group. Then how can you go to that group easily ?

Step 1.Where ever you will see that group,just right click on that and click properties and get address url like:


Step 2: Take the sel value(i.e 17637) and Type the url as the below example:

Then you will reach that Group direcltly.

Try it out and enjoy !

Monday, December 14, 2009

Copy a folder from one list to another list programmatically.

using (SPSite site = new SPSite("http://testserver/spsite"))
using (SPWeb web = site.OpenWeb())
string sourceListUrl = "CustomList1/";
string destinationListUrl = "CustomList2/";

SPFolder rootFolder = web.GetFolder(sourceListUrl);
foreach (SPFolder objRootSubFolder in rootFolder.SubFolders)
if (objRootSubFolder.Name != "Forms")
folder = web.GetFolder(objRootSubFolder.ServerRelativeUrl);
foreach (SPFolder objFolder in folder.SubFolders)
objFolder.CopyTo(destinationListUrl + objRootSubFolder.Name + "/" + objFolder.Name);

foreach (SPFile objFile in folder.Files)
objFile.CopyTo(destinationListUrl + objRootSubFolder.Name + "/" + objFile.Name);

Delete all site groups programmatically.

using (SPSite spSite = new SPSite("http://testserver/spsite"))
using (SPWeb spWeb = spSite.OpenWeb())
SPGroupCollection objCol = spWeb.SiteGroups;

for (int count = 0; count <= objCol.Count - 1; count++)

Delete all the items from a custom list or a document library.

using (SPSite spSite = new SPSite("http://testserver/spsite"))
using (SPWeb spWeb = spSite.OpenWeb())
SPList objLst = spWeb.Lists["List Name"];
SPListItemCollection objCol = objLst.Items;

for (int count = 0; count <= objCol.Count - 1; count++) { objLst.Items.Delete(0); } } } });

Updating a list item by avoiding unnecessary call to event receiver.

If there is custom list and a event receiver[For creating/updating list item] is binded to that, then suppose we want to update the list without calling to the event receiver, then we have to disable the event firing and call the SystemUpdate() function instead of Update() function. Below here is the example in 2 steps:

Step 1:

class UpdateList: SPItemEventReceiver

Step 2:

SPListitem listItem = lst.Items.Add();
listItem["Title"] = "Samarendra Swain";
listItem["Company"] = "Manuh Solutions";


Fetching SPList object properly.

When ever we need to access a Custom List or a Document Library , we normally write like:

SPList lst = web.Lists["List Name"];

But this is a performance killer. So avoid this and modify the code to:

SPList lst = web.GetList("http://testServer/Lists/ListName");

Proper Use of AllowUnsafeUpdates property.

Normally if we do not need to set the AllowUnsafeUpdates property to true in case of windows application. But if you are calling the SharePoint API in web based application then we need to set the AllowUnsafeUpdates property to true before creating/updating anything(e.g. creating/updating list item in a list).

Suppose there is assignment to create a list item and bind custom permission to that list item, then we normally write BL like:

web.AllowUnsafeUpdate = true;

SPLIstItem lstItem = list.Items.Add();
lstItem["Title"] = "Samarendra Swain";

Then with the return listitem object, we write BL to bind the role defination to the list item.


SPRoleDefinitionCollection objWebRoleDefn = oSPWeb.RoleDefinitions;
SPRoleAssignment objRoleAssign = new SPRoleAssignment(objSPGroup);

objRoleAssign.RoleDefinitionBindings.Add(objWebRoleDefn["Full Control"]);

If you will run this, then you will get a run time error because of the AllowUnsafeUpdates property value set to false.

So,if you are writing lstitem.BreakRoleInheritance(false); then it makes the AllowUnsafeUpdates property value to false , so that after writing that line, you have to write again web.AllowUnsafeUpdate = true;

Then your code will run successfiully.

Tuesday, October 13, 2009

Getting QueryString Parameters with JavaScript in SharePoint

To get the query string parameter in a sharepoint page using javascript, below is the code snippet.

// call the EnsureSetup method

// get the querystring parameter named empid e.g ...\test.aspx?empid=55&empname=sam
var empid = JSRequest.QueryString["empid"];
var empname = JSRequest.QueryString["empname"];

Output : empid = 55 and empname = Sam

Author: Samarendra Swain

Wednesday, September 30, 2009

Display the matching results in People Picker Control by clicking on check names link

You will find a function EntityEditorCallback(result,ctx,preventAutoPostBack) in core.js file. At the last line of the function, just call this function: onClickRw(true,false);

what ever you write in People Picker Control, It will display the matching results by clicking on Check Names link Or by pressing enter key.

No need to again click on that text and see the matching results.

-samarendra swain

Thursday, September 24, 2009

Delete a sharepoint group programmatically ?

To delete a sharepoint group using object model, below is the code snippet in c#.

// objSPWeb is SPWeb object

Update the List item permission programmatically

Suppose if you have already bind a sharepoint group to a list item in a custom list/library for integrating permission then later on , if you want to modify the permission for that list item, below is the code snippet to achive it.

SPRoleAssignment objRoleAssignment = objListItem.RoleAssignments.GetAssignmentByPrincipal(objSPGroup);
objRoleAssignment.RoleDefinitionBindings.Remove(web.RoleDefinitions["Full Control"]);

Samarendra Swain

Thursday, August 27, 2009

How to get the users of a Active Directory group in SharePoint.

While adding a new user to a SharePoint group, you can enter Active Directory group name, so that all the users inside the AD group can access the SharePoint site, which is completely a out-of-box functionality in SharePoint. But there might be requirement where we need to access users of a specific AD group independently to perform some action against each of them.

Below is the code snippet in c# to acces each users details of a specific Active Directory group.

NameSpace: using Microsoft.SharePoint.Utilities;

bool reachMaxCount;

// objSPWeb is the SPWeb object
SPPrincipalInfo[] adGroupUsers = SPUtility.GetPrincipalsInGroup(objSPWeb, "DomainName\\GroupName", 100, out reachMaxCount);

foreach (SPPrincipalInfo objAdUserInfo in adGroupUsers)
      string loginName = objAdUserInfo.LoginName;
      string displayName = objAdUserInfo.DisplayName;
      string emailId = objAdUserInfo.Email;

**************Fetch the AD users using LDAP**************

public void GetADUsersInADGroup(string domainName,string groupName)


string userNames = "Users : " + Environment.NewLine;

string anyADUserID = "samarendra";

string anyADUserPassword = "password";
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domainName, anyADUserID, anyADUserPassword);

DirectorySearcher dSearch = new DirectorySearcher(entry);

dSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";

SearchResult results = dSearch.FindOne();
if (results != null)

DirectoryEntry objGroup = new DirectoryEntry(results.Path, anyADUserID, anyADUserPassword, AuthenticationTypes.Secure);

System.DirectoryServices.PropertyCollection pcoll = objGroup.Properties;

for (int count = 0; count < pcoll["member"].Count; count++)


DirectoryEntry deUser = new DirectoryEntry("LDAP://" + domainName + "/" + pcoll["member"][count].ToString(), anyADUserID, anyADUserPassword, AuthenticationTypes.Secure);

userNames += deUser.Properties["cn"].Value + Environment.NewLine; // cn is for login Name





Samarendra Swain

Wednesday, August 26, 2009

Adding/Customize action menu in SharePoint

A common requirement that every Sharepoint developer is asked for today is customization of the SharePoint site based on various customer specific requirements. Most often customers have requirements where they want to add some additional features to action menus like Site action menu, ECB menu or List/library Action menu, etc. To achieve this, we have to write custom action in XML and consume it within the site as a new feature. In Sharepoint if we need to integrate new feature for a List / Library, we can achieve this easily by creating a custom action feature.

1. Create a folder named TestCustomAction under C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES directory.

2. Next, create a file named Feature.xml in the same folder with the following codes.

Enlarge the image

3. Next, create another file, TestCustomActions.xml in the same folder with the following codes.

Enlarge the image

4. Create a page named TestCustomActions.aspx under layouts folder and add your own Business Logic.

5. Finally, deploy this feature by running the command in the command prompt.

To activate this feature: stsadm -o installfeature -filename TestCustomAction\feature.xml -url http://TestServer/Site.

Finally to see the changes in the site do an iisreset.

See here also:Adding/Customizing action menu in SharePoint

Samarendra Swain

Tuesday, August 25, 2009

Create custom property in a web part as a dropdown list

SharePoint allows you to create custom web parts to help you provide highly customized solutions to your clients/users. The properties of these web parts are added by default but to further customize the solution, you can also create custom properties. The following example demonstrates how to add a custom dropdown property to a custom webpart.
// Create a Enum for Languages

public enum LanguageByEnum

English = 0,

// Create Get/Set for the dropdown property

protected LanguageByEnum languageName;

Category("Select Language"),
WebBrowsable, WebDisplayName("Select language:")]
public LanguageByEnum SelectedLanguage
get { return languageName; }
set { languageName = value; }

I have written the same here also:Create custom property in a web part as a dropdown list

Samarendra Swain

Create SharePoint Web Application Programmatically

Generally web applications in SharePoint are created using the out-of-box functionality provided within Central Administration. But because of some client's needs there might be a requirement of creating these web applications within a custom utility solution. This functionality can be achieved programmatically using Microsoft SharePoint APIs. By this, one can easily create a web application & associate a content database to it, register the web application in the IIS server, create an associated application pool and define different credentials for the web aplication.

Example code using C#.Net

// namespace required
using System.IO;
using Microsoft.SharePoint.Administration;

// Create new object of SPWebApplication & SPWebApplicationBuilder class
SPWebApplication newApplication;
SPWebApplicationBuilder webAppBuilder = new SPWebApplicationBuilder(SPFarm.Local);

// Set necessary values to webAppBuilder object

webAppBuilder.Port = portNo;
webAppBuilder.RootDirectory = new DirectoryInfo(@"D:\projects\TestWebSite3030");
webAppBuilder.ApplicationPoolId = appPoolId;
webAppBuilder.ApplicationPoolUsername = appPoolUserName;
webAppBuilder.ApplicationPoolPassword = password;
webAppBuilder.CreateNewDatabase = true;
webAppBuilder.DatabaseServer = dbServerName; // DB server name
webAppBuilder.DatabaseName = dbName;// DB Name
if (isSQLAuth)
webAppBuilder.DatabaseUsername = dbUid; // dbUid is username of the DB sever
webAppBuilder.DatabasePassword = dbPwd; // dbpassword is password of the DB sever
webAppBuilder.UseNTLMExclusively = true; // authentication provider for NTLM
webAppBuilder.AllowAnonymousAccess = isAnonymous; // anonymous access permission

// Finally create web application
newApplication = webAppBuilder.Create();

I have written the same here also:Create SharePoint Web Application Programmatically

Samarendra Swain

Enable publishing feature programmatically in MOSS 2007 site

In SharePoint, integrating publishing feature is possible only in MOSS 2007 site and not in WSS site.By turning on publishing feature you can use Web Content Management(WCM) feature in the site.Once the WCM feature is enabled you can then brand the site with your custom look and feel and can also enable the multilingual support in the site. The multilingual feature helps in creating different folder-based sites according to the languages set to the site.

While creating a site collection or site & workspaces using SharePoint API , you can add these two lines code to enable the publishing feature.Provided below is an example using C# for enabling publishing feature at site collection level.

Code in C#

// Turn on publishing feature
// objSiteCollection is the Site Collection object

// Make the necessary changes to the local server to use the feature

I have written the same here also:Enable publishing feature programmatically in MOSS 2007 site

Samarendra Swain

Monday, August 24, 2009

Programmatically assign specific permission in SharePoint

SharePoint site security helps manage permissions for different resources within a site by defining the levels of accessibility permissions for different peoples and groups. In SharePoint, always the top-level or the parent level permissions are inherited to it's child contents (e.g. a sub-site inheriting permissions from it's parent site collection).

In-order to create unique permission we need to break the inheriting parent permission and create new permission level for the SharePoint content. These permissions can be defined for specific users or groups.

Provided below is an example using C# for defining custom permission for a list item.

// assign a item to SPListItem object.
SPListItem objLstitem = objLst.Items[0]; // objLst is the SPList object

// get the user by ID/Email
// objSpWeb is the SpWeb object

SPUser objUser = objSpWeb.SiteUsers.GetByEmail(;

// Break inheriting parent permissions for this List Item.

// assign Role to the defined User
SPRoleDefinitionCollection objWebRoleDefn = objSpWeb.RoleDefinitions;
SPRoleAssignment objRoleAssign = new SPRoleAssignment(objUser);

// specify the name of the role definition like [Full Control][Read][Contribute] etc.

I have written the same here also:Programmatically assign specific permission in SharePoint

Samarendra Swain