Monday 10 March 2014

Create a sequential workflow using Visual studio 2010 in SharePoint 2010

Here we will discuss how to develop a sequential workflow using Visual studio 2010 in SharePoint 2010. Microsoft provides different project templates to work for SharePoint.
For this first open Visual studio 2010 and then File -> New Project.Then from the new project dialog box choose Visual C# and then Select SharePoint and from there select 2010 and Choose Sequential Workflow template and give a name in the Name box as shown in the figure below and click on OK.


In the next step provide the local debugging URL and you will able to only deploy as farm solution is selected
because you can not deploy a workflow as sandboxed solution. See the figure below.


And click on next. In the next step give the name of workflow and select the type of workflow as shown in the figure below.


In the next step select the list or library you want to attach the workflow and select where you want to show the history list you want to store as shown in the figure below.


The Workflow history list is used to store all events that occur while workflow is running.Here also you can check the check box if you want to automatic associate the workflow to the selected list or library. In the next step you can choose when you want to start the workflow as shown in the figure below.


Now your visual studio should look like the figure shown below.


In the solution explorer there is one folder for Feature and one folder for Package. The package folder will hold the .wsp file when you package or deploy the project. Elements.xml: This file describes the workflow to SharePoint and it stores the name and description of the workflow, any forms that it uses, and other information.Workflow1.cs:These are the files that make up the activities and code for the workflow.

Now Drag and drop a CreateTask activity from the Toolbox to the Workflow designer, right below the onWorkflowActivated1 activity. There is a red mark in the activity which shows that we need to set a mandatory field in the workflow as shown in the figure below.


Then go to the activity properties and give the correlationtoken.You have to use a unique correlation token for each task you are referencing in a workflow. And then expand the correlationtoken property and set the OwnerActivityName to Workflow1 as shown in the figure below.

Now also the red mark removes. Then find the TaskID and click on ..., it will open the Bind dialog. The Bind dialog is used to link a workflow property to a field or property in the code-behind file. This can be either an existing member or you can choose to create a new one. Here Click Bind to a new member tab. Type “taskId” in the New member name textbox. Select Create Property radio button. Then click on OK as shown in the figure below.


Next we need to do all these steps for TaskProperties property. In the next step double click on the CreateTask1 Activity ant will generate createTask1_MethodInvoking method. In this method, initialize taskId and taskProperties.
Here we will assign the task as shown below:
private void createTask1_MethodInvoking(object sender, EventArgs e)
        {
            taskId = Guid.NewGuid();
            taskProperties = new SPWorkflowTaskProperties();
            taskProperties.AssignedTo = "domainname\\username";
            taskProperties.Title = "Task assigned from the sequential workflow";
        }
After that F5 to deploy the web part, once the deployment finish go to the browser and click on the particular list. Click on the add new item and when you submit the form the breakpoint hits and when you will refresh a new item will be added to the list with name Task assigned from the sequential workflow.

Create an approval workflow in SharePoint Designer 2010


This is a video tutorial that explains about how to create an approval workflow in SharePoint designer 2010.

You can also Create a sequential workflow using Visual studio 2010 in SharePoint 2010 [Click Here.


Thursday 6 March 2014

Schedule Site Collection / Farm Backup in SharePoint


  1.  Create one text file and Change filename is “SP2010_Site_Backup_With_Notification.ps1” and place below code into that file
 # NAME: SP2010_Site_Backup_With_Notification.ps1
 # AUTHOR: VENKATA SIVA KRISHNA DASARI
 # COMMENT: A Powerful Script to take backup of the Site Collection SharePoint 2010 with email notification (or) Maintain log File.


 Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

 try
  {
     $today = (Get-Date -Format dd-MM-yyyy)
     $today1 = (Get-Date -Format ddMMMyyyy)
     $month = (Get-Date -Format MMM-yyyy)
     $prevMonth=$((Get-Date).AddMonths(-1))
     write-host $prevMonth
   
     $prevDay= $((Get-Date).AddDays(-30))
     $day=$prevDay.ToString("dd-MM-yyyy")
     $prevMonthDay=$prevMonth.ToString("MMM-yyyy")
     write-host $day
   # Check if log file exists.
     $ChkFile = "D:\Backups\Sharepoint\Scheduled\" + $day 
     write-host $ChkFile
     $FileExists = (Test-Path $ChkFile)

   # Part 1.

     If (($FileExists)) 
     {
    write-host "Backup File Exists" -foregroundcolor Green
    Remove-Item -recurse $ChkFile 
   
    write-host "Backup File Deleted" -foregroundcolor Green
     }
     ElseIf (!($FileExists))
     {
    write-host "Backup File not Exists" -foregroundcolor Green
     }
  
    
   # Check if Monthly log file exists.
     $ChkMonthLog = "D:\Backups\Sharepoint\Scheduled\TestBackupLog_" + $prevMonthDay + ".txt" 
     write-host $ChkMonthLog
     $FileExists1 = (Test-Path $ChkMonthLog)

   # Part 2.

     If (($FileExists1)) 
     {
    write-host "Month Log File Exists" -foregroundcolor Green
    Remove-Item -recurse $ChkMonthLog 
   
write-host "Month Log Deleted" -foregroundcolor Green
     }
     ElseIf (!($FileExists1))
     {
      write-host "Month Log not Exists" -foregroundcolor Green
     }



   # Location of the Backup Folder
     [IO.Directory]::CreateDirectory("D:\Backups\Sharepoint\Scheduled\$today")
   # This will actually initiate the Site Collection backup.

     Backup-SPSite –Identity http://Domain/sites/testPortal -path D:\Backups\Sharepoint\Scheduled\$today\testPortal_$today1.bak

     Add-Content -Value "Test Backup done successfully" -Path D:\Backups\Sharepoint\Scheduled\testBackupLog_$month.txt

     Add-Content -Value (Get-Date -Format dd-MMM-yyyy) -Path D:\Backups\Sharepoint\Scheduled\testBackupLog_$month.txt

     Add-Content -Value "----------------------------------------------------------" -Path D:\Backups\Sharepoint\Scheduled\testBackupLog_$month.txt
  
   # Remove-SPShellAdmin –username administrator 

   # Edit the From Address as per your environment.
   # $emailFrom = "test@test.com"
   # Edit the mail address to which the Notification should be sent.
   # $emailTo = "dvsivakrishna@gmail.com"
   # Subject for the notification email. The + “$today” part will add the date in the subject.
   # $subject = "The SharePoint Farm Backup was Successful for "+"$today"
   # Body or the notification email. The + “$today” part will add the date in the subject.
   # $body = "The SharePoint Site Backup was Successful for "+"$today"
   # IP address of your SMTP server. Make sure relay Is enabled for the SharePoint server on your SMTP server
   # $smtpServer = "1.1.1.20"
   # $smtp = new-object Net.Mail.SmtpClient($smtpServer)
   # $smtp.Send($emailFrom, $emailTo, $subject, $body)
  }
 Catch
  {
     $ErrorMessage = $_.Exception.Message
   # Configure the below parameters as per the above.
   # $emailFrom = "Admin@test.com"
   # $emailTo = "dvsivakrishna@gmail.com"
   # $subject = "The SharePoint Farm Backup Job failed on "+"$today"
   # $body = "The SharePoint Farm Backup Job failed on "+"$today and the reason for failure was $ErrorMessage."
   # $smtpServer = "1.1.1.20"
   #  $smtp = new-object Net.Mail.SmtpClient($smtpServer)
   # $smtp.Send($emailFrom, $emailTo, $subject, $body)
     Add-Content -Value $ErrorMessage -Path D:\Backups\Sharepoint\Scheduled\TestBackupLogErrorFile_$month.txt
  }

Open Task scheduler in Administrative tools 
          Start --> Administrative Tolls --> Task Scheduler

Right Click on “Task Scheduler library” and Click on “Create Task”



  1. Please place Name of task.
  2. Select option "Run whether user is logged on or not".
  3. Check option "Run With highest privileges".


Click on new button and Schedule Trigger

Browse .ps1 file and place "PowerShell command"



After click ok button task will run automatically on what time you scheduled.


Filtering Multiple Columns dynamically Using CAML Query In SharePoint Custom WebPart

//Filter And Bind data to Grid
public void BindGridTEST()
        {
            using (SPSite site = new SPSite(ConfigurationManager.AppSettings["InternalSiteURL"]))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPQuery query = new SPQuery();


                    this.Status = "PRO";

                    if (!string.IsNullOrEmpty(Convert.ToString(txtCName.Text)))
                        this.CName = txtCName.Text.Trim();

                    if (!string.IsNullOrEmpty(Convert.ToString(txtAName.Text)))
                        this.AName = txtAName.Text.Trim();

                    if (!string.IsNullOrEmpty(Convert.ToString(txtCode.Text)))
                        this.Code = txtCode.Text.ToLower().Trim();

                    if (!string.IsNullOrEmpty(Convert.ToString(txtPDate.Text)))
                        this.PDate = txtPDate.Text.ToLower().Trim();

                    //Generate CAML Query Dynamically
                    query.Query = Convert.ToString(getCAMLSerachQuery());
                    // queryTrainingDetails.QueryThrottleMode = SPQueryThrottleOption.Override;
                    query.RowLimit = 1000;
                 

                    query.IncludeMandatoryColumns = false;
                    query.ViewFields = string.Concat(@"<FieldRef Name='Name' />
                                        <FieldRef Name='Date' />
                                        <FieldRef Name='Code' />                                      
                                        <FieldRef Name='ID' />                                      
                                        <FieldRef Name='Status' />";



                    query.ViewFieldsOnly = true;
                    SPListItemCollection listitems;

                    listitems = web.Lists["ListName"].GetItems(query);
                    DataTable dt = null;

                    if (listitems != null && listitems.Count > 0)
                    {
                        int fieldCount = listitems.Fields.Count;
                        dt = listitems.GetDataTable();
                        lblNoRecordsMsg.Text = "";
                        gvGIPropDetails.Visible = true;
                        trchkSelectAll.Visible = true;
                        Cbx_Toggle.Checked = false;
                        gvDetails.DataSource = dt;
                        gvDetails.DataBind();
                    }
                    else
                    {
                        lblNoRecordsMsg.Text = "No Record(s) Found.";
                        gvDetails.Visible = false;
                        trchkSelectAll.Visible = false;
                    }

                }
            }
        }



 #region Sorting Properties
        private string _SortField = "ID";
        private bool _SortDirection = false;
        public string SortField
        {
            get { return _SortField; }
            set { _SortField = value; }
        }
        public bool SortDirection
        {
            get { return _SortDirection; }
            set { _SortDirection = value; }
        }
        #endregion Sorting Properties



        #region Search Criteria Properties
        private string _CName, _AName, _Insurer, _PropDate, _Status;

        public string Status
        {
            get { return _Status; }
            set { _Status = value; }
        }
        public string CName
        {
            get { return _CName; }
            set { _CName = value; }
        }
        public string AdviserName
        {
            get { return _AName; }
            set { _AName = value; }
        }
        public string Code
        {
            get { return _Code; }
            set { _Code = value; }
        }
        public string PDate
        {
            get { return _PDate; }
            set { _PDate = value; }
        }

        public string CAML_CName
        {
            get
            {
                return string.Format(@"<Contains><FieldRef Name='CName'/>" +
                                             "<Value Type='Text'>{0}</Value></Contains>", this.CName);
            }
        }

        public string CAML_AName
        {
            get
            {
                return string.Format(@"<Contains><FieldRef Name='AName'/>
                                             <Value Type='Text'>{0}</Value></Contains>", this.AName);
            }
        }
        public string CAML_Insurer
        {
            get
            {
                return string.Format(@"<Contains><FieldRef Name='Code'/>
                                             <Value Type='Text'>{0}</Value></Contains>", this.Code);
            }
        }

        public string CAML_PDate
        {
            get
            {
                return string.Format(@"<Eq><FieldRef Name='PDate'/>
                                             <Value Type ='DateTime' IncludeTimeValue='FALSE'>{0}</Value></Eq>", String.Format("{0:s}", Convert.ToDateTime(this.PDate)));

            }
        }

        public string CAML_Status
        {
            get
            {
                return string.Format(@"<Eq><FieldRef Name='Status'/>
                                             <Value Type='Text'>{0}</Value></Eq>", "PRO");
            }
        }

//Build CAML Query using AND Operator
        public string BuildCamlQuery
        {
            get
            {
                List<string> objCaml = new List<string>();
                StringBuilder _caml = new StringBuilder();

                if (!string.IsNullOrEmpty(this.ClientName))
                    objCaml.Add(this.CAML_CName);

                if (!string.IsNullOrEmpty(this.Insurer))
                    objCaml.Add(this.CAML_Insurer);

                if (!string.IsNullOrEmpty(this.AName))
                    objCaml.Add(this.CAML_AName);

                if (!string.IsNullOrEmpty(Convert.ToString(this.PDate)))
                    objCaml.Add(this.CAML_PDate);

                if (!string.IsNullOrEmpty(Convert.ToString(this.Status)))
                    objCaml.Add(this.CAML_Status);

                for (int i = 1; i < objCaml.Count; i++)
                {
                    _caml.Append("<And>");
                }

                //Now create a string out of the CMAL snippets in the list.

                for (int i = 0; i < objCaml.Count; i++)
                {
                    string snippet = objCaml[i];
                    _caml.AppendFormat(snippet);
                    if (i == 1)
                    {
                        _caml.Append("</And>");
                    }

                    else if (i > 1)
                    {
                        _caml.Append("</And>");
                    }

                }

                string value = string.Empty;

                if (_caml.ToString().Trim().Length > 0)
                    value = string.Format(@"<Where>{0}</Where>", _caml.ToString().Trim());
                //Return the final CAML query
                return value;
            }

        }

//Apend Sort Option to CAML Query
        public StringBuilder getCAMLSerachQuery()
        {
            StringBuilder camlQuery = new StringBuilder();
            if (this.BuildCamlQuery != null && this.BuildCamlQuery != string.Empty)
            {
                camlQuery.Append(this.BuildCamlQuery);
            }
            camlQuery.AppendFormat(@"<OrderBy><FieldRef Name='{0}' Ascending='{1}' /></OrderBy>", this.SortField, this.SortDirection);
            return camlQuery;
        }

        #endregion Search Criteria Properties

Wednesday 5 March 2014

Fetching records using IN Operator In CAMl Dynamically


SPQuery strQuery = new SPQuery();
strQuery.Query = string.Format(@"<Where>
                                                            <And>
                                                                <Eq>
                                                                    <FieldRef Name='Code' LookupId='True'/>
                                                                    <Value Type='Lookup'>{0}</Value>
                                                                </Eq>
                                                                <Eq>
                                                                    <FieldRef Name='Status' />
                                                                    <Value Type='Text'>POL</Value>
                                                                </Eq>
                                                            </And>
                                                        </Where>", ddlClient.SelectedValue.Split(new[] { ";#" }, StringSplitOptions.None)[0]);
                       
strQuery.ViewFields = string.Concat(@"<FieldRef Name='ID' />");
strQuery.ViewFieldsOnly = true; //Using this take View Fields only
strQuery.QueryThrottleMode = SPQueryThrottleOption.Override;//using this fetching above 8000 records

myList1items = web.Lists.TryGetList("ParentListName").GetItems(strQuery);//fetching records into List Item Collection

//Adding filter column using Array
ArrayList strarrayIds= new ArrayList();
                    foreach (SPListItem li in myList1items)
                    {
                        if (!strarrayIds.Contains(li["GID"]))
                        {
                            strarrayIds.Add(GetIDValueFromLookup(li["GID"]));
                        }
                    }

 string strViewFields = string.Concat(@"<FieldRef Name='ID' />");
     
//Fetching data into Listitem            
List<SPListItem> myList2items = getGenericListItemsWithAnd(strarrayIds, "ChildListName", "ID",strViewFields, true);


//Fetching data from list using IN Operator into Sharepoint List
public List<SPListItem> getGenericListItemsWithAnd(ArrayList arrayIds, string listname, string FieldName,string strViewFields, bool IsLookup)
        {
            List<SPListItem> lsGenericItems = new List<SPListItem>();
            using (SPSite site = new SPSite(ConfigurationManager.AppSettings["InternalSiteURL"]))
            {
                using (SPWeb web = site.OpenWeb())
                {

                    SPListItemCollection objListCol = null;
                    SPList lstToQuery = web.Lists.TryGetList(listname);
                    SPQuery objQuery = new SPQuery();


                    int intInOperCount = InOperatorCount();
                    int intCount = arrayIds.Count / intInOperCount;
                    int intBal = arrayIds.Count % intInOperCount;

                    if (intBal > 0)
                        intCount = intCount + 1;

                    for (int i = 0; i < intCount; i++)
                    {
                        ArrayList listTemp = new ArrayList();

                        int x = 0;
                        if (i == 0)
                            x = intInOperCount * i;
                        else
                            x = (intInOperCount * i);

                        if (intBal > 0 && i == intCount - 1)
                        {
                            listTemp = arrayIds.GetRange(x, intBal);
                        }
                        else
                        {
                            listTemp = arrayIds.GetRange(x, intInOperCount);
                        }

                        #region Code

                        StringBuilder camlQuery = new StringBuilder();

                        camlQuery.Append("<Where><And><In>");
                        camlQuery.Append("<FieldRef Name='" + FieldName + "'/><Values>");
                        camlQuery.Append(getInOperatorTags("Counter", IsLookup, listTemp));
                        camlQuery.Append("</Values></In>");

                        if (this.BuildCamlQuery != null && this.BuildCamlQuery != string.Empty)
                        {
                            camlQuery.Append(this.BuildCamlQuery);
                        }

                        camlQuery.Append("</And></Where>");

                        objQuery = new SPQuery();
                        objQuery.Query = Convert.ToString(camlQuery.ToString().Trim());
                        objQuery.ViewFields = strViewFields;
                        objQuery.ViewFieldsOnly = true;
                        objQuery.RowLimit = 500;

                        do
                        {
                            objListCol = lstToQuery.GetItems(objQuery);

                            foreach (SPListItem li in objListCol)
                            {
                                lsGenericItems.Add(li);
                            }
                            objQuery.ListItemCollectionPosition = objListCol.ListItemCollectionPosition;

                        } while (objQuery.ListItemCollectionPosition != null);

                        #endregion

                    }
                }
            }


            return lsGenericItems;
        }


//Generate Query For IN operator using CAML
        public string getInOperatorTags(string strType, bool isId, ArrayList objArrayList)
        {

            string strReturn = string.Empty;
            string strId = "";
            if (isId)
                strId = "LookupId='true'";
            for (int i = 0; i < objArrayList.Count; i++)
            {
                if (strReturn == "")
                {
                    strReturn = "<Value Type='" + strType + "' " + strId + ">" + Convert.ToString(objArrayList[i]) + "</Value>";
                }
                else
                {
                    strReturn = strReturn = strReturn + "<Value Type='" + strType + "' " + strId + ">" + Convert.ToString(objArrayList[i]) + "</Value>";
                }
            }

            return strReturn;


        }

//Count for Fetching data  for Single time
        public int InOperatorCount()
        {
            return 500;
        }

//fetch ID value from lookup
 public string GetIDValueFromLookup(object lookupValue)
        {
            if (lookupValue == null) return string.Empty;
            if (isLookup(lookupValue))
            {
                var value = Convert.ToString(lookupValue).Split(new[] { ";#" }, StringSplitOptions.None)[0];
                return value;
            }
            else
            {
                return Convert.ToString(lookupValue);
            }
        }

//Check Condition is it lookup
public bool isLookup(object lookupval)
        {
            bool retflag = false;
            int indexcolon = Convert.ToString(lookupval).IndexOf(';');
            int indexhash = Convert.ToString(lookupval).IndexOf('#');
            int diff = indexhash - indexcolon;
            if (indexcolon > 0 && indexhash > 0 && diff == 1)
                retflag = true;
            return retflag;
        }

Event Receivers in SharePoint

1. Introduction

While developing any application we need to handle some events. For example, when a new item is added to a list, we may need to perform some action like say, notifying the person who created the list item, or modifying the dependent entries in some other location etc. Handling of such events is facilitated by event receivers. We have many SharePoint event receiver classes in order to handle variety of events.

2. SharePoint Event Receiver types

There are basically two types of event receivers: Synchronous and Asynchronous event receivers.Synchronous event receivers are also known as ‘Before’ event receivers. They are used to perform some custom action before an event occurs. In this case, there is a flexibility of cancelling the event on some conditions so that the event that gets initiated will not occur.
Asynchronous event receivers are also known as ‘After’ event receivers. They are used to perform some custom action after an event occurs. These events are asynchronous because they need not happen immediately after the event is performed. They can happen sometime later also, unlike synchronous event receivers which occur immediately before an event occurs.

3. Classes of Event Receivers

There are fundamentally five classes for Event Receivers for SharePoint 2007.
Microsoft.SharePoint.SPEmailEventReceiver : This provides event handling whenever a user sends an email to a list on which e-mail feature is enabled
Microsoft.SharePoint.SPFeatureReceiver : This provides event handling whenever is feature is acted upon
Microsoft.SharePoint.SPItemEventReceiver : This provides event handling whenever any action is performed on a list item
Microsoft.SharePoint.SPListEventReceiver : This provides event handling whenever a list definition is modified like adding or deleting columns and modifying existing columns.
Microsoft.SharePoint.SPWebEventReceiver : This provides event handling whenever a site or a site collection is deleted or moved
Each of the classes has some virtual methods which are to be over-ridden to perform our custom action. Those methods are as follows.

3.1 Site Level Events

Methods under the class SPWebEventReceiver handle site level events. A brief overview of those methods is as follows.
Site Deleted - This occurs after a site collection is deleted.
Site Deleting - This occurs before a site collection is being deleted.
Web Deleted - This occurs after a website has been deleted completely. This is an asynchronous after event.
Web Deleting - This occurs before a website is deleted. This is a synchronous before event.
Web Moved - This occurs after an existing website is moved. This is an asynchronous after event.
Web Moving - This occurs before a website is moved. This is a synchronous event.

3.2 List Level Events

Methods under the class SPListEventReceiver handle list level events. A brief overview of those methods is as follows.
Field Added - This occurs after a field link is added to a list.
Field Adding - This occurs when is field is being added to a content type.
Field Deleted - This occurs after a field is deleted from a list.
Field Deleting - This occurs when a field is being deleted from a list.
Field Updated - This occurs after a field is updated in a list.
Field Updating - This occurs when a field is being updated in a list.

3.3 Item Level Events

Methods under the class SPItemEventReceiver handle item level events. A brief overview of those methods is as follows.
ItemAdded - This occurs after a new item is added to a list. This is an asynchronous after event.
ItemAdding - This occurs before an item is added to a list. This is a synchronous before event.
ItemAttachmentAdded - This occurs after an attachment is added to a list. This is an asynchronous event.
ItemAttachmentAdding - This occurs while an attachment is being added to a list.
ItemAttachmentDeleted - This occurs after an attachment is removed from an item.
ItemAttachmentDeleting - This occurs while an attachment is being removed from an item.
ItemCheckedIn - This occurs after an item is checked in.
ItemCheckedOut - This occurs after an item is checked out.
ItemCheckingIn - This occurs while an item is being checked in.
ItemCheckingOut - This occurs while an item is being checked out.
ItemDeleted - This occurs after an item is deleted from its list.
ItemDeleting - This occurs while an item is being deleted from its list.
ItemFileConverted - This occurs when the type of file is being converted.
ItemFileMoved - This occurs after a file is moved.
ItemFileMoving - This occurs while a file is being moved.
ItemUncheckedOut - This occurs after un-checking an item in a list.
ItemUncheckingOut - This occurs while an item is being unchecked.
ItemUpdated - This occurs after an item is updated.
ItemUpdating - This occurs while an item is being updated.

3.4 Feature Events

Methods under the class SPFeatureReceiver handle events related to feature. A brief overview of those methods is as follows.
FeatureActivated - This occurs after a feature is activated.
FeatureDeactivating - This occurs when a feature is being deactivated.
FeatureInstalled - This occurs after a feature is installed.
FeatureUninstalling - This occurs when a feature is being uninstalled.

3.5 Email Events

Method under the class SPEmailEmailEventReceiver handles the event related to email. A brief overview of the method is as follows.
EmailReceived This occurs after an email message has arrived (to an email enabled list).

4. Binding the Event Receivers

For the event receivers to receive an event, they should be bound to the corresponding objects. This binding can be done in three ways.
Using a feature
Using a content type
Using WSS object model

4.1 Using Feature

In the feature, the elements.xml file should be as follows.
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/“>
……………………
……………………
<Receivers ListTemplateId=”100″>
< Receiver>
< Name>VideoAddedEventReceiver</Name>
< Type>ItemAdded</Type>
< SequenceNumber>20000</SequenceNumber>
< Assembly>MyProject.MyModule.Events, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0b231a5ff63cd9fa</Assembly>
< Class>MyProject.MyModule.Events.VideoAddedEventReceiver</Class>
< Data></Data>
< Filter></Filter>
< /Receiver>
………………………………
……………………………..
< /Receivers>
< /Elements>
Any number of receivers can be bound through one feature.
Limitation: Site level events cannot be registered/bound through the feature because we cannot associate a ListTemplateId with a site.

4.2 Using Content Type

In a content type, the elements.xml file should be as follows.
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/“>
<ContentType ID=”id” Name=”name” Group=”GroupName” Description=”Description of content type” Version=”0″>
< FieldRefs>
< FieldRef ID=”FIELD ID” Name=”FIELD NAME” />
…………………………
…………………………
< /FieldRefs>
< XmlDocuments>
< XmlDocument NamespaceURI=”http://schemas.microsoft.com/sharepoint/events“>
<spe:Receivers xmlns:spe=”http://schemas.microsoft.com/sharepoint/events“>
<Receiver>
< Name> VideoAddedEventReceiver </Name>
< Type> ItemAdded </Type>
< SequenceNumber>20000</SequenceNumber>
< Assembly> MyProject.MyModule.Events, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0b231a5ff63cd9fa </Assembly>
< Class> MyProject.MyModule.Events.VideoAddedEventReceiver</Class>
< Data></Data>
< Filter></Filter>
< /Receiver>
< /spe:Receivers>
< /XmlDocument>
< /XmlDocuments>
< /ContentType>
< /Elements>
The same limitation of ‘using feature’ applies to content type also because a content type cannot be associated with a site.
Sequence Number determines when the event receiver should get executed in case if more than one event receivers are about to be executed. An event receiver with greater sequence number gets executed after its counterpart with lesser sequence number.

4.3 Using WSS object model

The below is a sample code how an event receiver is bound with a list.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb web = properties.Feature.Parent as SPWeb;
web.Lists["Video Library"].EventReceivers.Add(
SPEventReceiverType.ItemAdded,
“MyProject.MyModule.Events, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0b231a5ff63cd9fa”,
” MyProject.MyModule.Events.VideoAddedEventReceiver “);
}
In the above code, the custom class ‘VideoAddedEventReceiver’ of type ‘ItemAdded’ is bound with a list named ‘Video Library’.

5. Unbinding SharePoint Event Receiver

• Event receiver bound with the help of content type cannot be unbound.
• If the event receiver was bound with the help of a feature, deactivating the feature would unbind the event receiver from its associated object.
• If the event receiver was bound using WSS object model,
1. Move to the object (site collection or website or list) to which the event receiver is bound.
2. Retrieve the event receiver definition of the intended event receiver.
3. EventReceiverDefinitionObject.Delete().
4. Call the update of that object (site collection or website or list).