SHarePoint 2013 site collection through client object model - sharepoint

I am working on a requirement where I need to create a site collection in SharePoint using client side api. I know server side we can do it using self service site creation api. Also I know in case of SharePoint Online , we have Microsoft.Online.SharePoint.Client.Tenant.dll that we can use to create site collection However in my case I have a On premise environment (SharePoint 2013) where I need to create a site collection thru client side api. Can you please let me know if there is any API that I can use for this requirement.
Thanks for any Help you can provide on this.

This is not possible to do by using the CSOM, on an on-premise environment.
As you mentioned, it is possible on the SPO environment using the library that you listed (Microsoft.Online.SharePoint.Client.Tenant.dll).
I'm not sure if this will help, but here is code that could create a site inside of the current site collection:
You will also need to add using statements for System.Collections.Generic and System.Text.
// Starting with ClientContext, the constructor requires a URL to the
// server running SharePoint.
ClientContext context = new ClientContext("http://SiteUrl");
WebCreationInformation creation = new WebCreationInformation();
creation.Url = "web1";
creation.Title = "Hello web1";
Web newWeb = context.Web.Webs.Add(creation);
// Retrieve the new web information.
context.Load(newWeb, w => w.Title);
context.ExecuteQuery();
label1.Text = newWeb.Title;
This code was taken directly from here: http://msdn.microsoft.com/en-us/library/fp179912.aspx

How to create site collection via SharePoint 2013 Managed CSOM
Tenant.CreateSite method from Microsoft.Online.SharePoint.Client.Tenant.dll assembly is intended for site collection creation:
/// <summary>
/// Create a new site.
/// </summary>
/// <param name="context"></param>
/// <param name="url">rootsite + "/" + managedPath + "/" + sitename: e.g. "https://auto.contoso.com/sites/site1"</param>
/// <param name="title">site title: e.g. "Test Site"</param>
/// <param name="owner">site owner: e.g. admin#contoso.com</param>
/// <param name="template">The site template used to create this new site</param>
/// <param name="localeId"></param>
/// <param name="compatibilityLevel"></param>
/// <param name="storageQuota"></param>
/// <param name="resourceQuota"></param>
/// <param name="timeZoneId"></param>
internal static void CreateSite(ClientContext context, String url, String owner, String title =null, String template = null, uint? localeId = null, int? compatibilityLevel = null, long? storageQuota = null, double? resourceQuota = null, int? timeZoneId = null)
{
var tenant = new Tenant(context);
if (url == null)
throw new ArgumentException("Site Url must be specified");
if (string.IsNullOrEmpty(owner))
throw new ArgumentException("Site Owner must be specified");
var siteCreationProperties = new SiteCreationProperties {Url = url, Owner = owner};
if (!string.IsNullOrEmpty(template))
siteCreationProperties.Template = template;
if (!string.IsNullOrEmpty(title))
siteCreationProperties.Title = title;
if (localeId.HasValue)
siteCreationProperties.Lcid = localeId.Value;
if (compatibilityLevel.HasValue)
siteCreationProperties.CompatibilityLevel = compatibilityLevel.Value;
if (storageQuota.HasValue)
siteCreationProperties.StorageMaximumLevel = storageQuota.Value;
if (resourceQuota.HasValue)
siteCreationProperties.UserCodeMaximumLevel = resourceQuota.Value;
if (timeZoneId.HasValue)
siteCreationProperties.TimeZoneId = timeZoneId.Value;
var siteOp = tenant.CreateSite(siteCreationProperties);
context.Load(siteOp);
context.ExecuteQuery();
}
//Usage
const string username = "***#***.onmicrosoft.com";
const string password = "***";
const string tenantAdminUrl = "https://***-admin.sharepoint.com/";
const string newSiteCollUrl = "https://contoso.sharepoint.com/sites/finance"
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);
using (var context = new ClientContext(tenantAdminUrl))
{
context.Credentials = credentials;
CreateSite(context, newSiteCollUrl,username);
}

It is available in the April 2014 CU
http://blogs.msdn.com/b/vesku/archive/2014/06/09/provisioning-site-collections-using-sp-app-model-in-on-premises-with-just-csom.aspx

Related

Azure - Create Database via HTTP API (using Secret) - 403 Error

