Showing posts with label SPList. Show all posts
Showing posts with label SPList. Show all posts

Wednesday, September 21, 2011

Inbuilt method to Check if List Exist in SharePoint 2010.

In SharePoint 2007, one of the mostly required methods but not provided by Microsoft:
Checking if SharePoint List exists on Site or not?
If we directly use spWeb.Lists[“<ListName>”] and if list does not exist then it will throw an exception. To avoid such exceptions I have created following extension method:
public static bool IsListExists(this SPWeb spWeb, string listName)
{
    try
    {
        return spWeb.Lists.Cast<SPList>().Any(list => string.Compare(list.Title, listName, true) == 0);
    }
    catch (Exception ex)
    {
        ex.LogException("List does not exist", CommonConstants.EVENT_SOURCE, spWeb, spWeb.CurrentUser);
        return false;
    }
}
Now Microsoft is woke up, In SharePoint 2010 they have provided an inbuilt method method in the SPListCollection .Simply use this method instead of looping all the lists and check its existence.

SPList sampleList = spWeb.Lists.TryGetList("SampleList");
if (sampleList != null)
{
    // Code Block goes here
}

Hope this helps you...

Friday, March 4, 2011

Add event receiver to a SharePoint list

Recently I have created a generic function to add event receiver to specific SharePoint list.
Explaination is not need as code is very simple to understand.

private void AddEventReceiverToAList(string siteUrl)
{
    using (SPSite site = new SPSite(siteUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                SPList list = web.Lists["myList"];
                if (list != null)
                {
                    int receivers = list.EventReceivers.Count;
                    string className = "EventReceiverClass";
                    string asmName = "EventReceiverAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a865f0ecc234ea51";
                    web.AllowUnsafeUpdates = true;
                    bool isAddedReceiverExist = false;
                    for (int i = 0; i < receivers; i++)
                    {
                        SPEventReceiverDefinition eventReceiver = list.EventReceivers[i];
                        if (eventReceiver.Class == className && eventReceiver.Type == SPEventReceiverType.ItemAdded)
                        {
                            isAddedReceiverExist = true;
                            break;
                        }
                    }
                    if (!isAddedReceiverExist)
                        list.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, className);
                }
            }
            catch { }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }