Month: March 2014

How to create a simple Remote Event Receiver for a Custom List in Office 365 SharePoint 2013 site

Home | Office 365 | How to create a simple Remote Event Receiver for a Custom List in Office 365 SharePoint 2013 site

In this article, we’ll see how to create a remote event receiver for a custom list (in App Web) in SharePoint 2013 Online.  The Remote Event Receivers are components (classes) that makes SharePoint Apps to respond to events that occur in SharePoint lists or items.

Create a new App in Visual Studio 2012 and name it as ‘CustomListEventReceiver’

image

Set the Office 365 SharePoint site for debugging the App and select App Type as SharePoint Hosted App

image

Now the app project is created. The next step is to create or set up a Custom List in the App.

Right Click –> Add New Item –> List  and name it as ‘TestCustomList’

image

Select ‘Default(CustomList)’ for Create a custom list template and list instance of it –> Finish

image

Now the Custom List is created. The next step is to add the Remote Event Receiver.

Right Click –> Add New Item –> RemoteEventReceiver and name it as TestEventReceiver.

image

This creates a RemoteWeb Project containing .svc file listening for remote events . The whole ideas is that in SharePoint 2013, the event handling for Lists and Items happened outside of SharePoint in the WCF Service (inside RemoteWeb Project).

Select the following 3 events  to be handled

image

Now you’ll see a remote event receiver project (.svc file inside it) created as the part of the Solution.

image

Remove the ClientId and ClientSecret from Web.Config file

<add key="ClientId" value="b0b7eb35-8980-4910-a3f6-f7129bb16466" />
<add key="ClientSecret" value="oVS2tUbGHbnWEQMPk2i5VvwdyOH04iiWJZmp0N9HXSE=" />

Open the AppManifest.xml file and change the AppPrincipal to internal

<AppPrincipal>
   <Internal/>   
 </AppPrincipal>

Go to Project Properties in Visual Studio 2012 and set the following properties

image

Since this App is running in Office 365, we need to set an Azure Service Bus connection string is required for debugging the remote event receiver (.svc component). Otherwise, we’ll get this debugging error mentioned in one of my previous article.

Go to Elements.xml of default.aspx under Pages.xml.

Remove the following File tag in the Elements.xml

<File Path="PagesDefault.aspx" Url="Pages/Default.aspx" ReplaceContent="TRUE" />

Add the following File tag inside Elements.xml

 <File Path="PagesDefault.aspx" Url="Pages/Default.aspx" >
      <AllUsersWebPart WebPartZoneID="full" WebPartOrder="0">
        <![CDATA[ 
      <webParts>
      <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
      <metaData>
      <type
    name="Microsoft.SharePoint.WebPartPages.XsltListViewWebPart,
    Microsoft.SharePoint,Version=14.0.0.0,Culture=neutral,
    PublicKeyToken=71e9bce111e9429c" />
      <importErrorMessage>
      Cannot import this Web Part.
      </importErrorMessage>
      </metaData>
      <data>
        <properties>
          <property name="Title"
           type="string">TestCustomList</property>
          <property name="ListDisplayName"
           type="string">TestCustomList</property> 
           <property name="ChromeType"
           type="chrometype">TitleOnly</property>
        </properties>
      </data>
    </webPart>
  </webParts>
]]>
      </AllUsersWebPart>
    </File>

The above File element inserts an XSLST List View web part to render the list items of TestCustomList with the column name Title.

Open default.aspx and add the following webpart definition inside the  PlaceHolderMain (just outside of the div containing <p> with id as message)

<WebPartPages:WebPartZone runat="server" FrameType="TitleBarOnly" ID="full" Title="loc:full" />

Open TestEventReceiver and implement the ProcessEvent(SPRemoteEventProperties properties) method for the ItemAdding and ItemDeleted events

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;

