Root site collection in Javascript - sharepoint

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

Related

SharePoint CAML query gets (401) Unauthorized exception

I have a query which looks like this:
var site = properties.Site;
var context = new ClientContext(site.Url);
List list = context.Web.Lists.GetByTitle(properties.ListTitle);
var query = new CamlQuery();
query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/>" +
"<Value Type='Text'>" + fieldName + "</Value></Eq></Where></Query></View>";
ListItemCollection itemCollection = list.GetItems(query);
context.Load(itemCollection);
context.ExecuteQuery();
In this scenario properties is an SPItemEventProperties.
Whenever it gets to ExecuteQuery(), it throws an exception: The remote server returned an error: (401) Unauthorized.
What could be the cause of this?
Looking at your code I guess this is RER associated with list item action. It happens that if you run it from host web (rather than app web) or you use CSOM it fails to authencitate back to SharePoint. Most likely when you will try to debug your code you will see that your RER has not received a valid context token (SPRemoteEventProperties.ContextToken is an empty string). Additionally the way you create your context using constructor
var context = new ClientContext(site.Url);
Does not deal with authenticateion. You have token methods to do that.
var context = TokenHelper.CreateRemoteEventReceiverClientContext(properties)
This will return a valid context as long as this event is on app web.
If this does not resolve your problem you will need to switch to use app permissions in your AppManifest and build a proper Realm from your SPHostUrl
var siteUrl = properties.Site.Url;
var siteUri = new Uri(siteUrl);
var realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
var token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken;
using (var context = TokenHelper.GetClientContextWithAccessToken(siteUrl, token))
{
}
Let me know if that helps.

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!

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: how to upload a file to a doc lib using javascript

I see this article explaining how to upload a file using client API's from a fully trusted app.
How to implement such functionality but from javascript?
For example, I have this code in which I have both the local path of the file and the SharePoint doc lib, how do I complete it?
Thanks!
PS: I'm guessing there must be some fully trusted component involved in the client in order to achieve this, otherwise would be a javascript security hole, but which one would be the right one to use in this case against SharePoint?
<script type="text/javascript">
var list;
var filePath;
function ShowUploadDialog() {
// get file path user chooses through a dialog
var fileDialog = document.getElementById("fileDialog");
fileDialog.click();
filePath = fileDialog.value;
// get list
var context = new SP.ClientContext.get_current();
var site = context.get_site();
var web = site.get_rootWeb();
this.collList = web.get_lists();
list = collList.getByTitle("My doc library");
context.load(list);
context.executeQueryAsync(Succeeded, Failed);
}
function Succeeded(sender, args) {
// I HAVE HERE THE list AND THE filePath, HOW CAN UPLOAD THE FILE TO THE LIST?
}
function Failed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
UploadCtl solves this.

Resources