Showing posts with label event receiver. Show all posts
Showing posts with label event receiver. Show all posts

Thursday, April 4, 2013

Programatically breaking inheritance and adding unique permission to List Items


Permission handling is something which makes SharePoint a favorite product within the industry. SharePoint has Permission levels in built for basic roles, however you can create your own permission levels and assign to Groups and then set those groups to access any site/library/list. Whenever a sub-site is created, it asks you if you want to inherit the permission from the parent site or want to create unique permissions. 

If you choose to inherit the permissions, it will copy the same set of permissions to the sub-site which will again be passed on to the lists/libraries you create. It may happen that for securing our content, we want to break this inheritance and want to assign unique permissions to restrict the users for certain actions and to make the content more secure. Inheritance can be broken manually using the Out of feature also and if you have a business logic in place, you can do it programmatically also. This blog post gives you code to break inheritance for items meeting certain criteria and assigning permissions to them explicitly. I am using ItemAdded() event receiver to do this. You can use it within workflow or any custom webpart as well.

SPGroup securityGroup = spWeb.SiteGroups["Security Group Name"]; 
SPRoleDefinition groupRole = spWeb.RoleDefinitions["Read"]; 

SPRoleAssignment roleAssign = new SPRoleAssignment(securityGroup); 
roleAssign.RoleDefinitionBindings.Add(groupRole); 

SPListItem listItem = spWeb.GetListItem("http://List Item URL"); 
listItem.BreakRoleInheritance(true); 
listItem.RoleAssegnments.Add(roleAssignment); 
listItem.Update();

Monday, April 1, 2013

Creating Event Recievers within Visual Studio 2010

Event receivers can be broadly seen as of two types:

Asynchronous (triggered before finishing of previous event)
          ItemAdding, ItemUpdating
Synchronous (triggered after finishing the previous event)
          ItemAdded, ItemUpdated

Follow Steps to create an event receiver with Visual Studio 2010 and SharePoint 2010 :
  • Open up Visual Studio 2010 with administrator privileges
  • Click File > New > Project
  • Under Installed templates, click SharePoint and then select Event Receiver (C# in my case). Enter the name, storage location and Solution name in the text box provided and click on OK.
    • It will then ask you to specify the site and trust level or scope of your solution. If you want to deploy it across your farm so that all web applications can make use of it, you should select Deploy as Farm Solution. However, with event receivers, it is not usual so we will select Deploy as Sandboxed solution, which means it will only be accessible to the sites where we activate this feature.
    • Now it will ask you to select the type of Event Receiver you would like to create. In our case it would be List Item Events. Then select what item should be the event source, here we will select Document Library as we want to create an item in document library and want our event receiver logic to run after that. You may want to select Picture library or a list here or as per your business scenario.

    • Now, check the events you would want to code for within your receiver. For the sake of example, I will check An Item was Added which means it will automatically create a method stub for me with ItemAdded method. Now click on Finish.


    Our development IDE is ready to use now and you can see the method stub for ItemAdded being created already.

    Copy and Paste the code below to your solution.
    using (SPWeb web = properties.OpenWeb())
    {
        //Name is a metadata column within my document library
        //Checking if the Name field is equal to Test
        if (properties.ListItem["Name"] == "Test") 
        {//If it is
            // Populating the Title field with some value
            properties.ListItem["Title"] = "Event handler works"; 
            // Updating the ListItem to incorporate the change. 
            // Necessary step, without this  the changes are not pushed to ListItem
            properties.ListItem.Update(); 
        }
    
    }
    
    
    Some more useful methods which can be used are
    //Name of the Document Library
    string DocLibraryName = properties.ListTitle.ToString();
    
    //Getting the Item ID
    int ItemID = properties.ListItem.ID;
    
    //Collection of Role Assignments - required for controlling permission to the Item
    SPRoleAssignmentCollection roleAssignment = properties.ListItem.RoleAssignments;
    

    Build the solution and deploy it. Go to your SharePoint site and activate it(if not already activated) and create any document library and create an item with Name as Test and see your event receiver in action.

    This event receiver will fire on all the document libraries within your site where you have activated the feature, if this is not the intended behaviour, use
    if(properties.ListTitle.ToString() == "DocumentLibraryName")
    
    And write all your logic within your IF block.

    For any queries please feel free to email me. If this post helped you, please share it and benefit more and more fellow SharePoint developers

    Friday, March 15, 2013

    Resizing an Image for consistency in SharePoint

    While implementing intranet within our organization, we configure MySites within SharePoint, upload the user profiles from Active Directory and give users the ability to upload their own picture. Also, while implementing any News, or any company information, updates on the home page of Intranet, we tend to put pictures beside the text we write. Now, the image for several notifications can be of several size if you don’t have an in-house designer who trims/resizes your pictures to be uploaded to SharePoint. So, here comes my solution to resize images as we upload them to a definitive size which can then be uploaded and shown to users on the SharePoint.

    I have created Synchronous event receiver to my Notification list where I am adding the image and the code resizes the image and uploads it to the list for a nice and consistent look and feel of your website.

    Copy and paste the code below into your ItemAdded method.

           public override void ItemAdded(SPItemEventProperties properties)
           {
               int _imageWidth = 0;
               int _imageHeight = 0;
    
               if (properties.ListTitle.ToLower().Equals("intranet pictures"))
               {
                   try
                   {
                       string _width = properties.ListItem.File.Properties["vti_lastwidth"].ToString();
                       string _height = properties.ListItem.File.Properties["vti_lastheight"].ToString();
    
                       if (Int32.TryParse(_width, out _imageWidth) && Int32.TryParse(_height, out _imageHeight))
                       {
                           //checking if the image height and weight is 120 (for the sake of example)
                           if (_imageWidth != 120 || _imageHeight != 120)
                           {
                               SPFile _imageFile = properties.ListItem.File;
    
                               MemoryStream _inputStream = new MemoryStream(_imageFile.OpenBinary(), true);
                               MemoryStream _outputStream = new MemoryStream();
    
                               Image _resizedImage = Image.FromStream(_inputStream).GetThumbnailImage(120, Int32.Parse(_height), null, IntPtr.Zero);
                               _resizedImage.Save(_outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    
                               _imageFile.SaveBinary(_outputStream, false);                          
    
                           }
                       }
                   }
                   catch (Exception ex)
                   {
                       properties.ListItem.Delete();
                       properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
                       //You can give the location of your custom error page here
                       properties.RedirectUrl = "/_layouts/Intranet_PictureRestrict/IntranetPicError.aspx";                   
                   }
               }
           }
    
    Let me know if you want to customize it more or have any queries.

    Wednesday, March 13, 2013

    SharePoint 2013 : Introduction to Event Receivers


    I installed the beta version of SharePoint 2013 recently and played around with it. The first impression I had after creating team sites and community sites was “WOW, it looks amazing”. I guess that’s how you react every time you see a new offering of SharePoint J
    This is my first post on SharePoint 2013; dedicated to something I use the most within SharePoint implementations, the Event Receivers.

    As SharePoint 2013 offers App development as part of Office 365 development suite, which also replaces the traditional sandboxed solutions available in SharePoint 2010, it becomes very easy to create apps and maintain them within SharePoint 2013.

    Event receivers are somewhat modified for SharePoint 2013 into two parts, namely 
    • Remote event receivers and
    • App Event receivers 
    I will write separately about how to create both of these event receivers in my future posts. In this blog I will explain what they are and how they can be used to suit our business needs.

    Remote Event Receivers

    These event receivers signify events that occur on items within any list or library. Say addition of an item, update of an item or deletion of an item. They can be synchronous and asynchronous in nature. Microsoft has modified a bit in this version of SharePoint, the way we deal this nature of event receivers. We will see it how later in this post.

    App Event Receivers

    These event receivers signify the events that occur to the app we are creating. Say app installation, app uninstalling or app upgrading.

    As we create a new remote event receiver or app event receiver in Visual Studio 2012, we need a web application where we would be deploying our app. By default the scope of the app will be the host web application mentioned. A web service is added to this web application to handle the events which contains two methods

    ProcessEvent()
    Handles events that occur before an action occurs, such as when a user adds or deletes a list item

    ProcessOneWayEvent().ProcessEvent()
    Handles events that occur after an action occurs, such as after a user adds an item to a list or deletes an item from a list

    Like in SharePoint 2010, we had synchronous and asynchronous event receivers, in 2013; we have these two methods which deals with the nature of the event receivers.

    Many other things remains same the way we used to deal with them in SharePoint 2010 and VS 2010 environment like adding more events within your event receiver solution, changing the event receiver to point to either Document Library or an Announcement list and so on.

    I will write more as and when I try new things within SharePoint 2013.