I am trying to create an Azure Database programmatically using C# via the HTTP API.
I found this resource (in which he uses App Secret, rather than certificate), but can't get it to work due to a 403: Forbidden error.
If I use the token created in the 'try it' section of the azure docs, the code works fine, so it must be that the token generated doesn't have the permissions I need.
The secret I am trying to use was generated in Portal > Active Directory > App Registrations > {myapp} > Certificates and Secrets.
In API permissions I've added just about everything - though please suggest any I might have missed!
I opened the firewall to my IP and have spent hours looking for the answer, but can't seem to figure it out.
What am I missing please?
Although I believe it's permissions somewhere in Azure, here's my code:
/// <summary>
/// Create a new database
/// </summary>
/// <param name="subscriptionId">See Portal > Subscriptions (pick the right subscription!)</param>
/// <param name="resourceGroupName">The resource group the server was created in</param>
/// <param name="locationName">e.g. UK (South)</param>
/// <param name="sqlServeName">The name of the SQL Server VM created when the first database was created</param>
/// <param name="tenantId">See GetAccessToken</param>
/// <param name="clientId">See GetAccessToken</param>
/// <param name="clientSecret">See GetAccessToken</param>
/// <param name="databaseName">The name of the database to be created</param>
/// <returns></returns>
private async Task CreateDatabaseAsync(string subscriptionId, string resourceGroupName, string locationName, string sqlServeName, string tenantId, string clientId, string clientSecret, string databaseName)
{
var token = await GetAccessTokenAsync(tenantId, clientId, clientSecret);
var url = "https://management.azure.com/subscriptions/" + subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/Microsoft.Sql/servers/" + sqlServeName + "/databases/" + databaseName + "?api-version=2017-10-01-preview";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Remove("Authorization");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
string requestBody = "{location: \"" + locationName + "\"}";
HttpResponseMessage response = await httpClient.PutAsync(url, new StringContent(requestBody, Encoding.UTF8, "application/json"));
var statusCode = response.StatusCode.ToString();
}
/// <summary>
/// Gets and access token with which to call the Azure API
/// </summary>
/// <param name="tenantId">See Portal > Active Directory > Properties > Overview for this value</param>
/// <param name="clientId">See Portal > Active Directory > App Registrations > This App > Overview for this value</param>
/// <param name="clientSecret">See Portal > Active Directory > App Registrations > This App > Certificates & Secrets > Generate Secret </param>
/// <returns></returns>
private async Task<string> GetAccessTokenAsync(string tenantId, string clientId, string clientSecret)
{
Console.WriteLine("Begin GetAccessToken");
string authContextURL = "https://login.windows.net/" + tenantId;
var authenticationContext = new AuthenticationContext(authContextURL);
var credential = new ClientCredential(clientId, clientSecret);
var result = await authenticationContext
.AcquireTokenAsync("https://management.azure.com/", credential);
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
Managed to find the answer in this post/ this Microsoft Article.
What I needed to do was:
Go to Portal > Subscriptions > {my subscription}
Click on Access control (IAM)
Add > Add Role Assignment as shown below (note: 'SqlTest' is the Application I created in Portal > Azure Active Directory > App Registrations)
Then the code works nicely.

How to upload a data into share point?

Am new to this outlook share point.
i need to upload a file into microsoft sharepoint via REST.
can anyone guide me to do this?
We can use CSOM via C# to achieve this, here is a demo for your reference:
/// <summary>
/// upload file to Document Library
/// </summary>
/// <param name="context"></param>
/// <param name="documentLibraryName">MyDocLib</param>
/// <param name="filePath">C:\\</param>
/// <param name="fileName">hello2.txt</param>
public static void uploadFile(ClientContext context, string documentLibraryName, string filePath, string fileName)
{
string siteURL = context.Url.EndsWith("/") ? context.Url.Substring(0, context.Url.Length - 1) : context.Url;
List list = context.Web.Lists.GetByTitle(documentLibraryName);
context.Load(list);
context.ExecuteQuery();
FileStream fileStream = new FileStream(filePath, FileMode.Open);
FileCreationInformation newFileInfo = new FileCreationInformation()
{
ContentStream = fileStream,
Url = siteURL + "/" + documentLibraryName + "/" + fileName,
Overwrite = true
};
Microsoft.SharePoint.Client.File file = list.RootFolder.Files.Add(newFileInfo);
context.Load(file);
context.ExecuteQuery();
}
CSOM library download link: CSOM download
More information about CSOM:
Complete basic operations using SharePoint client library code
About Rest API, we can refer to the below link:
REST API in c# to upload document in document Library of sharepoint

Removing Workflow from the list using SP Object Model in SharePoint 2010

I am interested in removing a Workflow from the list using the SP Object Model. How can I do this?
I am not having much luck with Google today!
OK. So here is the function I wrote that removes the Workflow from the list. Hope it helps someone :)
/// <summary>
/// Removes the workflow.
/// </summary>
/// <param name="workflowName">Name of the workflow.</param>
/// <param name="spList">The sp list.</param>
private static void RemoveWorkflow(string workflowName, SPList spList)
{
SPWorkflowAssociation spWorkflowAssociation =
spList.WorkflowAssociations.Cast<SPWorkflowAssociation>()
.FirstOrDefault(workflowAssociation => workflowAssociation.Name.Equals(workflowName));
if (spWorkflowAssociation != null)
{
spList.WorkflowAssociations.Remove(spWorkflowAssociation.Id);
}
spList.Update();
}
Try this code,
using(SPSite oSite = new SPSite("http://localhost/"))
{
using(SPWeb oWeb = oSite.OpenWeb())
{
SPList oList = oWeb.Lists["DocumentLib"];
SPWorkflowAssociation objWorkflowAssociation = oList.WorkflowAssociations.Cast<SPWorkflowAssociation>().FirstOrDefault(workflowAssociation => workflowAssociation.Name.Equals("Approval Workflow"));
if (objWorkflowAssociation != null)
{
oList.WorkflowAssociations.Remove(objWorkflowAssociation.Id);
}
oList.Update();
}
}
Its working on my end...

