using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
namespace Test
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://xxxx/"))
{
using (SPWeb web = site.OpenWeb())
{
SetupLists(web);
}
}
}
/// <summary>
/// This method is used to setup list
/// </summary>
/// <param
name="web"></param>
private static void SetupLists(SPWeb web)
{
using (var newWeb = web.Site.OpenWeb(web.ID))
{
SetupCustomLists(newWeb);
newWeb.Update();
}
}
/// <summary>
/// This method is used to setup custom list by providing
Custom List Template Name
/// </summary>
/// <param
name="web"></param>
private static void SetupCustomLists(SPWeb web)
{
var customListTemplate = GetListTemplate(web, " customListTemplateName");
SetupList(web, "CustomList", "A new custom list.", customListTemplate);
// ...
any other lists of this type that need created ...
}
/// <summary>
/// This method is used to get ListTemplate with given name
as parameter
/// </summary>
/// <param
name="web"></param>
/// <param
name="templateName"></param>
/// <returns></returns>
private static SPListTemplate GetListTemplate(SPWeb web, string templateName)
{
var template = web.ListTemplates.OfType<SPListTemplate>().FirstOrDefault(i
=> i.Name == templateName);
if (template == null)
throw new SPException(string.Format("Template {0}
not found.", templateName));
return template;
}
/// <summary>
/// This method is used to creates/setups the new custom list
with existing template
/// </summary>
/// <param
name="web"></param>
/// <param
name="name"></param>
/// <param
name="description"></param>
/// <param
name="template"></param>
private static void SetupList(SPWeb web, string name, string description, SPListTemplate template)
{
var webId = web.ID;
SPList list;
using (var newWeb = web.Site.OpenWeb(webId))
{
list = EnsureList(newWeb, name,
description, template);
}
// ...
perform any additional actions needed on list ...
}
/// <summary>
/// This method ensures the newly created cusomt list
/// </summary>
/// <param
name="web"></param>
/// <param
name="name"></param>
/// <param
name="description"></param>
/// <param
name="template"></param>
/// <returns></returns>
private static SPList EnsureList(SPWeb web, string name, string description, SPListTemplate template)
{
var list = web.Lists.TryGetList(name);
if (list != null)
{
if (list.BaseTemplate != template.Type)
throw new SPException(string.Format("List {0} has type '{1}'; but should have type
'{2}'.", name, list.BaseTemplate,
template.Type));
return list;
}
var id = web.Lists.Add(name, description, template);
return web.Lists[id];
}
}
}