Friday, 30 September 2011

Create site with Predefined Lists in SharePoint 2010


A quick tip about how to create a site with Predefined List included in it.
So if you're creating a site using a custom or out-of-box list template and wants a List\Library to be created after the site creation, the easiest way to do this by using WebProvisioned event receiver on your existing Site definition.

Example -

A Web Event Receiver class -

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace WebProvisioning.SiteEventReceiver
{
public class WebEventReceiver : SPWebEventReceiver
{
public override void WebDeleting(SPWebEventProperties properties)
{
try
{
if (properties.Web.Lists["Data"] != null)
{
properties.Cancel = true;
}
}
catch
{
}
base.WebDeleting(properties);
}
public override void WebAdding(SPWebEventProperties properties)
{
base.WebAdding(properties);
}
public override void WebProvisioned(SPWebEventProperties properties)
{
properties.Web.Title += String.Format(” [Created By: {0}]“,properties.UserDisplayName);
properties.Web.AllowUnsafeUpdates = true;
properties.Web.Update();
base.WebAdding(properties);
}
}
}

Defining the Event Receiver – Lets look at the elements.xml file

<elements xmlns=”http://schemas.microsoft.com/sharepoint/”>
<receivers>
<receiver>
<name>SiteEventReceiverWebDeleting</name>
<type>WebDeleting</type>
<assembly>$SharePoint.Project.AssemblyFullName$</assembly>
<class>WebProvisioning.SiteEventReceiver.SiteEventReceiver</class>
<sequencenumber>10000</sequencenumber>
</receiver>
<receiver>
<name>SiteEventReceiverWebAdding</name>
<type>WebAdding</type>
<assembly>$SharePoint.Project.AssemblyFullName$</assembly>
<class>WebProvisioning.SiteEventReceiver.SiteEventReceiver</class>
<sequencenumber>10000</sequencenumber>
</receiver>
<receiver>
<name>SiteEventReceiverWebProvisioned</name>
<type>WebProvisioned</type>
<assembly>$SharePoint.Project.AssemblyFullName$</assembly>
<class>WebProvisioning.SiteEventReceiver.SiteEventReceiver</class>
<sequencenumber>10000</sequencenumber>
<synchronization>Synchronous</synchronization>
</receiver>
</receivers>
</elements>

If there are several event handlers attached to the same event, you can use the sequence number element to define the order. If you create the file using Visual Studio 2010, the $SharePoint.Project.AssemblyFullName$ placeholder is used to reference the current project’s assembly. If you create the file manually, you must enter the fully qualified assembly name in the element.

Ads by Google

No comments:

Post a Comment