Skip Navigation Links
Level Orange > Posts > Attaching a Receiver using Code
Attaching a Receiver using Code

Intro

So I have built a new receiver (You can review the article found here). Now what?

Well, the answer is that you have to attach it somehow. In this post, I plan to demonstrate how to do this via code. In a later approach I will be reviewing feature based development.

Implementation

The first thing we are going to do is create a new project in visual studio. In this case we will make it a console application just for a POC:

We then of course are going to add the Microsoft.SharePoint.dll reference. You can find this in my previous article located here.

Finally we are going to write the following code:

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.SharePoint;

namespace MSIT.Samples

{

class Program

{

static void Main(string[] args)

{

SPSite spSite = null;

SPWeb spWeb = null;

SPList spList;

try

{

spSite = new SPSite("http://r2-basemachine:1111");

spWeb = spSite.OpenWeb();

spList = spWeb.Lists["Contacts"];

//spList = spWeb.Lists["ContactType"];

string asmName = "MSIT.ItemReceivers, Version=0.0.0.0, Culture=neutral, PublicKeyToken=6546c52e1a7f48a0";

string className = "MSIT.ItemReceivers.UpdateContactsEvent";

spList.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, className);

spList.EventReceivers.Add(SPEventReceiverType.ItemUpdated, asmName, className);

spList.Update();

}

catch

{}

finally

{

spList = null;

spWeb.Dispose();

spSite.Dispose();

spWeb = null;

spSite = null;

}

}

}

}

 

You simply run this code and run IISReset and you are golden (ready for test)

Comments

There are no comments yet for this post.