Blog of Sundar Narasiman

SharePoint Conference Videos 2014

The SharePoint Conference 2014 videos are available in Channel9.
Please check it out
http://channel9.msdn.com/Events/SharePoint-Conference/2014

SharePoint 2013 Remote Event Receivers–Frequently asked questions

I was trying to compile the list of frequently asked questions on SharePoint 2013 Remote Event receivers, for my understanding. Here is the list that I compiled.

1. Can we run client-side code from remote event receivers?

No, we cannot run client-side code from remote event receivers

2. How does remote event receiver work fundamentally?

The User performs an action on SharePoint list or library. Based on the action event, the SharePoint communicates with the registered WCF service (defined for remote event). The WCF service communicates with Azure Access Control Services (ACS) and gets signed token from ACS. Using the signed token, the remote WCF services perform necessary action on the SharePoint list or library (based on action).

3. What are the various types of event scopes that are supported?

Remote event receivers are supported at list-level and library-level.

4. How do we debug remote event receivers?

Go to Project Properties in Visual Studio 2012 à SharePoint à Enable remote debugging

Then, set the Azure Service Bus End Point for debugging remote event receivers. Prior to that we  need to register for a Windows Azure Service Bus, please check this post http://sundarnarasiman.net/?p=107 for more details on registering an Azure Service Bus.

5. How do we debug remote event receivers?

Go to Project Properties in Visual Studio 2012 à SharePoint à Enable remote debugging

6. Whether the SharePoint 2010 event handler will work automatically after upgrading to SharePoint 2013?

There is no guaranteed that the SP 2010 Event Handler Solution Package will work 100% after upgrade. It may be require re-factoring SP 2010 event handler into an App for SharePoint in SharePoint 2013.

7. Can we have remote event receivers implemented as SharePoint Hosted App in SharePoint 2013?

No. The SharePoint 2013 Remote Event receivers require a WCF service to call back to SharePoint 2013 based on the fired event (remote). In order to host a WCF service, we need a remote Web project, which is feasible only in Auto Hosted App or Provider Hosted App. Hence remote event receivers can’t be implemented as SharePoint Hosted App (as of now).

8. What are the various types of App Models supported by Remote Event Receivers?

a)SharePoint Hosted Apps

b)Provider Hosted Apps

8. Does SharePoint 2013 remote event receivers support synchronous and asynchronous events?

Yes, the remote event receivers have support for both Synchronous and Asynchronous events. It has two methods ProcessEvent and ProcessOneWayEvent :-

ProcessEvent – this typically occurs before an action occurs like when a user adds or deletes and item. It is also called as Synchronous events which typically handles “-ing” events.

ProcessOneWayEvent – this typically occurs after an action occurs. It is also called as Asynchronous events which typically handles “-ed” events.

9. Can we have remote event receivers registered for Host Web in SharePoint?

By default remote event receivers in Visual Studio are registered for App Web only, not Host Web. We can use CSOM to explicitly register the event receiver for Host Web, assuming that App has already requested Permission to manage host web.

10. How SharePoint 2013 Remote event receivers work differently from SharePoint 2010 event receivers?

In SharePoint 2010, the event receivers which handles events of Lists, Libraries or Sites, runs the code on the SharePoint farm itself. In SharePoint 2013, the piece of the code which handles events (WCF) runs outside of SharePoint remotely.

 Subscribe to my blog

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

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

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

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

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

InfoPath Publishing error – The following url is not valid

I was involved in a SharePoint 2013 On-Premise Platform setup. After our successful installation we faced an issue as stated below.

Issue:

We were not able to publish any InfoPath form to  SharePoint site created in the 2013 environment, in spite of the site being accessible from the browser. When we try to publish the form we get the following error “The following url is not valid”. This is a quite common and annoying error message that you get when it comes to InfoPath publishing.

clip_image001

We got a HTTP 404 error when we analyzed the fiddler trace, while the InfoPath form is published to SharePoint.

clip_image002

Options attempted for Fix

After referring so many blogs, I patiently tried the following steps to fix this problem. But nothing worked.

• Checked if it has a root site collection. (Make sure the SharePoint application that contains the site you are publishing to, has a site in the root)

• Stopped the “System Event Notification” service

• Added the verb entry in the http Handler tag (Make sure that the <remove verb=”*” path=”*.asmx”/> is just under <httpHandlers> tag)

• Added a host entry for the URL and restarted the server

• Delete all sub keys of “Server Cache” key, they are in form of _http://xxxxxxx

• This seems to be the problem when your site is on a non-default port, Switched to port 80, still same error.

Resolution:

