转:http://msdn.microsoft.com/en-us/library/gg252010(v=office.14).aspx

Summary:  Learn how to create an event receiver for Microsoft SharePoint 2010 by using Microsoft Visual Studio 2010.

Applies to:  Microsoft SharePoint Foundation 2010 | Microsoft SharePoint Server 2010 | Microsoft Visual Studio 2010

Provided by:  Ben Hedges, Point8020

Microsoft Visual Studio 2010 provides a project type that enables you to build event receivers that perform actions before or after selected events on a Microsoft SharePoint 2010 site. This example shows how to add an event to the adding and updating actions
for custom list items.

This SharePoint Visual How To describes the following steps for creating and deploying an event receiver in Visual Studio 2010:

  1. Overriding the itemAdding event and the itemUpdating event.

  2. Verifying that the list to which the item is being added is the Open Position list.

  3. Elevating permissions so that the code can access a secure site to retrieve approved job titles.

  4. Comparing approved Job Titles with the title of a new item that is created in the
    Open Position list.

  5. Canceling the event when the Job Title is not approved.

In this example, a secure subsite contains a list named Job Definitions that specifies allowed job titles for roles in the organization. Along with job titles, the list also contains confidential salary information for the job title and
is therefore secured from users. In the main site, a list named Open Positions tracks vacancies in the organization. You create two event receivers for the
itemAdding and itemUpdating events that verify that the title of the open position matches one of the approved titles in the
Job Definitions list.

Prerequisites

Before you start, create the subsite and lists that you will need.

To create the Job Definitions subsite

  1. On the main site, on the Site Actions menu, click New Site.

  2. In the New Site dialog box, click Blank Site.

  3. On the right of the dialog box, click More Options.

  4. In the Title box, type Job Definitions.

  5. In the Web Site Address box, type JobDefinitions.

  6. In the Permissions section, click Use Unique Permissions, and then click
    Create.

  7. In the Visitors to this site section, select Use an existing group, and then select
    Team Site Owners. Click OK.

To create the Job Definitions list

  1. In the Job Definitions site, create a custom list named
    Job Definitions
    with the following columns:

    • Title (Default column)

    • MinSalary (Currency)

    • MaxSalary (Currency)

    • Role Type (Choice: Permanent, Contract)

  2. Add several jobs to this list. Note the titles that you specify for each job that you create because you will need them later.

To create the Open Positions list

  • In the parent site, create a custom list named Open Positions with the following columns:

    • Title (Default column)

    • Location (Single line of text)

Creating an Event Receiver

Next, create an Event Receiver project in Visual Studio 2010, and add code to the events receiver file.

To create a SharePoint 2010 event receiver in Visual Studio 2010

  1. Start Visual Studio 2010.

  2. On the File menu, click New, and then click
    Project
    .

  3. In the New Project dialog box, in the Installed Templates section, expand either
    Visual Basic or Visual C#, expand SharePoint, and then click
    2010.

  4. In the template list, click Event Receiver.

  5. In the Name box, type VerifyJob.

  6. Leave other fields with their default values, and click OK.

  7. In the What local site do you want to use for debugging? list, select your site.

  8. Select the Deploy as a farm solution option, and then click
    Next
    .

  9. On the Choose Event Receiver Settings page, in the What type of event receiver do you want? list, select
    List Item Events.

  10. In the What Item should be the event source? list, select
    Custom List
    .

  11. Under Handle the following events, select the An item is being added and the
    An item is being updated check boxes. Click Finish.

