SharePoint4us

Explore the Experience in SharePoint 2013

Friday, March 13, 2015

What are Event Receivers and How to Create Sample event Receivers and attach to Doc Library ?


Hi Friends,

Thanks for visiting my blog.
In  this blog, i would like to Post about  Event recivers in SharePoint 2013

1. What is Event Receiver ?
2. Why we use an event reciever ?
3. Types of  Event  Recivers?
4. Creation of Sample event Receivers and attach to Doc Library?
5. Interview Question on Event Recivers in SharePoint 2013, 2010


What is Event Receiver in SharePoint ?

In SharePoint you can add event handlers to the different lists, document libraries and content types within a SharePoint site.
Event handlers are defined in custom .NET assemblies. You can define event handlers for the different operations on list items, like adding a list item, updating a list item or deleting a list item.
Event handlers need to be registered and can best be installed and registered through the SharePoint feature framework.

Purpose of Event receivers

If you want to catch some action in SharePoint and want to do something on each action, then you can use event recivers. Event receivers are nothing but classes.
Sometimes they are called Before events and after events.

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.

Types of Event Recivers in SharePoint ?

There are synchronous and asynchronous events.

 Events ending by –ing are synchronous events: ItemAdding, ItemUpdating, ItemDeleting. Event handlers defined for these events are executed before the operation is executed on the content database. Asynchronous events are the events that end by –ed: ItemAdded, ItemUpdated, ItemDeleted. Event handlers for these events are executed after the operation is occurs in the content database.

Base Classes

There are different base classes from which you can inherit when developing event handlers. The decision from which class you are going to inherit depends on what you want to achieve with your event handler:
  •  SPItemEventReceiver: inherit from this class if you want your event handler to be executed when a list item is added, updated or deleted.
  •  SPListEventReceiver: inherit from this class if you want your event handler to be executed when the structure of your list is modified or when a content type is added or removed from the list.
  •  SPFeatureEventReceiver: you can add event handlers to a feature events like activation and deactivation, installation and deinstallation.
  •  SPEmailEventReceiver: you can also develop an event handler for emails that are sent to a SharePoint list
  •     SPWebEventReceiver: you can also handle events that occur when a site is added to or removed from a site collection.

 

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.

 

 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.

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.
I
temCheckedOut – 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.

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.

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).

 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




Creating a simple Event Receiver in SharePoint 2013 using  WSS Object Model.
 
Create an empty SharePoint 2013 project in Visual Studio 2012. In the project, select add new item and select Event Receiver


Select the type of event receiver you need to add, and select the events you need to handle.




In this sample I'm trying to update a SharePoint list based on file changes happening to a separate SharePoint library.

 Basically, the list will act like a log. So we need to create the library and a list.

 Here, I have created the Department library to add and maintain documents and also created Document Log list to log the changes happening to the library. 

In the list I have three columns, Title, Action & DateAndTime in order to catalog the changes happening to the library.



[The created document library and list]

Back to the SharePoint project. Now go to the event receiver .cs file and you'll get a bunch of methods base on your selection during event receiver creation. Edit the code as below to implement the logic. Note that the ItemAdded method is used instead of the ItemAdding method.