namespace CustomListEventReceiverWeb.Services
{
    public class TestEventReceiver : IRemoteEventService
    {
        public SPRemoteEventResult ProcessEvent(SPRemoteEventProperties properties)
        {
            SPRemoteEventResult oResult = new SPRemoteEventResult();
                       
            

            switch (properties.EventType)
            {
                case SPRemoteEventType.ItemAdding:


                   
                    
                    oResult.ChangedItemProperties.Add("Title", properties.ItemEventProperties.AfterProperties["Title"] += "Sundar");
                    break;

                case SPRemoteEventType.ItemDeleting:
                    oResult.ErrorMessage = "You cannot delete this list item";
                    oResult.Status = SPRemoteEventServiceStatus.CancelWithError;
                    break;
            }


            return oResult;
        }

        public void ProcessOneWayEvent(SPRemoteEventProperties properties)
        {
            if (properties.EventType == SPRemoteEventType.ItemAdded)
            {
                //Do something here ...
            }
        }
    }
}

Hit F5 and run the CustomListEventReceiver app

Now we’ll see the  item Title appended with “Sundar” (execution of ItemAdding event)

image

 

image

When we try to delete the item, it throws an error message “You cannot delete this list item” (execution of item deleted event).

image

 Subscribe to my blog

How to Execute KeyWord Search in Office 365 SharePoint 2013 site using CSOM

Home | Office 365 | How to Execute KeyWord Search in Office 365 SharePoint 2013 site using CSOM

In this post, we’ll see how we can programmatically execute Search Queries for Keywords using SharePoint 2013 Client Side Object Model (CSOM).

Create a Console Application in Visual Studio 2013 and name it as KeyWordSearch

Add a reference to Microsoft.SharePoint.Client.dll

image

Add a reference to Microsoft.SharePoint.Client.Search.dll and it is available in the location C:Program  Files\Common FilesMicrosoft Sharedweb server extensions15ISAPI

image

Add a reference to Microsoft.SharePoint.Client.Runtime.dll

When I fire a Search Query using the keyword ‘Sundar’ in online portal, it gives the below results.

image

We’ll attempt the same by invoking the SearchQuery using manged .NET Client Side Object Model (CSOM). We’ll be leveraging SearchExecutor class and KeyWordQuery class in the Microsoft.SharePoint.Client.Search and Microsoft.SharePoint.Client.Search.Query namespaces and invoking ExecuteQuery method to get the results back.

Replace the Program.cs with the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Search;
using Microsoft.SharePoint.Client.Search.Query;

namespace ExecuteKeywordSearch
{
    class Program
    {
        static void Main(string[] args)
        {
            //Assign User Id for your SharePoint Online tenant    
            string UserName = “youruserid@yoursite.onmicrosoft.com”;

            //Assign password for your SharePoint online tenant
            string Password = “yourpassword”;

            //Create a SecureString object from password string, needed for SharePointOnlineCredentials class
            SecureString SecurePassword = GetSecureString(Password);

            using (var oClientContext = new ClientContext(“https://yoursite.sharepoint.com/”))
            {
                //assign SharePoint Online Credentials to ClientContext Class
                oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);

                //Create an instance of KeywordQuery Class
                KeywordQuery oKeyWordQuery = new KeywordQuery(oClientContext);
               
                //Assign the Search Query
                oKeyWordQuery.QueryText = “Sundar”;

                //Associate SearchExecutor with ClientContext
                SearchExecutor oSearchExecutor = new SearchExecutor(oClientContext);
               
                //Execute the Search Query
                ClientResult<ResultTableCollection> oResultTables = oSearchExecutor.ExecuteQuery(oKeyWordQuery);

                oClientContext.ExecuteQuery();

                foreach (var oResultRow in oResultTables.Value[0].ResultRows)
                {
                    Console.WriteLine(oResultRow[“Title”].ToString());
                    Console.WriteLine(“n” + oResultRow[“Path”].ToString());

                }

 

                Console.ReadLine();

            }

        }

        private static SecureString GetSecureString(String Password)
        {
            SecureString oSecurePassword = new SecureString();

            foreach (Char c in Password.ToCharArray())
            {
                oSecurePassword.AppendChar(c);

            }
            return oSecurePassword;
        }

    }
}

When we execute the above piece of code, we’ll see the following search results that matches with screenshot (manual search) illustrated above.

image

 

 Subscribe to my blog

How to get Count and List of documents and sites followed by a User in Office 365 SharePoint 2013 Site using CSOM

Home | Office 365 | How to get Count and List of documents and sites followed by a User in Office 365 SharePoint 2013 Site using CSOM

In this post, we will see how to retrieve list of followers for a document in Office 365 SharePoint site using .NET Client Object Model (CSOM).

Create a Console application and name it as ‘GetFollowers’

Add a reference to the following assemblies to the Console application.

Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
Microsoft.SharePoint.Client.UserProfiles.dll

Add a new C# class and name it as GetFollower.cs

Copy and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.UserProfiles;
using Microsoft.SharePoint.Client.Social;
using System.Security;

namespace GetFollowers
{
    public class GetFollowers
    {

        public void RetrieveFollowedCount()
        {
            using (var oClientContext = new ClientContext(“
https://yoursite.sharepoint.com/”))
            {

                string UserName = “userid@yoursite.onmicrosoft.com”;
                string Password = “password”;

                SecureString oSecureString = GetSecureString(Password);

                oClientContext.Credentials = new SharePointOnlineCredentials(UserName, oSecureString);

                //Instantiate SocialFollowingManager instance
                SocialFollowingManager oSocialFollowingManager = new SocialFollowingManager(oClientContext);

                //Instantiate SocialActorInfo class
                //SocialActorInfo oSocialActorInfo = new SocialActorInfo();
                //oSocialActorInfo.ContentUri = sDocUrl;
                //oSocialActorInfo.ActorType = SocialActorType.Document;

                //Invoke this private method to get the count of followed documents and sites
                GetFollowedCount(oClientContext, oSocialFollowingManager);

                //Invoke this private method to get actual list of documents and sites (objects)
                GetFollowedDocuments(oClientContext, oSocialFollowingManager);

                    Console.ReadLine();

               

            }
        }

        private static void GetFollowedCount(ClientContext oClientContext, SocialFollowingManager oSocialFollowingManager)
        {
            //Set the SocialActorType as documents to get count of documents followed by user
            ClientResult<int> oFollowedDocsCount = oSocialFollowingManager.GetFollowedCount(SocialActorTypes.Documents);
            oClientContext.ExecuteQuery();
            Console.WriteLine(“n”+”Total number of documents followed   :” + oFollowedDocsCount.Value.ToString());

            //Set the SocialActorType as documents to get count of sites followed by user
            ClientResult<int> oFollowedSiteCount = oSocialFollowingManager.GetFollowedCount(SocialActorTypes.Sites);
            oClientContext.ExecuteQuery();
            Console.WriteLine(“n”+”Total number of sites followed    :” + oFollowedSiteCount.Value.ToString());

            //Set the SocialActorType as documents to get count of user followed by user
            ClientResult<int> oFollowedUserCount = oSocialFollowingManager.GetFollowedCount(SocialActorTypes.Users);
            oClientContext.ExecuteQuery();
            Console.WriteLine(“n”+”Total number of users followed    :” + oFollowedUserCount.Value.ToString());
        }

        private static void GetFollowedDocuments(ClientContext oClientContext, SocialFollowingManager oSocialFollowingManager)
        {

            ClientResult<SocialActor[]> oSocialActors = oSocialFollowingManager.GetFollowed(SocialActorTypes.Documents);
            oClientContext.ExecuteQuery();

            foreach (SocialActor oSocialActor in oSocialActors.Value)
            {
                Console.WriteLine(“n”+”Name of followed document    :”+oSocialActor.Name);
                Console.WriteLine(“n”+”Document uri    :”+oSocialActor.ContentUri);
                Console.WriteLine(“n”+”Status    :”+oSocialActor.Status);

            }
        }

        //this method formats the input string into array of characters and place into SecureString object
        private static SecureString GetSecureString(String Password)
       {
           SecureString oSecurePassword = new SecureString();

           foreach (Char c in Password.ToCharArray())
           {
               oSecurePassword.AppendChar(c);

           }
           return oSecurePassword;
       }

 

       
        }
   
}

The whole idea is that we are leveraging GetFollowedCount  method of SocialFollowingManager class to get count of documents and sites and we are leveraging GetFollowed method of SocialManager class to actually find out the documents (in the above).

Invoke this class from Program.cs

static void Main(string[] args)
       {

           GetFollowers oGetFollowers = new GetFollowers();

           oGetFollowers.RetrieveFollowedCount();
       }

 

Run the application and we will see the results below.

image

