Exemplo n.º 1
0
        /// <summary>
        /// Creates a new Communication Site Collection
        /// </summary>
        /// <param name="clientContext">ClientContext object of a regular site</param>
        /// <param name="siteCollectionCreationInformation">information about the site to create</param>
        /// <returns>ClientContext object for the created site collection</returns>
        public static async Task <ClientContext> CreateAsync(ClientContext clientContext, CommunicationSiteCollectionCreationInformation siteCollectionCreationInformation)
        {
            await new SynchronizationContextRemover();

            ClientContext responseContext = null;

            var accessToken = clientContext.GetAccessToken();

            using (var handler = new HttpClientHandler())
            {
                clientContext.Web.EnsureProperty(w => w.Url);
                // we're not in app-only or user + app context, so let's fall back to cookie based auth
                if (String.IsNullOrEmpty(accessToken))
                {
                    handler.SetAuthenticationCookies(clientContext);
                }

                using (var httpClient = new PnPHttpProvider(handler))
                {
                    string requestUrl = $"{clientContext.Web.Url}/_api/SPSiteManager/Create";
                    //    string requestUrl = String.Format("{0}/_api/sitepages/communicationsite/create", clientContext.Web.Url);

                    var siteDesignId = GetSiteDesignId(siteCollectionCreationInformation);

                    Dictionary <string, object> payload = new Dictionary <string, object>();
                    //payload.Add("__metadata", new { type = "Microsoft.SharePoint.Portal.SPSiteCreationRequest" });
                    payload.Add("Title", siteCollectionCreationInformation.Title);
                    payload.Add("Lcid", siteCollectionCreationInformation.Lcid);
                    payload.Add("ShareByEmailEnabled", siteCollectionCreationInformation.ShareByEmailEnabled);
                    payload.Add("Url", siteCollectionCreationInformation.Url);
                    // Deprecated
                    // payload.Add("AllowFileSharingForGuestUsers", siteCollectionCreationInformation.AllowFileSharingForGuestUsers);
                    if (siteDesignId != Guid.Empty)
                    {
                        payload.Add("SiteDesignId", siteDesignId);
                    }
                    payload.Add("Classification", siteCollectionCreationInformation.Classification ?? "");
                    payload.Add("Description", siteCollectionCreationInformation.Description ?? "");
                    payload.Add("WebTemplate", "SITEPAGEPUBLISHING#0");
                    payload.Add("WebTemplateExtensionId", Guid.Empty);
                    payload.Add("HubSiteId", siteCollectionCreationInformation.HubSiteId);
                    payload.Add("Owner", siteCollectionCreationInformation.Owner);

                    var body = new { request = payload };

                    // Serialize request object to JSON
                    var jsonBody    = JsonConvert.SerializeObject(body);
                    var requestBody = new StringContent(jsonBody);

                    // Build Http request
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                    request.Content = requestBody;
                    request.Headers.Add("accept", "application/json;odata.metadata=none");
                    request.Headers.Add("odata-version", "4.0");
                    MediaTypeHeaderValue sharePointJsonMediaType = null;
                    MediaTypeHeaderValue.TryParse("application/json;odata.metadata=none;charset=utf-8", out sharePointJsonMediaType);
                    requestBody.Headers.ContentType = sharePointJsonMediaType;

                    if (!string.IsNullOrEmpty(accessToken))
                    {
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    }

                    requestBody.Headers.Add("X-RequestDigest", await clientContext.GetRequestDigest());

                    // Perform actual post operation
                    HttpResponseMessage response = await httpClient.SendAsync(request, new System.Threading.CancellationToken());

                    if (response.IsSuccessStatusCode)
                    {
                        // If value empty, URL is taken
                        var responseString = await response.Content.ReadAsStringAsync();

                        if (responseString != null)
                        {
                            try
                            {
                                var responseJson = JObject.Parse(responseString);
#if !NETSTANDARD2_0
                                if (Convert.ToInt32(responseJson["SiteStatus"]) == 2)
#else
                                if (responseJson["SiteStatus"].Value <int>() == 2)
#endif
                                {
                                    responseContext = clientContext.Clone(responseJson["SiteUrl"].ToString());
                                }
                                else
                                {
                                    throw new Exception(responseString);
                                }
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                    }
                    else
                    {
                        // Something went wrong...
                        throw new Exception(await response.Content.ReadAsStringAsync());
                    }
                }
                return(await Task.Run(() => responseContext));
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Creates a new Communication Site Collection and waits for it to be created
        /// </summary>
        /// <param name="clientContext">ClientContext object of a regular site</param>
        /// <param name="siteCollectionCreationInformation">information about the site to create</param>
        /// <returns>ClientContext object for the created site collection</returns>
        public static ClientContext Create(ClientContext clientContext, CommunicationSiteCollectionCreationInformation siteCollectionCreationInformation)
        {
            var context = CreateAsync(clientContext, siteCollectionCreationInformation).GetAwaiter().GetResult();

            return(context);
        }