To modify the events receiver file

  1. In the events receiver file, add the following code to the class.

    Public Function CheckItem(ByVal properties As SPItemEventProperties) As Boolean
    Dim jobTitle As String = properties.AfterProperties("Title").ToString()
    Dim allowed As Boolean = False
    Dim jobDefWeb As SPWeb = Nothing
    Dim jobDefList As SPList
    Dim privilegedAccount As SPUser = properties.Web.AllUsers("SHAREPOINT\SYSTEM")
    Dim privilegedToken As SPUserToken = privilegedAccount.UserToken Try
    Using elevatedSite As New SPSite(properties.Web.Url, privilegedToken)
    Using elevatedWeb As SPWeb = elevatedSite.OpenWeb()
    jobDefWeb = elevatedWeb.Webs("JobDefinitions")
    jobDefList = jobDefWeb.Lists("Job Definitions") For Each item As SPListItem In jobDefList.Items
    If item("Title").ToString() = jobTitle Then
    allowed = True
    Exit For
    End If
    Next End Using
    End Using Return (allowed) Finally
    jobDefWeb.Dispose()
    End Try
    End Function
    bool checkItem(SPItemEventProperties properties)
    {
    string jobTitle = properties.AfterProperties["Title"].ToString();
    bool allowed = false;
    SPWeb jobDefWeb = null;
    SPList jobDefList;
    SPUser privilegedAccount = properties.Web.AllUsers[@"SHAREPOINT\SYSTEM"];
    SPUserToken privilegedToken = privilegedAccount.UserToken;
    try
    {
    using (SPSite elevatedSite = new SPSite(properties.Web.Url, privilegedToken))
    {
    using (SPWeb elevatedWeb = elevatedSite.OpenWeb())
    {
    jobDefWeb = elevatedWeb.Webs["JobDefinitions"];
    jobDefList = jobDefWeb.Lists["Job Definitions"];
    foreach (SPListItem item in jobDefList.Items)
    {
    if (item["Title"].ToString() == jobTitle)
    {
    allowed = true;
    break;
    }
    }
    }
    }
    return (allowed);
    }
    finally
    {
    jobDefWeb.Dispose();
    }
    }
  2. In the EventReceiver1 file, replace the ItemAdding method with the following code.

    Public Overrides Sub ItemAdding(properties as SPItemEventProperties)
    Try
    Dim allowed As Boolean = True If properties.ListTitle = "Open Positions" Then
    allowed = CheckItem(properties)
    End If If allowed = False Then
    properties.Status = SPEventReceiverStatus.CancelWithError
    properties.ErrorMessage = _
    "The job you have entered is not defined in the Job Definitions List"
    properties.Cancel = True
    End If Catch ex As Exception
    properties.Status = SPEventReceiverStatus.CancelWithError
    properties.ErrorMessage = ex.Message
    properties.Cancel = True
    End Try
    End Sub
    public override void ItemAdding(SPItemEventProperties properties)
    {
    try
    {
    bool allowed = true; if (properties.ListTitle == "Open Positions")
    {
    allowed = checkItem(properties);
    } if (!allowed)
    {
    properties.Status = SPEventReceiverStatus.CancelWithError;
    properties.ErrorMessage =
    "The job you have entered is not defined in the Job Definitions List";
    properties.Cancel = true;
    }
    }
    catch (Exception ex)
    {
    properties.Status = SPEventReceiverStatus.CancelWithError;
    properties.ErrorMessage = ex.Message;
    properties.Cancel = true;
    }
    }
  3. In the EventReceiver1 file, replace the ItemUpdating method with the following code.

    Public Overrides Sub ItemUpdating(properties as SPItemEventProperties)
    Try
    Dim allowed As Boolean = True If properties.ListTitle = "Open Positions" Then
    allowed = CheckItem(properties)
    End If If allowed = False Then
    properties.Status = SPEventReceiverStatus.CancelWithError
    properties.ErrorMessage = _
    "The job you have entered is not defined in the Job Definitions List"
    properties.Cancel = True
    End If Catch ex As Exception
    properties.Status = SPEventReceiverStatus.CancelWithError
    properties.ErrorMessage = ex.Message
    properties.Cancel = True End Try
    End Sub
    public override void ItemUpdating(SPItemEventProperties properties)
    { bool allowed = true; if (properties.ListTitle == "Open Positions")
    {
    allowed = checkItem(properties);
    } try
    { if (!allowed)
    {
    properties.Status = SPEventReceiverStatus.CancelWithError;
    properties.ErrorMessage =
    "The job you have entered is not defined in the Job Definitions List";
    properties.Cancel = true;
    }
    }
    catch (Exception ex)
    {
    properties.Status = SPEventReceiverStatus.CancelWithError;
    properties.ErrorMessage = ex.Message;
    properties.Cancel = true;
    }
    }

To deploy the project

  1. In Solution Explorer, right-click the project, and then click
    Deploy.

  2. In the SharePoint site, in the Open Positions list, click
    Add new item
    .

  3. In the Title field, provide a title for a job description that does not exist in the
    Job Definitions list in the secured subsite.

  4. Click Save. You receive a message from the event receiver.

  5. In the Title field, provide a title for a job description that exists in the
    Job Definitions list in the secured subsite.

  6. Click Save. The position is created.

  • The solution overrides the ItemAdding and ItemUpdating methods and verifies whether the list that is being added to is the
    Open Positions list. If it is, a call is made to the CheckItem method, passing in the properties that are associated with the event.

  • In the CheckItem method, the permissions are elevated to ensure successful access to the secured subsite. The job titles that are in the approved list are compared to the job title of the
    properties.AfterProperties property associated with the event. If any title matches, the
    allowedBoolean variable is set to true, and the method returns.

  • Depending on the value of the allowed variable, the calling method either permits the event or sets the
    properties.ErrorMessage property and then cancels the event using
    properties.cancel.