 Subscribe to my blog

Follow a document in Office 365 SharePoint site using .NET CSOM

Home | Office 365 | Follow a document in Office 365 SharePoint site using .NET CSOM

In this article, I’d be covering on how to programmatically follow a document in Office 365 SharePoint Site using .NET Client Side Object Model (CSOM). I will be using SharePointOnlineCredentials available in Microsoft.SharePoint.Client.Runtime assembly to connect to Office 365 SharePoint site. In my previous posts related to Office 365, I was leveraging the MSOnlineClaimsHelper (Active Authentication) by Wictor Wilen, which is still valid and I believe the same functionality has been brought into SharePointOnlineCredentials class..

Create a Console Application in Visual Studio 2013 and name it as FollowDocument

Create a new class by name FollowDocument.cs

Add reference to the following assemblies in FollowDocument.cs

Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
Microsoft.SharePoint.Client.UserProfiles.dll

Add the following namespaces to FollowDocument.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Security;
using Microsoft.SharePoint.Client.UserProfiles;
using Microsoft.SharePoint.Client.Social
;

Add a public method named StartFollowing with following code snippet

using (var context = new ClientContext(“https://sharepointsundar.sharepoint.com/”))
            {
                String docurl = “
https://yoursite.sharepoint.com/Shared%20Documents/HOL_High%20Trust%20Provider%20App.docx”;
             
                String UserName = userid@yoursite.onmicrosoft.com;
                String Password = “your password”;

                SecureString SecurePassword = GetSecureString(Password);                            
                context.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);              

                //Instantiate SocialFollowingManager instance
                SocialFollowingManager oSocialFollowingManager = new SocialFollowingManager(context);

                //Instantiate SocialActorInfo class
                SocialActorInfo oSocialActorInfo = new SocialActorInfo();
                oSocialActorInfo.ContentUri = docurl;
                oSocialActorInfo.ActorType = SocialActorType.Document;

                //Check whether the current user is already following the item
                ClientResult<bool> bFollowFlag = oSocialFollowingManager.IsFollowed(oSocialActorInfo);
                context.ExecuteQuery();
                Console.WriteLine(“Is the current user following this document:” + bFollowFlag.Value);

                if (! bFollowFlag.Value)
                {
                    //If the document is not already followed by the user, start following it
                    ClientResult<SocialFollowResult> oResult = oSocialFollowingManager.Follow(oSocialActorInfo);
                    context.ExecuteQuery();
                }                                          

                               Console.ReadLine();           
            }
       
        }

In the above method, we are connecting to Office 365 SharePoint site using SharePointOnlineCredentials class, instantiating the SocialFollowingManager class and the SocialActorInfo class. We check for the status of Following of a Document by a user using ‘IsFollowed’ property of SocialFollowManager. Based on the Follow Status, we invoke ‘Follow’ method on SocialFollowManager class, to follow a document.

The next step is to Implement a Private method called GetSecureString() to get the SecureString object (representing the  password of Office 365 SharePoint site).

private static SecureString GetSecureString(String Password)
       {
           SecureString oSecurePassword = new SecureString();

           foreach (Char c in Password.ToCharArray())
           {
               oSecurePassword.AppendChar(c);

           }
           return oSecurePassword;
       }

 

Finally, we invoke the FollowDocument.StartFollowing method from Main method in Program.cs

static void Main(string[] args)
        {

            FollowDocument oFollow = new FollowDocument();
            oFollow.StartFollowing();
           
        }

image

