Using SharePoint leftSide Navigation in SharePoint Custom App - sharepoint

Is it possible to use SharePoint left navigation bar in a "Provider Hosted App". The navigation shown on SharePoint site "PlaceHolderLeftNavBar". Is there any way like some ajax call or REST/CSOM functionality?

According to the official MSDN documentation, the CSOM and JSOM both contain Navigation properties which also provide access to the quick launch menu (aka "left navigation bar").
Links to the docs are as follows:
SP.Navigation.quickLaunch property (sp.js) (JSOM)
Navigation.QuickLaunch property (CSOM)
In order to use either CSOM or JSOM in a provider hosted app, you would need to authenticate using either OAUTH (for Office 365 / SharePoint Online) or by using certificates in a High-Trust / on-premises environment.
If you use the App for SharePoint 2013 template provided by Visual Studio 2013, and select provider-hosted, it should come with a TokenHelper.cs/vb class file which will do much of the heavy lifting for both scenarios. More info on authentication techniques is also available on MSDN - look for the following topics in particular:
Authorization and authentication for apps in SharePoint 2013 How to:
Create high-trust apps for SharePoint 2013 (advanced topic)
I'm not sure if there is a pure REST endpoint available at this time, which could certainly simplify the advanced authorization requirements of CSOM / JSOM in a provider hosted app.

SP.Web.navigation property gets a value that specifies the navigation structure on the site, including the Quick Launch area and the top navigation bar
How to access Navigation (Quick Launch) via CSOM (JavaScript)
function getQuickLaunch(success,error)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var nav = web.get_navigation();
var quickLaunch = nav.get_quickLaunch();
context.load(quickLaunch);
context.executeQueryAsync(
function() {
var nodes = [];
var nodesCount = quickLaunch.get_count();
for(var i = 0; i < nodesCount;i++){
var node = quickLaunch.getItemAtIndex(i);
nodes.push(node);
}
success(nodes);
},
error
);
}
Usage
getQuickLaunch(
function(nodes){
for(var idx in nodes)
{
console.log(nodes[idx].get_title());
}
},
function(sender, args) {
console.log('Error:' + args.get_message());
}
);
How to access Navigation (Quick Launch) via REST
function getQuickLaunch(siteurl, success, failure) {
$.ajax({
url: siteurl + "/_api/web/navigation/quickLaunch",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
success(data.d.results);
},
error: function (data) {
failure(data);
}
});
}
Usage
getQuickLaunch(_spPageContextInfo.webAbsoluteUrl,
function(nodes){
for(var idx in nodes)
{
console.log(nodes[idx].Title);
}
},
function(error) {
console.log(JSON.stringify(error));
}
);

Related

List all groups of a user in Azure Active directory using the Azure API call