public override void ItemAdded(SPItemEventProperties properties)
        {
            //base.ItemAdded(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Added";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

public override void ItemUpdating(SPItemEventProperties properties)
        {
            //base.ItemUpdating(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Updated";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

public override void ItemDeleting(SPItemEventProperties properties)
        {
            //base.ItemDeleting(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Deleted";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }


As I am targeting to add the event receiver only to the Department document library, the Elements.xml file requires a change.



 Note that I have commented out the setting which points to all document libraries, instead pointed to Department document library. The edited Elements.xml file is as below:


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!--   <Receivers ListTemplateId="101"> -->
  <Receivers ListUrl="Lists/Department">

   <Receiver>

        <Name>DepartmentEventReceiverItemAdded</Name>
        <Type>ItemAdded</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MySharePointProject.ListEventReceiver.DepartmentEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>

      <Receiver>

        <Name>ListEventReceiverItemUpdating</Name>
        <Type>ItemUpdating</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MySharePointProject.ListEventReceiver.DepartmentEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
      <Receiver>
        <Name>ListEventReceiverItemDeleting</Name>
        <Type>ItemDeleting</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MySharePointProject.ListEventReceiver.DepartmentEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
</Receivers>
</Elements>

Compile and deploy the solution to your site. Now you may play around with the library and observe the changes happening to the list.... :)

I have added a document, uploaded, added, modified the 3 docs and then deleted one of the docs respectively.

 The below method start executes and logic excutes

 
And here's what I get in the DocumentLog list.




This is how we add an event recivers to SharePoint List /Doc Lib 1.What is event receiver?
An event receiver is a piece of managed code that responds to SharePoint events when specific triggering actions occur on a SharePoint object. Triggering actions include activities such as adding, updating, deleting, moving, checking in, and checking out.

2.         What Are Event Hosts?
Event hosts are common SharePoint objects that expect to receive events—in other words, objects whose event receivers "listen" for SharePoint events. These SharePoint event host object types include instances of common objects such as SharePoint site collections, sites, and lists. Each event host type has a specific set of event receiver base types from which it can inherit.

3.         What are the types of event receivers?
There are two types of event receivers available in SharePoint.
1. Syncronous Events: This event is executed in the same thread in which the triggering action is occurring. For example, when the user adds an item from the SharePoint user interface, the event is fully executed before returning to the user and showing that the item was added. These are before events that occurs before the currently requested operation happens.  This provides an opportunity for an event receiver to perform tasks before data is committed to a database. A good example of the use of Before events is performing data validation, because Before events fire prior to commitment of data. You can also use Before (or synchronous) events to cancel user actions—for example, if data validation fails.
(e.g. ItemAdding, ItemUpdating,ItemDeleting)

2. Asynchronous Events: This event occurs at a later time than the action that triggered it, and it executes on a thread that is different from the one in which the triggering action is running. These are after events. After events trigger event receivers that execute after user actions are committed to the content database; they invoke code that runs after the content database has been modified. This allows you to execute logic that occurs after a user has completed a specific action.
(e.g. ItemAdded, ItemUpdated,ItemDeleted)

4.         What is the base class for List events and List Item events?
The Base class for SharePoint events is   Microsoft.SharePoint.SPEventReceiverBase. The List and List Item events inherited based on the scope of event host as below.
   List Item: 
Microsoft.SharePoint.SPItemEventReceiver
  SharePoint List:  Microsoft.SharePoint.SPListEventReceiver

5.         How to cancel the actions using event receiver?
SharePoint before events(synchronous) can be cancelled since it get trigged before completing the operation. Any validation can be applied as well as the event can be cancelled using event properties.
E.g
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
if(condition=true)
{
properties.Cancel=True;
}
}
6.         What is the best practice to get the context of SPSite when using event receiver?
The event properties should be used to get the current SPContext. If we get the current context of the site in different object  like SPContext then your connection may get lose when your dispose the site context.  Use SPItemEventProperties.Site/SiteID properties to get the current context or use SPItemEventProperties.Context property.

7.         Best coding practice of event receiver?
a.       Enable / disable firing other event in the same SharePoint object to avoid unnecessary loops.
b.      Do not use SPcontext to get the site/web properties, instead user event properties to get site/web properties
c.       Dispose if any heavy object process in event receiver in final block
d.      Do not use RunWithElevatedPrevillege if event receiver planned to be deployed as sandbox solution
e.      Use UserToken to impersonate your current access.

8.         What is Enabling and Disabling event receiver?
SharePoint Event is nothing but triggering action occurs on a SharePoint object. The trigger may come from manual action (updating item manually) or automatic action (SPItem.Update). Both actions will fire the events. Sometimes it makes unnecessary events in the same list. These events many go infinitely and impact the server performance majorly. To avoid this unnecessary event firing, we can purposely enable/disable the other event firing on the same object. 
You can achieve this by executing the DisableEventFiring method on the list item. After the changes are saved you can activate the event handler again by executing the EnableEventFiring method on the list item.
Best practice is to execute the DisableEventFiring method right before any of the update methods and to execute the EnableEventFiring method right after one of the update methods.

9.         What is before property?
Get the string/value pairs in a hash table before the event occurred on the SharePoint item.

10.     What is after property?
Get the string/value pairs in a hash table after the event occurred on the SharePoint item.
11.     What is the difference between event receiver and workflow?
Workflows:
·         SharePoint Workflow consist a set of task(s) which can be triggered both manually and automatically.
·         SharePoint Workflows are created in SharePoint Designer, Microsoft Visio and of course through Visual Studio.
·         The workflow is triggered once an action is completed.
·         Workflow can be exported and imported
·         Workflow can be paused
·         Workflow can send mails without attachment
·         Does not required coding knowledge to work on SPD workflows
·         Multiple forms(initiation, task edit..) can be associated as part of workflow
Event Receivers:
·         SharePoint event receiver contains custom coding/logic which can be triggered automatically based on the event host type.
·         SharePoint event receivers can be created only in Visual Studio.
·         The events can be triggered before action or after action.
·         Events cannot be exported and imported
·         Events can be cancelled(synchronous) but cannot be paused
·         Even receivers  can send mails with attachment
·         Required coding knowledge
·         No custom forms associated as part of event actions





Thursday, March 12, 2015

What is Managed meta data service in SharePoint 2010, 2013 and how to Configure it?



Hi Friends,

Today , I would like to post  about Managed Metadata Service in SharePoint 2013.
Managed Metadata is a hierarchical collection of terms that can be associated with items in SharePoint 2010. We can use Central Administration website to manage these terms.

 Managed Metadata Service.
 The managed metadata service application makes it possible to use managed metadata and share content types across site collections and web applications.
A managed metadata service publishes a term store and, optionally, content types; a managed metadata connection consumes these. This article describes the managed metadata service and connections, and provides an example scenario for using them.

Metadata  
 Metadata is information about information. For example, the title and author is metadata about the book. Metadata can be many kinds of information -- a location, a date, or a catalog item number. When you use SharePoint products, you can manage the metadata centrally. You can organize the metadata in a way that makes sense in your business and use the metadata to make it easier to find what you want. 

 This is a new feature introduced  in SharePoint 2010.

Example: You have a document library to upload chapters. For each item you can specify a column metadata of category like CSharp, ASP.NET etc.


Why is the Purpose?

So you might be wondering that there exist list columns for the same purpose.
Following are some advantages provided by Managed Metadata:
1. Term Sets can be shared across a site collection or globally
2. Searching using Metadata gives more relevant result
           
                       Some Concepts inside Managed Metadata


 
Term: A term is keyword that can be associated with a SharePoint item.
Term Set: A term set is a group of terms. You can restrict that a particular item should contain a term from a particular term set. For example: setting the category of an chapter item from term set [c#, asp.net]
Local Term Sets: Site collection scoped term set. Only site user can see it.
Global Term Sets: Global Term Set created outside the site collection. They are visible to all users.
  
Managed Metadata Service
 The metadata is managed through Central Administration and using the Service Application Managed Metadata Service.

Practical

So now we can proceed to see how to setup Managed Metadata and use it along with a Document Library. Following are the activities involved:

1. Setup Term Store Administrator
2. Setup Term Set and Terms
3. Set Managed Metadata Column

How to configure managed meta data service?

We can configure the managed meta data service in central administration. 

Central Administration--> Application management-->Manage service applications 



In Manage service applications, add new managed meta data service as shown in the image below.


Add Name, Database name, Application pool name details in the popup as shown images below.

Name: Name of the service.
Database name: Name of the data base for the service.
Application Pool: Application pool to run the service.


Followed screen

  Managed meta data service will be created in the service applications. 

Check managed metadata web service is running in the services (Application management--> manage services)


After creating managed meta data service, we need to check the following properties (Managed meta data service--> Properties(top ribbon))



Default Keyword location: To store new enterprise keywords in the keyword set associated term store in the managed meta data or not.


Default term set location: To store term sets, while creating managed meta data site columns in managed meta data term store.


Use Content Types: This option will available only if the service has hub defined to share content types. This option need to select when to make content types that associated managed meta data service available to users of sites in the web application.


Push-down Content Type Publishing updates from the Content Type Gallery to sub-sites and lists using the content type: This option need to select when update the existing instances of the changed content types in sub-sites and libraries.


Check the permissions for managed meta data service (Select the service--> click on Administrators (top ribbon)), assign administrator to the service as shown the images below.


 Select the Service and click on Administrators in ribbon.


By clicking on the managed meta data service, it will redirect to managed meta data screen as shown in the image below. There we can create new groups, term sets and terms.



 
 RC on Managed Meta data Services


Give Name as Courses
 

Right Click on Courses



Create a List Column 






New Form 



Select the course Details



Now you can Able to see the  Course details


finally , we have configured the managed metadata service and used in the list .

 Hope  you like this post...



Tuesday, March 3, 2015

How to Insert, Update Delete List items using REST API in SharePoint2013 ?

Hello,

In this post we are going learn how to do CRUD(Create, Read, Update and Delete) operations using SharePoint2013 REST API .


Before learning how to write the script, you should know where to write the script?

This depends on your requirement, lets suppose if you are implementing a visual web part then you can write the script on your user control( .ascx file) in script tag as shown below. You can write your script in a function and then call that function wherever you want.

In the below script I am calling the script on document ready function

<script type="text\javascript">

$(document).ready( function(){

             // Calling function 
             GetListItembyID();

});

function GetListItembyID(){

            //write your script to get the list item based on id here

}

</script>

Or else you can write the script in a Content Editor web part like as mentioned above.


Reading list item based on item id

Here is the following scenario, I just want to fetch some data based on item id from a list.

In this case we need to use GET http method to fetch/read items. Following are the sample snippets which I used to fetch some of the columns(Title, Name, Email ) information of the item having ID as 1 from the list titled EMPMaster.


$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/getitembyid('1')/?$select=Title, Name, Email",
              type: "GET",
              headers: {
                               "accept":  "application/json; odata=verbose"
                            },
              success: function(data){
                                alert(data.d.Title); //You will get title here
                                alert(data.d.Name); //You will get name here
                                alert(data.d.Email); //You will get email here
                            },
              error: function(err){
                                alert("Error while fetching list item: " + JSON.stringify(err));
                            }

          });


