Get Sharepoint Site Collection URLs by JQuery - sharepoint

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");

Related

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 upload a document to SharePoint programmatically?

I want to upload documents from a web portal to SharePoint programmatically. That is, as user uploads a document it should go directly into SharePoint. I am new to SharePoint and am looking for suggestions/ideas on how to achieve above. Thanks
You have multiple ways of uploading a document, depending on where you code is running. The steps are practically the same.
From the Server Object Model
Use this one if you are working in the SharePoint server side (Web Parts, Event Receivers, Application Pages, etc.)
// Get the context
var context = SPContext.Current;
// Get the web reference
var web = context.Web;
// Get the library reference
var docLib = web.Lists.TryGetList("NAME OF THE LIBRARY HERE");
if (docLib == null)
{
return;
}
// Add the document. Y asume you have the FileStream somewhere
docLib.RootFolder.Files.Add(docLib.RootFolder.Url + "FILE NAME HERE", someFileStream);
From client side code (C#)
Use this one if you are working from a client application that consumes SharePoint services.
// Get the SharePoint context
ClientContext context = new ClientContext("URL OF THE SHAREPOINT SITE");
// Open the web
var web = context.Web;
// Create the new file
var newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes("PATH TO YOUR FILE");
newFile.Url = "NAME OF THE NEW FILE";
// Get a reference to the document library
var docs = web.Lists.GetByTitle("NAME OF THE LIBRARY");
var uploadFile = docs.RootFolder.Files.Add(newFile);
// Upload the document
context.Load(uploadFile);
context.ExecuteQuery();
From JS using the SharePoint web services
Use this one if you want to upload a document from pages without the server roundtrip:
// Get the SharePoint current Context
clientContext = new SP.ClientContext.get_current();
// Get the web reference
spWeb = clientContext.get_web();
// Get the target list
spList = spWeb.get_lists().getByTitle("NAME OF THE LIST HERE");
fileCreateInfo = new SP.FileCreationInformation();
// The title of the document
fileCreateInfo.set_url("my new file.txt");
// You should populate the content after this
fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
// Add the document to the root folder of the list
this.newFile = spList.get_rootFolder().get_files().add(fileCreateInfo);
// Load the query to the context and execute it (successHandler and errorHandler handle result)
clientContext.load(this.newFile);
clientContext.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
Hope it helps!

Using SharePoint leftSide Navigation in SharePoint Custom App

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

Root site collection in Javascript

How to get the Root Site collection url when the context is in a child site, in JavaScript or JQuery.
You could use the following using client object model
var clientContext = new SP.ClientContext();
var owebsite = clientContext.get_site.get_rootWeb();
Without client object model you can use the following
var siteCollectionPath= _spPageContextInfo.siteServerRelativeUrl;
var clientContext = new SP.ClientContext.get_current();
this.web = clientContext.get_site().get_rootWeb();
It's working for me.
Do you mean root web or root site collection?
This one will get you the root site collection:
_spPageContextInfo.siteAbsoluteUrl.replace(_spPageContextInfo.siteServerRelativeUrl, _spPageContextInfo.siteServerRelativeUrl == \"/\" ? \"/\": \"\") + \""
From my post: http://www.rdacorp.com/2015/03/alternate-solution-alternate-css-url-sharepoint-2013-online/
Below sample script shows how you can retrieve root web. The onQuerySucceedSample function alerts root site title.
getRootWeb = function () {
//Get and load a reference to the root web of the current site collection.
var ctx = new SP.ClientContext.get_current();
var site = ctx.get_site();
this.rootWeb = site.get_rootWeb();
ctx.load(this.rootWeb);
//Ask SharePoint to pull data for us
ctx.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceed),Function.createDelegate(this, this.onQueryFailed));
};
//Function executed on success
onQuerySucceed = function () {
alert(this.rootWeb.get_title());
};
//Function executed on failure
onQueryFailed = function (sender, args) {
alert('Unable to retrieve data from the SharePoint. Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
};
you can get the url without the client object model by using available information and string parse it down from there. Not as robust as the Client-Object model but significantly less complicated for simple tasks.
window.location.href
...gives you the full window url (e.g. "http://sitecollection.com/sites/mysite/Lists/myList/NewForm.aspx?ContentTypeId=0x01006AC2C39AA621424EBAD9C2AC8A54F8B9007B626ABEEB66E34196C46E13E0CA41A2&ContentTypeName=xxxx")
L_Menu_BaseUrl
Or
_spPageContextInfo.siteServerRelativeUrl
...(as Jinxed points out) will give you the relative url (e.g. "/sites/mysite")

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