 Subscribe to my blog

How SharePoint 2010 customizations can be mapped to SP 2013 App Model

Home | SharePoint 2013 App | How SharePoint 2010 customizations can be mapped to SP 2013 App Model

I tried to do a mapping on how the SharePoint 2010 server-side customization can be mapped to SP 2013 App Model, here is the list below.

No SP 2010 Farm Solution SP 2013 App Model
1

Alternate CSS in hive

Apps cannot deploy files to SharePoint’s root files/hive. Instead, css can be deployed to SharePoint using a module or app installed event

2

Alternate CSS in Module

Apps cannot deploy files to SharePoint’s root files/hive. Instead, css can be deployed to SharePoint using a module or app installed event

3 Application Page

Apps cannot deploy files to SharePoint’s root files/hive, which includes the layouts folder. As an alternative, web part pages can be deployed through a module or app installed event receiver

4 Custom Column

Declarative columns can only be deployed to the app web. To deploy columns to Host Web leverage App Installed Event

5 Content Type

Declarative content types can only be deployed to the app web. To deploy content types to App Web leverage App Installed Event

6 Custom Action Apps support specific types of custom actions, including ribbon commands and context menus in both the app web and host web.
7 Delegate Control

Apps for SharePoint do not support delegate controls. Add custom HTML snippet to the Master Page to achieve the effect of delegate controls

8 Feature Receiver

Apps have remote events for “App Installed”, “App Uninstalling”, and “App Upgraded”. All of these can be used in a similar way to feature receivers in farm solutions.

9 Feature Stapling

Apps can be “stapled” through the app catalog, leverage the concept of App Stapling

10 Images (in hive)

Apps cannot deploy files to SharePoint’s root files/hive. Instead, images can be deployed to SharePoint using a module or app installed event

11 List definition

Apps can deploy custom list definitions, but only to the app web and not the host web

12 List Event Receiver

Leverage Remote Event Receivers to address on-premise List Event Receivers for Cloud

13 List Instance

Declarative list instances can only be deployed to the app web and not the host web. `

14

Master Page (in hive)

Apps cannot deploy files to SharePoint’s root files/hive. Instead, master pages can be deployed to SharePoint using a module or app installed event
15

Master Page (Module)

Apps can use modules to deploy master pages to SharePoint, but only to the app web…not the host web. Leverage app installed event can be used to deploy a master page to a host web

16 Module

Apps can leverage modules to declaratively deploy files into SharePoint

17

Script (in hive)

Apps cannot deploy files to SharePoint’s root files/hive. Instead, script can be deployed to SharePoint using a module or app installed event

18 Search Configuration Apps for SharePoint can be used to consistently and efficiently deploy a search configuration to a number of sites
19 Site Definition

Site definitions deploy files into SharePoint’s root files/hive, which is not a capability of apps for SharePoint

20 Timer Jobs

Timer Jobs cannot be addressed in App Model

21

User Controls (Control Templates

Apps cannot deploy user controls to SharePoint hive, consider other alternatives

24 Webpart Apps can deploy App Parts to SharePoint
25 Web Part Page Leverage App Installed event to provision a web part page to the Host Web. However for App Web, leverage Modules.
26 Web Template Web Templates can be installed to the host web’s site collection root using the App Installed event
27 Workflow Workflow is supported in SP 2013 App Model
28 Workflow Activity Workflow activity is supported in SP 2013 App Model

 Subscribe to my blog