What is the Rest API for listing all groups in Azure Activedirectory from Spring boot application?
(at the moment a google search bring about the below two APIs which are as below, one is "Azure Active Directory Graph API" and another is "Azure API Management REST API Group entity"
Not sure which API exactly to use for getting list of groups of Azure AD ?
The best approach is to call the Microsoft Graph API (though you can also do this with the Azure AD Graph API).
To list all groups, the request would be:
GET https://graph.microsoft.com/v1.0/groups
In Java, you can use the Microsoft Graph SDK for Java, an example of how you could retrieve all groups (this includes paging through multiple pages of results, in case you have more than 999 groups):
// Set up the Graph client
IGraphServiceClient graphClient =
GraphServiceClient
.builder()
.authenticationProvider(authProvider)
.logger(new NotALogger())
.buildClient();
// Set up the initial request builder and build request for the first page
IGroupCollectionRequestBuilder groupsRequestBuilder = graphClient.groups();
IGroupCollectionRequest groupsRequest = groupsRequestBuilder
.buildRequest()
.top(999);
do {
try {
// Execute the request
IGroupCollectionPage groupsCollection = groupsRequest.get();
// Process each of the items in the response
for (Group group : groupsCollection.getCurrentPage()) {
System.out.println(group.displayName);
}
// Build the request for the next page, if there is one
groupsRequestBuilder = groupsCollection.getNextPage();
if (groupsRequestBuilder == null) {
groupsRequest = null;
} else {
groupsRequest = groupsRequestBuilder.buildRequest();
}
} catch(ClientException ex) {
// Handle failure
ex.printStackTrace();
groupsRequest = null;
}
} while (groupsRequest != null);
To list all groups the signed-in user is a member of (including nested groups):
POST https://graph.microsoft.com/v1.0/me/getMemberGroups
Content-type: application/json
{
"securityEnabledOnly": true
}

How to provision Branding files using SharePoint Hosted App in SharePoint Online/Office 365?

I am looking for SharePoint Hosted App Solution which will provision Branding files (JS/CSS/Images) into SharePoint Online/Office 365 environment.
I got a very good article to achive this and tried to implement the same as shown in below link: http://www.sharepointnutsandbolts.com/2013/05/sp2013-host-web-apps-provisioning-files.html
This solution is not working for me and while execution of app, I am getting below error:
Failed to provision file into host web. Error: Unexpected response data from server. Here is the code which is giving me error:
// utility method for uploading files to host web..
uploadFileToHostWebViaCSOM = function (serverRelativeUrl, filename, contents) {
var createInfo = new SP.FileCreationInformation();
createInfo.set_content(new SP.Base64EncodedByteArray());
for (var i = 0; i < contents.length; i++) {
createInfo.get_content().append(contents.charCodeAt(i));
}
createInfo.set_overwrite(true);
createInfo.set_url(filename);
var files = hostWebContext.get_web().getFolderByServerRelativeUrl(serverRelativeUrl).get_files();
hostWebContext.load(files);
files.add(createInfo);
hostWebContext.executeQueryAsync(onProvisionFileSuccess, onProvisionFileFail);
}
Please suggest me, what can be the issue in this code? Or else suggest me another way/reference in which I can Create a SharePoint-Hosted App to provision Branding Files.
Thanks in Advance!
I would use a different method to access host web context as follows:
//first get app context, you will need it.
var currentcontext = new SP.ClientContext.get_current();
//then get host web context
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
function getQueryStringParameter(param) {
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] == param) {
return singleParam[1];
}
}
}
Here are some references:
https://sharepoint.stackexchange.com/questions/122083/sharepoint-2013-app-create-list-in-host-web
https://blog.appliedis.com/2012/12/19/sharepoint-2013-apps-accessing-data-in-the-host-web-in-a-sharepoint-hosted-app/
http://www.mavention.com/blog/sharePoint-app-reading-data-from-host-web
http://www.sharepointnadeem.com/2013/12/sharepoint-2013-apps-access-data-in.html
Additionally, here is an example of how to deploy a master page, however as you might notice during your testing the method used to get host web context is not working as displayed in the video and you should use the one I described before.
https://www.youtube.com/watch?v=wtQKjsjs55I
Finally, here is a an example of how to deploy branding files through a Console Application using CSOM, if you are smart enough you will be able to convert this into JSOM.
https://channel9.msdn.com/Blogs/Office-365-Dev/Applying-Branding-to-SharePoint-Sites-with-an-App-for-SharePoint-Office-365-Developer-Patterns-and-P

How to set the security token in breeze to access SharePoint list?

I have used http://www.andrewconnell.com/blog/getting-breezejs-to-work-with-the-sharepoint-2013-rest-api
code in a empty web application project. How can I set the security access in order to deal with the SharePoint list.
function configureBreeze() {
// configure breeze to use SharePoint OData service
var dsAdapter = breeze.config.initializeAdapterInstance('dataService', 'SharePointOData', true);
dsAdapter.defaultSettings = {
xhrFields: {
withCredentials: true
}
};
// tell breeze how to get the security validation token for
// HTTP POST & DELETE calls
dsAdapter.getRequestDigest = function () {
return jQuery('#__REQUESTDIGEST').val();
};
}
I am getting a Access Denied error!
Did you look at all three parts of Andrew's post?
Part 3 talks about security ... the "request digest" in particular ... and shows you how to get the SharePoint OData adapter and set the adapter.getRequestDigest function.
You might want to post additional questions to that blog post too.

Get Sharepoint Site Collection URLs by JQuery

I have a special requirement that I need to get all site collection URLs list from JQuery.Can any one please help on that
I am afraid that you cannot get the list of all site collections in pure JavaScript. I assume that you meant all existing site collections in a web application or in all web applications.
If your page (aspx) runs on the SharePoint server you can put some server-side code on the page "rendering" the list as JavaScript and then just access it. This would be the easiest way; probably using Page.ClientScript.RegisterStartupScript.
If your page (and/or the web application) runs outside the SharePoint farm you would have to create and deploy your web service (asmx) or a handler (ashx) to the SharePoint farm. You would probably respond with the site collection list as JSON content and consume it by jQuery on your page (AJAX).
The functionality is available in the server-side SharePoint API only. You would use SPWebService.ContentService.WebApplications and application.Sites to get the list in any case:
var json = new StringBuilder();
foreach (var site in SPWebService.ContentService.WebApplications.SelectMany(
application => application.Sites))
using (site) {
if (json.Length > 0)
json.Append(',');
json.Append('"').Append(site.Url).Append('"');
}
json.Insert(0, "[").Append("]");
--- Ferda
Try below code.you can get all site collection using client object model
function loadWebs() {
var clientContext = new SP.ClientContext.get_current();
this.webs = clientContext.get_web().get_webs();
clientContext.load(this.webs);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onWebsLoaded), Function.createDelegate(this, this.onQueryFailed));
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
function onWebsLoaded(sender, args) {
for (var i = 0; i < this.webs.get_count(); i++) {
alert(this.webs.itemAt(i).get_title());
}
}
ExecuteOrDelayUntilScriptLoaded(loadWebs, "sp.js");

SharePoint 2010 Client Object Model - Kerberos/Claims Authentication

I'm trying to read a value from a list in a remote SharePoint site (different SP Web App). The web apps are set up with Claims Auth, and the client web app SP Managed account is configured with an SPN. I believe Kerberos and claims are set up correctly, but I am unable to reach the remote server, and the request causes an exception: "The remote server returned an error: (401) Unauthorized."
The exception occurs in the line ctx.ExecuteQuery(); but it does not catch the exception in the if (scope.HasException) instead, the exception is caught by the calling code (outside of the using{} block).
When I look at the traffic at the remote server using Wireshark, it doesn't look like the request is even getting to the server; it's almost as if the 401 occurs before the Kerberos ticket is exchanged for the claim.
Here's my code:
using (ClientContext ctx = new ClientContext(contextUrl))
{
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(contextUrl), "Kerberos", CredentialCache.DefaultNetworkCredentials);
ctx.Credentials = cc;
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);
Web ctxWeb = ctx.Web;
List ctxList;
Microsoft.SharePoint.Client.ListItemCollection listItems;
using (scope.StartScope())
{
using (scope.StartTry())
{
ctxList = ctxWeb.Lists.GetByTitle("Reusable Content");
CamlQuery qry = new CamlQuery();
qry.ViewXml = string.Format(ViewQueryByField, "Title", "Text", SharedContentTitle);
listItems = ctxList.GetItems(qry);
ctx.Load(listItems, items => items.Include(
item => item["Title"],
item => item["ReusableHtml"],
item => item["ReusableText"]));
}
using (scope.StartCatch()) { }
using (scope.StartFinally()) { }
}
ctx.ExecuteQuery();
if (scope.HasException)
{
result = string.Format("Error retrieving content<!-- Error Message: {0} | {1} -->", scope.ErrorMessage, contextUrl);
}
if (listItems.Count == 1)
{
Microsoft.SharePoint.Client.ListItem contentItem = listItems[0];
if (SelectedType == SharedContentType.Html)
{
result = contentItem["ReusableHtml"].ToString();
}
else if (SelectedType == SharedContentType.Text)
{
result = contentItem["ReusableText"].ToString();
}
}
}
I realize the part with the CredentialCache shouldn't be necessary in claims, but every single example I can find is either running in a console app, or in a client side application of some kind; this code is running in the codebehind of a regular ASP.NET UserControl.
Edit: I should probably mention, the code above doesn't even work when the remote URL is the root site collection on the same web app as the calling code (which is in a site collection under /sites/)--in other words, even when the hostname is the same as the calling code.
Any suggestions of what to try next are greatly appreciated!
Mike
Is there a reason why you are not using the standard OM?
You already said this is running in a web part, which means it is in the context of application pool account. Unless you elevate permissions by switching users, it won't authenticate correctly. Maybe try that. But I would not use the client OM when you do have access to the API already.

Resources