In this post, we’ll see how to get a SharePoint Group in SharePoint Online using REST. I’ll be using a SharePoint hosted app for the purpose of demonstration.
Launch Visual Studio 2013.
I will be accessing the following REST endpoint for getting a web title
index – an integer that refers a group uniquely in the site.
Since the call is initiating from AppWeb to HostWeb, it will present a classical cross-domain scenario, where I will be using the SP 2013 javascript cross-domain libraries to manage this call.
After creating the App project in Visual Studio 2013, the following points need to be considered.
a)The App Permission need to be left with default setting of Internal.
<AppPrincipal><Internal/></AppPrincipal>
With this setting, the SharePoint hosted app will have access to the Host Web by default.
b)The App need to be given the following permission.
c)The executor object need to be instantiated with the parameter of ‘AppWebUrl’, not the ‘HostWebUrl. (you’ll see more detailed code in the coming sections). If you instantiate it with ‘HostWebUrl, you will get an error like ‘App web not found’.
var executor = new SP.RequestExecutor(AppWebUrl);
d)To access the HostWeb rest end points the url property in the cross-domain call need to be set in this fashion.
e)Copy and paste the following code in the App.js (replace Ii t the existing code over there)
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var HostWebUrl;
var AppWebUrl;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
//getUserName();
HostWebUrl =
decodeURIComponent(
RetrieveQueryStringParameter("SPHostUrl")
);
AppWebUrl =
decodeURIComponent(
RetrieveQueryStringParameter("SPAppWebUrl")
);
var scriptbase = HostWebUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
});
function successHandler(data) {
var jsonObj = JSON.parse(data.body);
var results = jsonObj.d;
document.getElementById("message").innerText = "Field title is" + results["Title"] + "Field Id is" + results["Id"];
}
function errorHandler(data, errorCode, errorMessage) {
document.getElementById("message").innerText = "failure";
}
function RetrieveQueryStringParameter(ParamsforRetrieval) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == ParamsforRetrieval)
return singleParam[1];
}
}
function execCrossDomainRequest() {
var executor = new SP.RequestExecutor(AppWebUrl);
executor.executeAsync({
url: AppWebUrl + "/_api/SP.AppContextSite(@target)/web/sitegroups(3)?@target='" + HostWebUrl + "'",
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: successHandler,
error: errorHandler
});
}
Run the above piece of code, now you will be able to get the title and id for the site collection group (no: 3).
In this post, we’ll see how we can fetch the fields collection of a SharePoint web in SharePoint 2013 online using REST. For the purpose of demonstration, I’ll be using a SharePoint hosted app.
Launch Visual Studio 2013.
File –> New –> Office/SharePoint –> Apps and name it as ‘GetFieldsREST’
I will be accessing the following REST endpoint for getting a web title
Since the call is initiating from AppWeb to HostWeb, it will present a classical cross-domain scenario, where I will be using the SP 2013 javascript cross-domain libraries to manage this call.
After creating the App project in Visual Studio 2013, the following points need to be considered
a)The App Permission need to be left with default setting of Internal.
<AppPrincipal><Internal/></AppPrincipal>
With this setting, the SharePoint hosted app will have access to the Host Web by default.
b)The App need to be given full-control permission for site-collection. Otherwise, it will not be able to fetch the fields collection.
c)The executor object need to be instantiated with the parameter of ‘AppWebUrl’, not the ‘HostWebUrl. (you’ll see more detailed code in the coming sections). If you instantiate it with ‘HostWebUrl, you will get an error like ‘App web not found’
var executor = new SP.RequestExecutor(AppWebUrl);
d)To access the HostWeb rest end points the url property in the cross-domain call need to be set in this fashion.
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var HostWebUrl;
var AppWebUrl;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
//getUserName();
HostWebUrl =
decodeURIComponent(
RetrieveQueryStringParameter("SPHostUrl")
);
AppWebUrl =
decodeURIComponent(
RetrieveQueryStringParameter("SPAppWebUrl")
);
var scriptbase = HostWebUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
});
function successHandler(data) {
var jsonObj = JSON.parse(data.body);
var results = jsonObj.d;
document.getElementById("message").innerText = "Field title is" + results["Title"] + "Field Id is" + results["Id"];
}
function errorHandler(data, errorCode, errorMessage) {
document.getElementById("message").innerText = "failure";
}
function RetrieveQueryStringParameter(ParamsforRetrieval) {
varparams =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == ParamsforRetrieval)
return singleParam[1];
}
}
function execCrossDomainRequest() {
var executor = new SP.RequestExecutor(AppWebUrl);
executor.executeAsync({
url: AppWebUrl + "/_api/SP.AppContextSite(@target)/web/fields?@target='" + HostWebUrl + "'",
method: "POST",
body: "{ '__metadata': { 'type': 'SP.Field' }, 'Title': 'Comments', 'FieldTypeKind': 3 }",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: successHandler,
error: errorHandler
});
}
In this post, we’ll see how we can access the property of a SharePoint web in SharePoint 2013 online using REST. For the purpose of demonstration, I’ll be using a SharePoint hosted app.
Launch Visual Studio 2013.
File –> New –> Office/SharePoint –> Apps and and name it as ‘GetWebdetailsREST’
I will be accessing the following REST endpoint for getting a web title
Since the call is initiating from AppWeb to HostWeb, it will present a classical cross-domain scenario, where I will be using the SP 2013 javascript cross-domain libraries to manage this call.
After creating the App project in Visual Studio 2013, the following points need to be considered
a)The App Permission need to be left with default setting of Internal.
<AppPrincipal><Internal/></AppPrincipal>
With this setting, the SharePoint hosted app will have access to the Host Web by default.
b)The App need to be given read permission for site-collection
c)The executor object need to be instantiated with the parameter of ‘AppWebUrl’, not the ‘HostWebUrl. (you’ll see more detailed code in the coming sections). If you instantiate it with ‘HostWebUrl, you will get an error like ‘App web not found’
var executor = new SP.RequestExecutor(AppWebUrl);
d)To access the HostWeb rest end points the url property in the cross-domain call need to be set in this fashion.
'use strict';
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
var HostWebUrl;
var AppWebUrl;
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
//getUserName();
HostWebUrl =
decodeURIComponent(
RetrieveQueryStringParameter("SPHostUrl")
);
AppWebUrl =
decodeURIComponent(
RetrieveQueryStringParameter("SPAppWebUrl")
);
var scriptbase = HostWebUrl + "/_layouts/15/";
$.getScript(scriptbase + "SP.RequestExecutor.js", execCrossDomainRequest);
});
// This function prepares, loads, and then executes a SharePoint query to get the current users information
function getUserName() {
}
function successHandler(data)
{
var jsonObj = JSON.parse(data.body);
document.getElementById("message").innerText = "Web title from REST call is"+ jsonObj.d["Title"];
}
function errorHandler(data, errorCode, errorMessage) {
document.getElementById("message").innerText = "failure";
}
function RetrieveQueryStringParameter(ParamsforRetrieval) {
var params =
document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == ParamsforRetrieval)
return singleParam[1];
}
}
function execCrossDomainRequest() {
var executor = new SP.RequestExecutor(AppWebUrl);
executor.executeAsync(
{
url: AppWebUrl + "/_api/SP.AppContextSite(@target)/web/title?@target='" + HostWebUrl + "'",
type: "GET",
crossDomain:true,
headers: {
"accept": "application/json; odata=verbose",
"content-type": "application/json;odata=verbose",
"content-length": 1028,
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: successHandler,
error: errorHandler
}
);
}
Now you can see the updated site title in the App. This completes this demo.
In this post, we’ll see how we can enable multi-factor authentication for Office 365. The concept of multi-factor authentication has be become increasingly popular nowadays for bringing the additional layer of security hardening. Multi-factor authentication is a form of authentication, which enforces more than one form of authentication to verify the legitimacy of the transactions performed by a user. Nowadays, the most common form of second-form of authentication in to validate the Authorization code by sending it to the user’s mobile devices.
Let’s see the steps to enable multi-factor authentication in Office 365.
Log in to Office 365 admin portal, go to Users –> Active Users.
Click setup and you will be presented with the following screen.
Click ‘Enable’ link on the bottom right and the following screen will pop-up.
Click ‘enable multi-factor auth’.
Now you will get a confirmation that multi-factor authentication is enabled for selected accounts.
When I log in next time, it asks for me to setup the second form of authentication.
Click ‘Set it up now’.
It sends a 6 digit verification code to the registered mobile number. You are all set for multi-factor authentication enabled Office 365 tenant. This wraps up my quick how-to article.
At this point of time, the multi-factor authentication is available for Office 365 Midsize Business, Enterprise plans, Academic plans, Nonprofit plans, and standalone Office 365 plans, including Exchange Online and SharePoint Online. It is not available for Office 365 Small Business and Office 365 Dedicated plans as of now. The detailed Faqs about multi-factor authentication is available here.
In this post, we’ll understand what is an App Only Permission policy in SharePoint 2013 App model with a sample app project. The SharePoint 2013 App permissions are of three types and they are as follows :-
App Only
User Only
App+User
When the logged in user does not have enough privileges to perform a certain action or set of actions, the App Only permission comes into picture. The App can elevate its permission using the App Only permission or context. A SharePoint 2013 App configured with App Only permission or context can only installed by the site-collection administrator at this point of time.
I’ll be using a Provider hosted app for the purpose of this demonstration. I have a user called ‘User A’ who does not have permission to modify the Title of SharePoint lists in the site-collection. I will be using App Only context to elevate the App’s permission and change the List Title.
I have a list called ‘Announcements’ and I will be changing its Title using App Only permission or context.
Launch Visual Studio 2013.
File –> New –> Office/SharePoint –> Apps and name it as ‘AppOnlyContextApp’
Select the app hosting type as Provider hosted apps.
In order to update the Title of the SharePoint List (at the root of the site-collection), provide the Full Control to Site-Collection.
Set App Only permission in the AppManifest.XML file
Copy and paste the following code for the default.aspx.cs file and I have added the necessary logic in the page_load method to update Title of a particular list.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace AppOnlyContextWeb
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Uri redirectUrl;
switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
{
case RedirectionStatus.Ok:
return;
case RedirectionStatus.ShouldRedirect:
Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
break;
case RedirectionStatus.CanNotRedirect:
Response.Write("An error occurred while processing your request.");
Response.End();
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// The following code gets the client context and Title property by using TokenHelper.
// To access other properties, the app may need to request permissions on the host web.
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPHost())
{
//Load the sharepoint web
clientContext.Load(clientContext.Web, web => web.Title);
clientContext.ExecuteQuery();
Response.Write(clientContext.Web.Title);
//Load the list-collection in the sharepoint web
clientContext.Load(clientContext.Web.Lists);
clientContext.ExecuteQuery();
//Change the title of announcment list to some arbitrary title
clientContext.Web.Lists[1].Title = "SundarAnnouncements";
clientContext.Web.Lists[1].Update();
clientContext.ExecuteQuery();
}
}
}
}
Hit F5 and run the App in Visual Studio. Now we can verify the elevation of App permission by using App Only policy, by validating the change in List title.
In this post, we’ll see how we can get the list of Fields in a SharePoint List in SharePoint 2013 Online using CSOM. I’ll be using a Console application for the purpose of demonstration.
Open Visual Studio 2013.
File –> New Project –> Visual C# –> Console Application and name it as ‘GetFieldsCSOM’
Add a reference to the ‘Microsoft.SharePoint.Client’ and ‘Microsoft.SharePoint.Client.Runtime’ assemblies
Import the following namespaces
using Microsoft.SharePoint.Client;
using System.Security;
The following code will invoke the GetbyTitle method of Lists class and access the Fields property collection.
namespace GetFieldsCSOM
{
class Program
{
privatestatic SecureString GetSecureString(String Password)
{
SecureString oSecurePassword = new SecureString();
foreach (Char c in Password.ToCharArray())
{
oSecurePassword.AppendChar(c);
}
return oSecurePassword;
}
staticvoid Main(string[] args)
{
//Replace it with the url of your tenant or your site-collectionstring SiteUrl = "https://yoursite.sharepoint.com";
System.Uri oUri = new System.Uri(SiteUrl);
using (ClientContext oClientContext = new ClientContext(SiteUrl))
{
//Replace it with your user id for SharePoint Onlinestring UserName = "userid@yoursite.onmicrosoft.com";
//Replace it with your passwordstring Password = "password";
//Create a SecureString object from password string, needed for SharePointOnlineCredentials class
SecureString SecurePassword = GetSecureString(Password);
oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);
oClientContext.Load(oClientContext.Web.Lists.GetByTitle("TestList").Fields);
oClientContext.ExecuteQuery();
FieldCollection oFieldCollection = oClientContext.Web.Lists.GetByTitle("TestList").Fields;
foreach(Field oField in oFieldCollection)
{
Console.WriteLine(oField.Title);
}
Console.ReadLine();
}
}
}
}
In this post, we’ll see how we can retrieve users in a SharePoint group in SharePoint 2013 Online using managed .NET Client Side Object Model (CSOM). We’ll create a Console Application in Visual Studio for the purpose of the demo.
Open Visual Studio 2013.
File –> New Project –> Visual C# –> Console Application and name it as ‘GetUsersInGroup’
Add a reference to assemblies ‘Microsoft.SharePoint.Client’ and ‘Microsoft.SharePoint.Client.Runtime’.
Import the following two namespaces.
using Microsoft.SharePoint.Client;
using System.Security;
In the client object model, the list groups in a site-collection needs to be fetched first and then based on the groups another call needs to be made to SharePoint Online to get the list of users. The following code snippet explains it all.
namespace GetUsersInGroupCSOM
{
class Program
{
staticvoid Main(string[] args)
{
//Replace it with the url of your tenant or your site-collectionstring SiteUrl = "https://yoursite.sharepoint.com";
System.Uri oUri = new System.Uri(SiteUrl);
using (ClientContext oClientContext = new ClientContext(SiteUrl))
{
//Replace it with your user id for SharePoint Onlinestring UserName = "lavsunswe@yoursite.onmicrosoft.com";
//Replace it with your passwordstring Password = "yourpassword";
//Create a SecureString object from password string, needed for SharePointOnlineCredentials class
SecureString SecurePassword = GetSecureString(Password);
oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);
//Load the site-collection groups using CSOM
oClientContext.Load(oClientContext.Web.SiteGroups);
oClientContext.ExecuteQuery();
GroupCollection oSiteCollectionGroups= oClientContext.Web.SiteGroups;
Console.WriteLine("List of groups in the site collection");
Console.WriteLine("-------------------------------------");
foreach (Group oGroup in oSiteCollectionGroups)
{
Console.WriteLine(oGroup.Title);
Console.WriteLine("n");
}
//Load the users collection in the Group 1
oClientContext.Load(oSiteCollectionGroups[1].Users);
oClientContext.ExecuteQuery();
Console.WriteLine("List of users in the first group of site-collection");
Console.WriteLine("-------------------------------------");
foreach(User oUser in oSiteCollectionGroups[1].Users)
{
Console.WriteLine(oUser.Title);
Console.WriteLine("n");
}
Console.ReadLine();
}
}
privatestatic SecureString GetSecureString(String Password)
{
SecureString oSecurePassword = new SecureString();
foreach (Char c in Password.ToCharArray())
{
oSecurePassword.AppendChar(c);
}
return oSecurePassword;
}
}
}
The Office 365 Development Patterns & Practices team have shipped the new open source repository today to GitHub.com/OfficeDev. The whole idea of releasing this is that, many sharepoint developers were familiar with how to build custom solutions with full-trust code and VSTO, however they did not know how to implement these solutions using App Model. The set of samples addresses the transformation from Full Trust Code to App Model.
I have a requirement to transfer the entire SharePoint 2013 Farm on Azure with Virtual Network, Cloud services, Storage accounts, Virtual Machines, Subnets and Availability sets to a different Subscription on Azure. I did some analysis and in this migration process i have learnt that the following Azure services (as of today 07/29/2014) can be transferred from one Azure subscription to another Azure subscription without data-loss and downtime, by raising a support ticket with Microsoft Azure Support :-
Virtual Machines
Cloud Services
CDN
Web sites
Media Services
Service Bus
Storage
Multi Factor Authentication
Traffic Manager
Mobile Services
Virtual Network
Access Control Service (ACS)
Caching – we need to work with Engineering Team for migrating caching service
Reserved IP Address and the Reserved IPs under the list
However, there are certain Azure services that cannot be moved from One subscription to another subscription (as of today 07/29/2014):-
a) Active Directory (AAD) b) BizTalk Services c) HD Insight d) Backup e) Hyper-V Recovery Manager f) Azure Store g) Import / Export h) Scheduler i) Management Services j) SQL Reporting
The following pre-conditions should be met before initiating a subscription transfer with Microsoft Azure support :
Source and destination subscription should be active
Selective service transfer is not feasible as of today, it might come in future. It has to be all or nothing.
The destination azure subscription should be empty, otherwise it will be overwritten during upgrade
Source and destination subscription should have same server administrator assigned until the migration is complete.