Beginning files for any Feature

There are a few files. Feature.xml, elements.xml and in the event of just an eventreceiver, just a main.cs and worker.cs files

Feature.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<FeatureĀ  Id=”A GUID IS PUT IN HERE”
Title=”…”
Description=”…”
Version=”12.0.0.0″
Hidden=”FALSE”
Scope=”Site” //can be site/web/farm
DefaultResourceFile=”core”
ReceiverAssembly=”KMS_ER_Itemadding_DetailsLists, Version=1.0.0.0, Culture=neutral, PublicKeyToken=91d8ff9e64e6b4a3″
ReceiverClass=”NAMESPACE.CLASS”

xmlns=”http://schemas.microsoft.com/sharepoint/”>
<ElementManifests>
<ElementManifest Location=”elements.xml”/>
</ElementManifests>
</Feature>

Elements.xml

<?xml version=”1.0″ encoding=”utf-8″ ?>
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”>
//can be blank
</Elements>

main.cs

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Reflection;

namespace KMS_ER_Itemadding_DetailsLists.FeatureCode
{
class KMS_ER_ItemAdding_DetailLists_Main : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
//can do anything you want here. Whatever the feature calls for. This piece of code adds to an event receiver

SPList plotList = newsubsite.Lists[“Details”];
string assName = Assembly.GetExecutingAssembly().FullName;
plotList.EventReceivers.Add(SPEventReceiverType.ItemAdding, assName,
“NAMESPACE.WORKER”);
newsubsite.Dispose();

}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
// and to delete it
SPList plotList = newsubsite.Lists[“Details”];

foreach (SPEventReceiverDefinition item in plotList.EventReceivers)
{
if (item.Assembly == Assembly.GetExecutingAssembly().FullName)
{
item.Delete();
break;
}
} }

public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
}

public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
}
}
}

worker.cs

The worker.cs is the logic behind the event receiver. Whatever you just added has to do some logic to determine if it will allow the event to continue or do some other work when it does continue. This one below only allows for one item to be added to a list named Details.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Diagnostics;
namespace NAMESPACE
{
class Worker : SPItemEventReceiver
{
public override void ItemAdding(SPItemEventProperties properties)
{
using (SPWeb t_site = properties.OpenWeb())
{
SPList t_aList = t_site.Lists[“Details”];
foreach (SPListItem t_listitems in t_aList.Items)
{
properties.Cancel = true;
properties.ErrorMessage = “Only one item in this list is allowed!”;
}
}
}
}
}

Comments are closed.