Sharepoint hosted apps - sharepoint

I am trying to create a site in my sharepoint hosted app using Javascript client object model in a SP Online site with a custom template.
Question: Can I do this in a sharepoint hosted app? If so please can you provide some examples.
Here is my code
this.context = SP.ClientContext.get_current();
this.web = context.get_web();
// Build out the WebCreationInformation for the new site
var wci = new SP.WebCreationInformation();
wci.set_title('My New Web Site 2');
wci.set_description('Description Input');
wci.set_url('mynewwebsite7');
wci.set_language(1033);
wci.set_useSamePermissionsAsParentSite(true);
wci.set_webTemplate('STS#1');
// Create the new web in the client context
this.childWeb = this.web.get_webs().add(wci);
this.context.load(this.web);
this.context.load(this.childWeb);//, 'ServerRelativeUrl', 'Created');
// Now create it on the server
this.context.executeQueryAsync(Function.createDelegate(this, this.createSiteSucceeded),
Function.createDelegate(this, this.createSiteFailed));

this.web = context.get_web();
// Build out the WebCreationInformation for the new site
var wci = new SP.WebCreationInformation();
You can't write this in your code. You have to load the requestexecutor.js first and then make the client context or the rest API calls to get the desired result. also you have to give full control over site collection in the appmanifest.

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 publish website form webapplication hosted in Azure?

need solution for website publishing form web application hosted in Azure.
I tried the following code, It create the domain but I was not able to upload the Published website.
private HttpResponseMessage CreateWebsite(CreateSiteViewModel site)
{
var cert = X509Certificate.CreateFromCertFile(Server.MapPath(site.CertPath));
string uri = string.Format("https://management.core.windows.net/{0}/services/WebSpaces/{1}/sites/", site.Subscription, site.WebSpaceName);
// A url which is looking for the right public key with
// the incomming https request
var req = (HttpWebRequest)WebRequest.Create(uri);
String dataToPost =string.Format(
#"<Site xmlns=""http://schemas.microsoft.com/windowsazure"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"">
<HostNames xmlns:a=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"">
<a:string>{0}.azurewebsites.net</a:string>
</HostNames>
<Name>{0}</Name>
<WebSpaceToCreate>
<GeoRegion>{1}</GeoRegion>
<Name>{2}</Name>
<Plan>VirtualDedicatedPlan</Plan>
</WebSpaceToCreate>
</Site>", site.SiteName, site.WebSpaceGeo, site.WebSpaceName);
req.Method = "POST"; // Post method
//You can also use ContentType = "text/xml";
// with the request
req.UserAgent = "Fiddler";
req.Headers.Add("x-ms-version", "2013-08-01");
req.ClientCertificates.Add(cert);
// Attaching the Certificate To the request
// when you browse manually you get a dialogue box asking
// that whether you want to browse over a secure connection.
// this line will suppress that message
//(pragramatically saying ok to that message).
string postData = dataToPost;
var encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(postData);
// Set the content length of the string being posted.
req.ContentLength = byte1.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
// Close the Stream object.
newStream.Close();
var rsp = (HttpWebResponse)req.GetResponse();
var reader = new StreamReader(rsp.GetResponseStream());
String retData = reader.ReadToEnd();
req.GetRequestStream().Close();
rsp.GetResponseStream().Close();
return new HttpResponseMessage
{
StatusCode = rsp.StatusCode,
Content = new StringContent(retData)
};
}
I am not entirely sure what you try to achieve here. But if I understand correctly you want to publish a website programmatic.
You cannot do this (publish a website programmatic) with Azure Management APIs. Azure management APIs are to manage Azure services and resources. The web site content itself is not in any way Azure Service, nor an Azure resource.
If you want to programmaticly publish a website to Azure Web Site, I would suggest taking deep read into How to deploy an Azure Web site.
Out from what is mentioned there, pretty easy to automate are
Web Deploy
Repositories using GIT
MSBuild
any other that you are familiar with ...

How do I pass user credentials from the console to SharePoint Online?

I am trying to connect SharePoint 2013 Online website using a Context Token from a console executable. However, it is giving me error The remote server returned an error: (403) Forbidden.
Here is the code snippet:
string spurl = ConfigurationManager.AppSettings["Sharepoint_URL"].ToString();
using (ClientContext context = new ClientContext(spurl))
{
context.Credentials = new NetworkCredential("username", "password", "domain");
context.ExecuteQuery();
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine(context.Web.Title);
}
Console.ReadKey();
How can I make a connection with SharePoint Online? Does it only support claims-based authentication?
I think the method with which you are trying to authenticate is outdated. The SharePoint 2013 Client Object Model now has a class called SharePointOnlineCredentials which abstracts away all the tedious cookie container stuff. E.g.:
using (ClientContext clientContext = new ClientContext("https://yoursite.sharepoint.com/"))
{
SecureString passWord = new SecureString();
clientContext.Credentials = new SharePointOnlineCredentials("loginname#yoursite.onmicrosoft.com", passWord);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
Console.WriteLine(web.Title);
Console.ReadLine();
}
Please refer to this link for more information: https://sharepoint.stackexchange.com/questions/83985/access-the-sharepoint-online-webservice-from-a-console-application

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!

SharePoint 2010 Client Object Model: How to retrieve subwebs for a specified user?

I have a need to retrieve a list of subwebs for a specified user using the client object model. The challenge is that this is being called from a C# web service that is running under the identity of a SharePoint user with access to all the subwebs. Is there a way to filter this list to only return those that belong to a specified user? I only have the username and do not have the password for this account so direct impersonation using NetworkCredential is not going to work.
Pseudo code below:
var clientContext = new ClientContext(siteUrl);
var site = clientContext.Web;
var user = site.CurrentUser;
clientContext.Load(site);
clientContext.Load(user);
clientContext.ExecuteQuery();
var webCollection = site.GetSubwebsForCurrentUser(null);
clientContext.Load(webCollection);
clientContext.ExecuteQuery();
foreach (var web in webCollection)
{
// should I check permissions here?
}

Resources