How to retrieve current user in SharePoint 2013 Online using CSOM

In this post, we’ll see how we can retrieve the current user in a SharePoint 2013 online site using client side object model (CSOM). We’ll  be using a console application for the purpose of this demonstration.

Open Visual Studio 2013

File –> New Project –> C# –> Console application

Add  reference to the following assemblies.

Microsoft.SharePoint.Client.dll

Microsoft.SharePoint.Client.runtime.dll

Import the following namespaces at the top of Program.cs

using  Microsoft.SharePoint.Client;
using System.Security;

namespace Retrievecurrentuser
{
    class Program
    {
        static void Main(string[] args)
        {

            using (ClientContext oClientContext = new ClientContext(@"https://yoursite.sharepoint.com"))
            {

                //Assign User Id for your SharePoint Online tenant     
                string UserName = "userid@yoursite.onmicrosoft.com";

                //Assign password for your SharePoint online tenant
                string Password = "password";

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


                //load the properties of web object
                Web oWeb = oClientContext.Web;
                oClientContext.Load(oWeb);
                oClientContext.ExecuteQuery();

                //retrieve the site name
                string SiteName = oWeb.Title;

                //retrieve the current user
                oClientContext.Load(oWeb.CurrentUser);
                oClientContext.ExecuteQuery();

            Console.WriteLine("Login Name"+ oClientContext.Web.CurrentUser.LoginName);
                Console.WriteLine("Is Admin"+ oClientContext.Web.CurrentUser.IsSiteAdmin);
                Console.WriteLine("Email"+ oClientContext.Web.CurrentUser.Email);
                
                Console.ReadLine();


            }
        }

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

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

            }
            return oSecurePassword;
        }

    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Then create a clientcontext in the program.cs, load the web object (execute query) and then load the current user based on the web object.

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Now we’ll be able to fetch the user properties like the below.

image

 Subscribe to my blog

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 https://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=" />

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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" />

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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)


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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  FilesCommon 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();           
            }
       
        }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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 to add a Calender App to Office 365 E3 public SharePoint Site

In this article, I’d deal with how to add a Calender App to Office 365 E3 public SharePoint site.  I came across this scenario when I was designing an Office 365 public facing site for the User Group in Chennai. When you subscribe for an Office 365 E3 subscription, you’ll get a public facing Sharepoint site.

Office 365 E3 Calender1

You’ll see a Calender App missing in the Site Contents when you try to add an App. You need to employ an work around to achieve this one.

Add Custom List App

Office 365 E3 Calender2

Go to List Settings –> Advanced Settings –> Enabled Management of Content Types

Office 365 E3 Calender3

Add from existing Site Content Types

Office 365 E3 Calender4

Click Ok.

Change new button order and default content type and set Event as default content type

Office 365 E3 Calender5

Now we have added the Calender App and we create events here.

 

 

 Subscribe to my blog

Deprecation of Custom Managed Code in Sandbox Solutions

Microsoft SharePoint product team has officially clarified yesterday that they are deprecating managed code in Sandbox Solutions.

http://blogs.msdn.com/b/sharepointdev/archive/2014/01/14/deprecation-of-custom-code-in-sandboxed-solutions.aspx

This will impact us if we are working on migration to Office 365 SharePoint online.

If you have customization in existing SP 2010 environment, please consider the following alternatives if you want to move to Cloud.

http://blogs.msdn.com/b/richard_dizeregas_blog/archive/2013/07/16/app-approaches-to-common-sharepoint-customizations.aspx

 Subscribe to my blog

How to Add external users to SharePoint Online

I was wondering if there is a way to add external users to SharePoint Online. The external users are nothing but people who don’t have user accounts in the SharePoint Online environment. The access to external users can be provided by sending them an invitation through e-mail. I’ve learnt that we can send the e-mail invitation to any type of e-mail address such as *.gmail.com, *.yahoo.com or *.yourowndomain.com. However to log-in to the SharePoint online environment, the e-mail account has to be associated with a valid Microsoft account.

 

Click Share

pic1

Now the a email invite will be sent to the invitees (external users)

Open the e-mail invite and click the link on that.

pic2

To accept the invite, you need to have a valid Microsoft account.

pic3

This completes the sign-in process for the external user to the SharePoint Online Team site using a valid Microsoft account.

 Subscribe to my blog