Dec 15, 2012

Creating List Programatically in Sharepoint 2010 using Feature Receiver

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;

namespace Devendra_Feature_Event_Receivers.Features.AddList
{
    /// 
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// 
    /// 
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// 

    [Guid("5bf5f6c5-c371-419a-984b-f0ecf9ddeda0")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                //get the current web object.
                SPWeb web = properties.Feature.Parent as SPWeb;

                //Get the list object. this method is used to create the list if list already exist then it will return the list object.
                SPList list = web.EnsureList("Employee", "This list contains Employee details.", SPListTemplateType.GenericList);

                //Check if list exist.
                if (list != null)
                {
                    //Rename Title Field as FirstName.
                    SPField field = list.EnsureField("Title", "", SPFieldType.Text, true);
                    field.Title = "FirstName";
                    field.Update();

                    //Add the filed to the list.
                    SPField fld = null;
                    //Add the filed to the list.if field already exist in the list then it will return the object of the field.
                    fld = list.EnsureField("LastName", "Employee LastName", SPFieldType.Text, true);

                    //Add field to the default view.
                    if (fld != null)
                    {
                        SPView view = list.Views[0];
                        view.ViewFields.Add(fld);
                        view.Update();
                        fld = null;
                    }
                    //Add values to the list
                    SPListItemCollection listItems = list.Items;
                    AddItems(listItems, "Devendra", "Velegandla");
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void AddItems(SPListItemCollection listItems, string FirstName, string LastName)
        {
            SPListItem item = null;
            item = listItems.Add();
            item["FirstName"] = FirstName;
            item["LastName"] = LastName;
            item.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            //Get the current web object.
            SPWeb web = properties.Feature.Parent as SPWeb;
            //Ensure and delete the list.
            web.DeleteList("Employee");
        }



    }

}




add one more class called utilities.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace Devendra_Feature_Event_Receivers.Features.AddList
{
public static class Utilities
{
/// Used to create the list by using the list template type.
public static SPList EnsureList(this SPWeb web, string listTitle, string desc, SPListTemplateType lstTemplateType)
{
//Get the list collection.
SPListCollection lstCollection = web.Lists;

//Check If List already Exist in the system.
SPList lstObj = (from SPList lst in lstCollection
where string.Equals(lst.Title, listTitle, StringComparison.InvariantCultureIgnoreCase) == true
select lst).FirstOrDefault();

//If yes return the list object.
if (lstObj != null)
{
return lstObj;
}
//List does not exist and need to create a new one
Guid lstGuid = web.Lists.Add(listTitle, desc, lstTemplateType);
try
{
SPList newList = web.Lists.GetList(lstGuid, true);
newList.OnQuickLaunch = true;
newList.Update();
return newList;
}
catch //If for some reason list creation fails returns an null object
{
return null;
}
}
/// Used to create the list column with display name and field type
public static SPField EnsureField(this SPList list, string fldDisplayName, string fldDesc, SPFieldType fldType, bool isMadatory)
{
//get list the field collections
SPFieldCollection fieldCollection = list.Fields;

//Check If field already exist in the list.
SPField spField = (from SPField field in fieldCollection
where string.Equals(field.Title, fldDisplayName, StringComparison.InvariantCultureIgnoreCase) == true
select field).FirstOrDefault();

//If exist return the field.
if (spField != null)
{
return spField;
}
//If field does not exist Add the field to the list
try
{
list.Fields.Add(fldDisplayName, fldType, isMadatory);
SPField spfield = list.Fields.GetField(fldDisplayName);
spfield.Description = fldDesc;
spfield.Update();
return spfield;
}
catch // Incase if any exception occur.
{
return null;
}
}
/// Used to Ensure that subscription list exist and if yes then delete the list.
public static bool DeleteList(this SPWeb web, string listTitle)
{
//Get the list collection.
SPListCollection lstCollection = web.Lists;

//Check If List Exist in the system.
SPList lstObj = (from SPList lst in lstCollection
where
string.Equals(lst.Title, listTitle, StringComparison.InvariantCultureIgnoreCase) == true
select lst).FirstOrDefault();

//If yes delete the list object.
if (lstObj != null)
{
try
{
lstObj.Delete();
return true;
}
catch (Exception ex)
{
}
}
return false;
}
}
}



SharePoint-Journey for Administrators, Developers and users

1 comment: