SharePoint2013 Study Notes— How to Create a Event Receiver and Add Feature Event Receivers

In the followingprocedure, you’ll expand this project by adding a simple event handler (anevent receiver) to a list instance to show how to handle events that occur inSharePoint items such as lists.

To How to Create a Event Receiver to re-name it when upload a document, such as: add-title

  1. Create a project named SP2013EventHander,and click OK
  1. Deploy as a farm solution, and Finish
  1.  Add new items, in the Templates pane ,select Event Receiver namedTitleAddEvent
  1. Click Add. In the What type of event receiver do you want? choose List Item Events.
  2. In the What item should be the event source? choose Document Library
  3. In the Handle the following events list, select theAn item was added, and then choose theFinish button.
  4.  In the Elements.xml
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Receivers ListUrl="documentTest">
          <Receiver>
            <Name>CustomEventReceiverItemAdded</Name>
            <Type>ItemAdded</Type>
            <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
            <Class>SP2013EventHander.CustomEventReceiver.CustomEventReceiver</Class>
            <SequenceNumber>10000</SequenceNumber>
          </Receiver>
      </Receivers>
    </Elements>
    

  5. In the cs resouces file:
    using System;
    using System.Security.Permissions;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    using Microsoft.SharePoint.Workflow;
    
    namespace SP2013EventHander.CustomEventReceiver
    {
        /// <summary>
        /// List Item Events
        /// </summary>
        public class CustomEventReceiver : SPItemEventReceiver
        {
            /// <summary>
            /// An item was added.
            /// </summary>
            public override void ItemAdded(SPItemEventProperties properties)
            {
                SPListItem item = properties.ListItem;
                String url = item.Url;
                int left=url.LastIndexOf('/')+1;
                url = url.Substring(left, url.Length - left);
                url = url.Split('.')[0];
                item["Title"]=url+"-add";
                item.SystemUpdate();
                //base.ItemAdded(properties);
            }
    
    
        }
    }



To How to Create a Event Receiver to re-name it when editing a document, such as: updated-title

  1. As above
  1. As above
  1.  Add new items, in the Templates pane ,select Event Receiver named TitleUpdatedEvent
  1. Click Add. In the What type of event receiver do you want? choose List Item Events.
  2. In the What item should be the event source? choose Document Library
  3. In the Handle the following events list, select the An item was updated, and then choose the Finish button.
  4.  In the Elements.xml
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Receivers ListTemplateId="101">
          <Receiver>
            <Name>TitleUpdatedEventItemUpdated</Name>
            <Type>ItemUpdated</Type>
            <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
            <Class>SP2013EventHander.TitleUpdatedEvent.TitleUpdatedEvent</Class>
            <SequenceNumber>10000</SequenceNumber>
          </Receiver>
      </Receivers>
    </Elements>
    

  5. In the cs resouces file
    using System;
    using System.Security.Permissions;
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Utilities;
    using Microsoft.SharePoint.Workflow;
    
    namespace SP2013EventHander.TitleUpdatedEvent
    {
        /// <summary>
        /// List Item Events
        /// </summary>
        public class TitleUpdatedEvent : SPItemEventReceiver
        {
            /// <summary>
            /// An item was updated.
            /// </summary>
            public override void ItemUpdated(SPItemEventProperties properties)
            {
                SPListItem item = properties.ListItem;
                String url = item.Url;
                int left = url.LastIndexOf('/') + 1;
                url = url.Substring(left, url.Length - left);
                url = url.Split('.')[0];
                item["Title"] = url + "-updated";
                item.SystemUpdate();
                //base.ItemUpdated(properties);
            }
    
    
        }
    }



To How to Create a List when avtivated a feature


1.Create a feature by right-clicking the Features node and selecting Add Feature. named CreateListEvent

2.Add an event receiver to the feature by right-clicking CreateListEvent in the Features node and selecting Add Event Receiver.

3.The event receiver class contains four commented-out methods that act as events. Replace the FeatureActivated and  method FeatureDeactivating with the following:
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;

namespace SP2013EventHander.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("8a8d3e44-549a-497e-9c17-8d22fbc12c14")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                // Get reference to SharePoint site.
                SPSite site = new SPSite("http://silv-vm-01");
                SPWeb web = site.OpenWeb("/");
                // Get reference to Announcements list.
                //SPField filed=web.Fields["Announcements"];
                //SPList list = web.Lists.Add("test", "new",Microsoft.SharePoint.SPDocTemplateCollection);
                web.Lists.Add("test", "new",Microsoft.SharePoint.SPListTemplateType.DocumentLibrary);
                web.Update();
            }

            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                // Get reference to SharePoint site.
                SPSite site = new SPSite("http://silv-vm-01");
                SPWeb web = site.OpenWeb("/");
                // Get reference to Announcements list.
                SPList announcementsList = web.Lists["Announcements"];

                // Add new announcement to Announcements list.
                SPListItem oListItem = announcementsList.Items.Add();
                oListItem["Title"] = "Deactivated Feature: " + properties.Definition.DisplayName;
                oListItem["Body"] = properties.Definition.DisplayName + " was deactivated on: " + DateTime.Now.ToString();
                oListItem.Update();

            }

            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

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

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章