Upon troubleshooting this issue i found that InfoPath client was not able to find the root (/) site collection and it threw a HTTP 404 error in Fiddler.  We had to add the HTTP verbs (GET, POST, PUT, HEAD, etc.) explicitly in our IIS Server -> request filtering module which solved the particular issue that I was facing

After adding the verbs, verify the new verbs are in config file C:WindowsSystem32inetsrvconfigapplicationHost.config.

Verbs will be under /configuration/system.webServer/security/request Filtering/verbs section.

In a nutshell the PUT request to the site was failing, for which i had to add the verbs.

 Subscribe to my blog

How to publish a post to the Office 365 SharePoint 2013 Social Feed using Client Object Model (CSOM)

In this article, I’ll explain on how to post to Office 365 SharePoint Social Feed using .NET Client Object Model (CSOM).

Step1  Create a Console application by name ‘PublishToSocialFeed’

Step2 Add references to the following assemblies

Microsoft.SharePoint.Client
Microsoft.SharePoint.ClientRuntime
Microsoft.SharePoint.Client.UserProfiles

Step3 Add references to the following assemblies

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social
;

Step4

Create a Public Function by name ‘PublishPost’ and add the following snippet of code.

public static void PublishPost()
       {
           Uri oUri = new Uri(“
https://yoursite.sharepoint.com”);

           Office365ClaimsHelper claimsHelper = new Office365ClaimsHelper(oUri, “youruserid@yoursite.onmicrosoft.com”, “yourpassword”);
          
           using (ClientContext oClientContext = new ClientContext(oUri))
           {
               oClientContext.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;

               SocialFeedManager oSocialFeedManager = new SocialFeedManager(oClientContext);
              
               //Create an instance of Social Data Item object
               SocialDataItem oSocialDataItem = new SocialDataItem();
               oSocialDataItem.ItemType = SocialDataItemType.Link;
               oSocialDataItem.Text = “Google”;
               oSocialDataItem.Uri = “
http://google.com”;

               //Create an instance of Social Post Creation Data
               SocialPostCreationData oSocialPostCreationData = new SocialPostCreationData();
               oSocialPostCreationData.ContentText = “This is my first post”;

               oSocialFeedManager.CreatePost(null, oSocialPostCreationData);
               oClientContext.ExecuteQuery();

               Console.WriteLine(“Published a news feed”);
           }

       }
To know more about ‘Office 365 Helper’ class and active authentication for Office 365, please refer to Wictor Wilen’s article.

 Subscribe to my blog

How to retrieve list of installed Workflows in SharePoint 2013 Office 365 site using CSOM

In this article, I’d be articulating on how to retrieve list of installed workflows in SharePoint 2013 Office 365 site using Client Side Object Model (CSOM). Just to give a background the workflow framework in SP 2013 has undergone a major revamp, there are new WorkflowServicesManager and WorkflowDeploymentService objects, we’d also be leveraging the new APIs accordingly to retrieve

Create a console application and name it as ‘RetrieveInstalledWorkflows’.

Add references to the following dll’s.

Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
Microsoft.SharePoint.Client.WorkflowServices.dll

Import the following namespaces

using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.WorkflowServices;
using Microsoft.SharePoint.Client.WorkflowServices;
using Microsoft.SharePoint.Client.Workflow;

Create a static method by name ‘RetrieveInstalledWorkflows’ and implement the following snippet of code.

public static void RetrieveInstalledWorkflows()
{
    Uri oUri = new Uri(“
https://yoursite.sharepoint.com”);
   
  
    Office365ClaimsHelper claimsHelper = new Office365ClaimsHelper(oUri, “userid@yoursiter.onmicrosoft.com”, “your password”);
    using (ClientContext oClientContext = new ClientContext(oUri))
    {      

        oClientContext.ExecutingWebRequest += claimsHelper.clientContext_ExecutingWebRequest;
       
        //Get the instance of Workflow Services Manager
        WorkflowServicesManager oWorkflowServicesManager = new WorkflowServicesManager(oClientContext,oClientContext.Web);

        //Hook to WorkflowDeploymentService
        WorkflowDeploymentService oWorkflowDeploymentService = oWorkflowServicesManager.GetWorkflowDeploymentService();

        //Fetch all the installed workflows
        var oWorkflowDefinitionCollection = oWorkflowDeploymentService.EnumerateDefinitions(true);
        oClientContext.Load(oWorkflowDefinitionCollection);

 
        oClientContext.ExecuteQuery();

        foreach(var oWorkflowDefinition in oWorkflowDefinitionCollection)
        {
            Console.WriteLine(“Workflow”+oWorkflowDefinition.DisplayName);
        }

        Console.ReadLine();

    }

}

To know more about Office365ClaimsHelper class, please refer to Wictor Wilen’s article on active authentication

 Subscribe to my blog