Access denied when trying to add Windows User account

I am trying to programmatically add a user like this below but get an access denied message on the Save. I'm running locally on Windows 7 and the code resides in a console app.
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="description"></param>
public static void CreateUser(string userName, string password, string description)
{
PrincipalContext pc = new PrincipalContext(ContextType.Machine, null);
System.DirectoryServices.AccountManagement.UserPrincipal u = new UserPrincipal(pc);
u.SetPassword(password);
u.Name = userName;
u.Description = description;
u.UserCannotChangePassword = true;
u.PasswordNeverExpires = true;
u.Save();
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, "Users");
gp.Members.Add(u);
gp.Save();
}
Any ideas? I tried supplying an administrators username and password and still get the same error.
The console app gets executed like this:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UserName = userName;
startInfo.Password = securePassword;
startInfo.LoadUserProfile = true;
startInfo.UseShellExecute = false;
startInfo.FileName = batchPath;
startInfo.Arguments = operationLogID.ToString();
Process.Start(startInfo);
Here is a rough view of how the code is set up:
Console App test harness gets executed in debug mode.
I check for a user and if they don't exist..then I try and create it shown above. This is where the error occurs.
Even if you're logged in as admin, you need to run your console as admin. Here's how to launch a console as admin: http://www.howtogeek.com/howto/windows-vista/run-a-command-as-administrator-from-the-windows-vista-run-box/.
Then find your console app and run it.
Good luck!
-Michael

Sharepoint Forms authentication Run with different account

I a console application that creates a sub sites under a site collection
The site collection accepts only forms based user.
Now, when i run the console application, its with windows credentials.
I need some way to run the code in console app that creates sub site to run under forms user who is admin to that site collection.
Please let me know your suggestions.
Thanks
You need to create a new Web service within the Central Administration Web application ([12 hive]\AMDISAPI) and add a function that creates subsites.
Here's an example - the hstCreateSubSite function from the SharePoint for Hosters project:
/// <summary>
/// Method to create a Sub site for a site collection
/// </summary>
/// <param name="strSiteURL">url of the sitecollection i.e. "http://www.sitea.com"</param>
/// <param name="subsitePath">the path to the subsite i.e. inventory</param>
/// <param name="strTitle">sub site title</param>
/// <param name="strDesc">sub site description</param>
/// <param name="strTemplate">a valid templateID</param>
/// <param name="nLCID">the LCID for the language i.e. 1033 for english</param>
[WebMethod]
public void hstCreateSubSite(string strSiteURL, string subSitePath, string strTitle, string strDesc, string strTemplate, uint nLCID)
{
SPSite oSite = new SPSite(strSiteURL);
SPWeb oSubSiteWeb = oSite.OpenWeb();
SPWeb oWeb = null;
if (String.IsNullOrEmpty(strDesc)) strDesc = null;
if (String.IsNullOrEmpty(strTitle)) strTitle = null;
try
{
// elevate permissions to allow user to create a new site.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// the subsite will inherit permissions and will not convert the site if it exists
oWeb = oSubSiteWeb.Webs.Add(subSitePath, strTitle, strDesc, nLCID, strTemplate, false, false);
SPNavigationNodeCollection nodes = oSubSiteWeb.Navigation.TopNavigationBar;
SPNavigationNode navNode = new SPNavigationNode(strTitle, subSitePath);
nodes.AddAsLast(navNode);
oWeb.Navigation.UseShared = true;
// create entry in property bag to store template and url in the subsite.
oWeb.AllowUnsafeUpdates = true;
// add the Templateid to the property bag. This needs to be done becuase
// sites that are created from site templates (.stp) do not retain the templateid.
oWeb.Properties.Add("STP_ID", strTemplate);
oWeb.Properties.Update();
oWeb.AllowUnsafeUpdates = false;
});
}
catch (Exception ex)
{
throw ex;
}
finally
{
//dispose objects
if (oWeb != null)
oWeb.Dispose();
if (oSite != null)
oSite.Dispose();
}
}

Resources