Creating SharePoint 2010 Event Receivers in Visual Studio 2010的更多相关文章

  1. SharePoint Development - Custom List using Visual Studio 2010 based SharePoint 2010

    博客地址 http://blog.csdn.net/foxdave 之前两次我们定义了内容类型和字段,我们现在用它们为这一讲服务--创建一个自定义列表. 打开Visual Studio,打开之前的工程 ...

  2. SharePoint Development - Custom Field using Visual Studio 2010 based SharePoint 2010

    博客地址 http://blog.csdn.net/foxdave 自定义列表的时候有时候需要自定义一些字段来更好地实现列表的功能,本文讲述自定义字段的一般步骤 打开Visual Studio,我们还 ...

  3. 在 Visual Studio 2010 中创建 SharePoint 2010 事件接收器

    Microsoft Visual Studio 2010 提供了一个可用于生成事件接收器的项目类型,事件接收器会在 Microsoft SharePoint 2010 网站上选择事件之前或之后执行操作 ...

  4. Visual Studio 2010 集成 SP1 补丁 制作 Visual Studio 2010 Service Pack 1 完整版安装光盘的方法

    Now that Visual Studio 2010 SP1 has been released, administrators and developers may wish to install ...

  5. Win7 32bit + Matlab2013b +Visual Studio 2010联合编程配置

    要建立独立运行的C应用程序,系统中需要安装Matlab.Matlab编译器.C/C++编译器以及Matlab C/C++数学库函数和图形库函数. Matlab编译器使用mbuild命令可以直接将C/C ...

  6. visual studio 2010 破解版 破解方法

    1.Microsoft Visual Studio 2010下载(均来自微软官网) 高级版(Premium) [建议下载]       http://download.microsoft.com/do ...

  7. Creating a SharePoint BCS .NET Connectivity Assembly to Crawl RSS Data in Visual Studio 2010

    from:http://blog.tallan.com/2012/07/18/creating-a-sharepoint-bcs-net-assembly-connector-to-crawl-rss ...

  8. SharePoint 2010中使用Visual Studio 2010进行方便快速的Web Part开发

    转:http://www.cnblogs.com/fatwhale/archive/2010/02/24/1672633.html 在Visual Studio 2010中,  已经集成了用于Shar ...

  9. [SharePoint 2010] Visual Studio 2010內撰寫視覺化WebPart超簡單

    新一代的Visual Studio 2010對於SharePoint 2010的專案撰寫,有非常另人讚賞的改進. 以往寫一個WebPart要搞好多雜七雜八的步驟,也要硬寫HTML輸出,當然有人說可以寫 ...

随机推荐

  1. 查看 dmp 字符集

    用Oracle的exp工具导出的dmp文件也包含了字符集信息,dmp文件的第2和第3个字节记录了dmp文件的字符集.如果dmp文件不大,比如只有几M或几十M,可以用UltraEdit打开(16进制方式 ...

  2. Android串口通信(基于Tiny6410平台)

    友善之臂的Android系统有他们自己编写的一个串口通信程序,网上没有找到他的源代码,而且界面操作不在一个界面,不是很方便,这里我自己写了一个粗糙点的串口通信程序. 同样这里还是调用友善之臂的frie ...

  3. python中精确输出JSON浮点数的方法

    有时需要在JSON中使用浮点数,比如价格.坐标等信息.但python中的浮点数相当不准确, 例如下面的代码: 复制代码代码如下: #!/usr/bin/env python import json a ...

  4. 关联式容器(associative containers)

    关联式容器(associative containers) 根据数据在容器中的排列特性,容器可分为序列式(sequence)和关联式(associative)两种. 标准的STL关联式容器分为set( ...

  5. JavaScript 隐式转换

    javascript 中的怪癖,js运算符隐式类型转换 x + "" //等价于 String(x) + x //等价于 Number(x),也可以写成x-0 !!x //等价于 ...

  6. C Primer Plus之C预处理器和C库

    编译程序前,先由预处理器检查程序(因此称为预处理器).根据程序中使用的预处理器指令,预处理器用符号缩略语所代表的内容替换程序中的缩略语. 预处理器不能理解C,它一般是接受一些文件并将其转换成其他文本. ...

  7. Eclipse通过集成svn实现版本控制

    Eclipse通过集成svn即安装subclipse插件 前面已经讲解过了,这就不说了,作为测试人员继续总结下Eclipse通过集成svn实现的版本控制 首次从SVN代码库中导出代码文件: 1.右键工 ...

  8. leetcode:两个数的和||

    两个数的和|| 给定一个排序数组,求出其中两个数的和等于指定target时,这两个数在原始数组中的下标,返回的下标从1开始 解题 原始数组已经是升序的,找出其中两个数的和等于target 定义两个指针 ...

  9. DOS命令 Net config server Net config workstation

    DOS命令 Net config 作用:显示当前运行的可配置服务,或显示并修改某项服务的设置. 格式:net conifg service options 参数:(1)键入不带参数的net conif ...

  10. 使用exe4j把JAVA GUI程序打包成exe文件时遇到的问题

    1.把项目打包成jar文件时,只要勾选src目录就行了,其他的比如资源文件和jar包是不能添加进去的. 2.在D盘建一个文件夹,最好与项目同名,然后把打包好的jar包放进去,其他资源文件(图片之类的) ...