SonarCloud API - restore

Hi,
I would like to restore quality profile from backup xml file using sonarcloud API in my c# application. Documentation says that api/qualityprofiles/restore takes 2 parameters: organization name and backup as xml file. The problem is I’m not sure how to send a file as parameter. Here is what I am trying:

public async Task UploadProfileAsync()
        {
            var tokken = ConfigurationManager.AppSettings.Get("tokken");
            var organization = ConfigurationManager.AppSettings.Get("organization");

            var client = new HttpClient
            {
                DefaultRequestHeaders =
                {
                    Authorization = GetBasicAuthTokenHeader(tokken)
                }
            };

            var filePath = "test.xml";
            XmlDocument fileXml = new XmlDocument();
            fileXml.Load(filePath);

            var content = new StringContent(string.Empty, Encoding.UTF8, "application/xml");
            var uri = new Uri($"https://sonarcloud.io/api/qualityprofiles/restore?organization={organization}&backup={fileXml.OuterXml}");
            HttpResponseMessage response = await client.PostAsync(uri, content);

            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseContent);
            }
            else
            {
                Console.WriteLine(response.ToString());
            }
        }

This code and everything else I have tried produces “Bad Request” response. Could anyone help me with this code or show an example of api/qualityprofiles/restore usage?

Best regards.

Hi @NawW and welcome to the community !

This API can be called with a multipart/form-data payload, considering the binary (XML payload) to pass.

HTH,
Mickaël

MultipartFormDataContent worked for me, here is final code:

var uri = new Uri($"https://sonarcloud.io/api/qualityprofiles/restore");

MultipartFormDataContent content = new MultipartFormDataContent();

content.Add(new StringContent(organization), "organization");

byte[] bytes = Encoding.UTF8.GetBytes(fileXml.OuterXml);
content.Add(new ByteArrayContent(bytes), "backup");

HttpResponseMessage response = await client.PostAsync(uri, content); 

Thank you very much for help.

Best regards.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.