Reading multiple list items

In the below snippet I used to fetch columns(Title, Name, Email ) information of all items from the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items?$select=Title, Name, Email",
              type: "GET",
              headers: {
                               "accept":  "application/json; odata=verbose"
                            },
              success: function(data){
                               // Looping multiple items
                               $.each(data.d.results, function(index, item){
                                     alert(Item: " + index);
                                     alert(item.Title); //You will get title here
                                     alert(item.Name); //You will get name here
                                     alert(item.Email); //You will get email here
                                 });
                            },
              error: function(err){
                                alert("Error while fetching list items: " + JSON.stringify(err));
                            }

          });



Inserting list item

In the below snippet I have added list item having columns(Title, Name, Email ) values as "ABC", "XYZ", xyz@abc.com in to the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items",
              type: "POST",
              data: JSON.stringify({
                                                   '__metadata': {'type': 'SP.Data.EMPMasterListItem' },
                                                   'Title': 'ABC',
                                                   'Name': 'XYZ',
                                                   'Email': 'xyz@abc.com'
                                                }),
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val()
                            },
              success: function(data){
                              alert("Item added successfully!");
                            },
              error: function(err){
                                alert("Error while adding item: " + JSON.stringify(err));
                            }

          });



Updating list item based on item id

In the below snippet I have updated list item column "Name" value to "XYZ1" having id as 1  in the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items(1)",
              type: "POST",
              data: JSON.stringify({
                                                   '__metadata': {'type': 'SP.Data.EMPMasterListItem' },
                                                   'Name': 'XYZ1'
                                                }),
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "MERGE",
                               "If-Match": "*"
                            },
              success: function(data){
                              alert("Item updated successfully!");
                            },
              error: function(err){
                                alert("Error while updating item: " + JSON.stringify(err));
                            }

          });



Deleting list item based on item id

In the below snippet I have deleted list item having id as 1 in the list titled EMPMaster.

$.ajax({
              url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items(1)",
              type: "POST",
              headers: {
                               "Accept": "application/json;odata=verbose",
                               "content-type": "application/json; odata=verbose",
                               "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                               "X-HTTP-Method": "DELETE",
                               "If-Match": "*"
                            },
              success: function(data){
                              alert("Item deleted successfully!");
                            },
              error: function(err){
                                alert("Error while deleting item: " + JSON.stringify(err));
                            }

          });


So thats it for now. Hope you learn some basic operations using REST apis in SharePoint 2013.

Happy coding. Cheers!!! :)