1

I want to update Site Name using CSOM for SharePoint Site which is connected to Office 365 Group so at the end I want to update SharePoint Site Title and Office 365 Group Name both.

I have tried CSOM to update Site Title and Graph API to update Site Name as well Group Name

    var authManager = new PnP.Framework.AuthenticationManager(ClientId, CertificatePath, CertificatePassword, TenantId);
    using (ClientContext sourceSiteContext = authManager.GetContext("https://contoso.sharepoint.com/sites/SiteRenameTest"))
            {

                sourceSiteContext.Web.Title = "Updated Site Title";
                sourceSiteContext.Web.Update();
                sourceSiteContext.ExecuteQuery();


                sourceSiteContext.Load(sourceSiteContext.Site);
                sourceSiteContext.ExecuteQuery();


                var graphAccessToken = await authManager.GetAccessTokenAsync(new string[] { "https://graph.microsoft.com/.default" });
                var spAccessToken = await authManager.GetAccessTokenAsync(new string[] { "https://contoso.sharepoint.com/.default" });

                Microsoft.Graph.GraphServiceClient graphServiceClient = new Microsoft.Graph.GraphServiceClient(new Microsoft.Graph.DelegateAuthenticationProvider(
                async (requestMessage) =>
                {

                    requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", graphAccessToken);
                }));

                var group = new Microsoft.Graph.Group
                {
                    DisplayName = "Updated Site Title"                        
                };
                var response = await graphServiceClient.Groups[sourceSiteContext.Site.GroupId.ToString()].Request().UpdateAsync(group);
           }

Using above method, it updates Site Title and Office 365 Group Name but it does not update under Site Information Panel,

enter image description here

enter image description here

enter image description here

Now what is happening is if someone just open Site Information Panel(which still shows old Site Title) and cancel it without saving it, in background(after 10 minutes) Site Title and Office 365 Group changes with previous site name.

I have also tried to update Site Title using same way which SharePoint is using internally from UI i.e. _api/SP.Directory.DirectorySession/Group('{0}) (I need to find it using fiddler as there is no official documentation provided by Microsoft here), but it gives error like "The parameter __metadata does not exist in method Group.". I have tried with POST / PATCH call both and also tried to set ODataVersion but didn't work

HttpClient client = new HttpClient();
string requestDigest = await GetRequestDigest(spAccessToken, "https://contoso.sharepoint.com/sites/SiteRenameTest");
HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("POST"), "https://contoso.sharepoint.com/sites/SiteRenameTest" + string.Format("/_api/SP.Directory.DirectorySession/Group('{0}')", sourceSiteContext.Site.GroupId.ToString()));
client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata=verbose"));
message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", spAccessToken);
message.Headers.Add("X-RequestDigest", requestDigest);
//message.Headers.Add("X-HTTP-Method", "PATCH");
//client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
//client.DefaultRequestHeaders.Add("OData-Version", "3.0");
//client.DefaultRequestHeaders.Add("prefer", "return=representation");

string requestContent = JsonConvert.SerializeObject(new ChangeSiteNameRequestModel()
{
    __metadata = new __Metadata() { type = "SP.Directory.Group" },
    displayName = "SiteRename-KV1"
});
message.Content = new StringContent(requestContent, Encoding.Default);
message.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
HttpResponseMessage response = await client.SendAsync(message);

if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
    var responseContext = await response.Content.ReadAsStringAsync();
}
else
{
    var responseContext = await response.Content.ReadAsStringAsync();
}

Request Model schema which I am using

    public class ChangeSiteNameRequestModel
{
    public __Metadata __metadata { get; set; }
    public string displayName { get; set; }
}

public class __Metadata
{
    public string type { get; set; }
}

Below is the screen shot from Fiddler for API which SharePoint is using.

enter image description here

My end goal is here to update Site Name of the site which is connected to group in such a way that it will update site title (even in Site Information Panel), office 365 group name and also it should show updated site name in SharePoint Admin Center.

Any help would be highly appreciated here.

1 Answer 1

1

I found the solution with this link.

Here is my updated code which changes Site Name everywhere:

namespace ConsoleApp1
{
    internal class Program
    {
                
        static string CertificatePath = @"";
        static string CertificatePassword = "";
        static string TenantId = "";
        static string ClientId = "";
        static async Task Main(string[] args)
        {
            try
            {
                string siteUrl = "https://contoso.sharepoint.com/sites/SiteRename2";
                //await ShareDocumentDemo();
                var authManager = new PnP.Framework.AuthenticationManager(ClientId, CertificatePath, CertificatePassword, TenantId);
                using (ClientContext sourceSiteContext = authManager.GetContext(siteUrl))
                {
                    sourceSiteContext.Load(sourceSiteContext.Site);
                    sourceSiteContext.ExecuteQuery();


                    string newSiteTitle = "Update Site Title Final Test";
                   

                    var graphAccessToken = await authManager.GetAccessTokenAsync(new string[] { "https://graph.microsoft.com/.default" });
                    var spAccessToken = await authManager.GetAccessTokenAsync(new string[] { "https://contoso.sharepoint.com/.default" });                                       
                    await UpdateSiteName(siteUrl, spAccessToken, sourceSiteContext,newSiteTitle);
                    await SyncGroupProperty(siteUrl, spAccessToken, sourceSiteContext);

                }
            }
            catch (Exception ex)
            {

            }
        }
        public static async Task SyncGroupProperty(string siteUrl, string spAccessToken, ClientContext sourceSiteContext)
        {
            HttpClient client = new HttpClient();
            string requestDigest = await GetRequestDigest(spAccessToken, siteUrl);
            HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("POST"), siteUrl + string.Format("/_api/GroupService/SyncGroupProperties"));
            client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata=verbose"));
            message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", spAccessToken);
            message.Headers.Add("X-RequestDigest", requestDigest);           
            HttpResponseMessage response = await client.SendAsync(message);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var responseContext = await response.Content.ReadAsStringAsync();
            }
            else
            {
                var responseContext = await response.Content.ReadAsStringAsync();
            }
        }
        public static async Task UpdateSiteName(string siteUrl, string spAccessToken, ClientContext sourceSiteContext, string siteTitle)
        {            
            HttpClient client = new HttpClient();
            string requestDigest = await GetRequestDigest(spAccessToken, siteUrl);
            HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("PATCH"), siteUrl + string.Format("/_api/SP.Directory.DirectorySession/Group('{0}')", sourceSiteContext.Site.GroupId.ToString()));
            client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata=verbose"));            
            message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", spAccessToken);
            message.Headers.Add("X-RequestDigest", requestDigest);                                    

            string requestContent = JsonConvert.SerializeObject(new ChangeSiteNameRequestModel()
            {
                __metadata = new __Metadata() { type = "SP.Directory.Group" },
                displayName = siteTitle
            });
            message.Content = new StringContent(requestContent, Encoding.Default);
            message.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
            //message.Content.Headers.Add("Accept", "application/json;odata=verbose");
            HttpResponseMessage response = await client.SendAsync(message);

            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                var responseContext = await response.Content.ReadAsStringAsync();
            }
            else
            {
                var responseContext = await response.Content.ReadAsStringAsync();
            }
        }       
        public static async Task<string> GetRequestDigest(string accessToken, string siteUrl)
        {
            HttpClient client = new HttpClient();
            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, siteUrl + "/_api/contextinfo");

            message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
            //message.Headers.Add("Content-Type", "application/json;odata=verbose");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //client.Headers.Add(HttpRequestHeader.Accept, "application/json;odata=verbose");
            HttpResponseMessage response = await client.SendAsync(message);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                RequestDigestResponse requestDigestResponse = JsonConvert.DeserializeObject<RequestDigestResponse>(responseContent);

                return requestDigestResponse.FormDigestValue;
            }


            return "";

        }
       
        
    }


    public class ChangeSiteNameRequestModel
    {
        public __Metadata __metadata { get; set; }
        public string displayName { get; set; }
    }

    public class __Metadata
    {
        public string type { get; set; }
    }

    public class RequestDigestResponse
    {


        public string FormDigestValue { get; set; }

    }   
   }

Important: API Which I have used is not documented API by Microsoft.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.