Posted by: R Manimaran | December 7, 2010

Using Extensions Methods in SharePoint

In the Previous post we have seen about Extensions and how to use it in C#.

Here we have Some Examples using Extensions Method in SharePoint.

using (SPSite oSPSite = new SPSite(http://server”))

{

using (SPWeb oSPWeb = oSPSite.OpenWeb())

{

//Calling a Extensions Method to Check the List Exists

if (!oSPWeb.IsListExists(“Tasks“))

{

Guid taskListGuid= oSPWeb.Lists.Add(“Tasks“, “Task List“,

SPListTemplateType.Tasks);

}

//Another extension method Here

SPList taskList = oSPWeb.Lists.GetListByListName(“Tasks“);

//One More Extensions Method on SPList

taskList.ClearItems();

//Extension Method on SPListItem

SPUser CreatedBy = taskList.Items[0].CreatedBy(oSPWeb);

string email = CreatedBy.Email;

//Extension Method on SPViewCollections

SPView view = taskList.Views.GetViewByName(“AllItems“);

}

}

Our Extensions Methods

IsListExists à Extension on SPWeb

public static bool IsListExists(this SPWeb web, string name)

{

bool exists = false;

try

{

SPList list = web.Lists[name];

exists = true;

}

catch

{

exists = false;

}

return exists;

}

GetListByListName à Extension on SPListCollection

public static SPList GetListByListName(this SPListCollection lists, string name)

{

if (lists != null && !string.IsNullOrEmpty(name))

{

foreach (SPList list in lists)

{

if (string.Compare(list.Title, name,StringComparison.OrdinalIgnoreCase) == 0)

{

return list;

}

}

}

return null;

}

ClearItems à Extension Method on SPList

public static void ClearItems(this SPList list)

{

int ItemCount = list.ItemCount;

SPListItemCollection itemCollections = list.Items;

foreach (SPListItem item in itemCollections)

{

list.GetItemById(item.ID).Delete();

}

}

CreatedBy à Extension Method on SPListItem

public static SPUser CreatedBy(this SPListItem item,SPWeb oWeb)

{

string userName =item[“Author”].ToString();

SPFieldUserValue loginUserValue = new SPFieldUserValue(oWeb, userName);

return loginUserValue.User;

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: