Azure provides various rest apis to perform different actions and operations that are possible in the azure server like to create web applications, databases and many more. User can design their own simplified UI to perform actions, instead of logging into Azure and perform all the steps one by one.
Below code is the Web application consumer in C# to create copy of database on the Azure Server.
The first important step in this case is to fetch the access token from the Azure server as proof of the authentication/authorization and second step is to use this token to perform request to create copy of database with proper parameters and request body content of type ‘application/json’
1. Fetch the Access token from the Azure Server:
https://docs.microsoft.com/en-us/rest/api/ describes the Uri scheme and its usage in using the rest api url’s. To fetch the access token, login to microsoft requires ‘CustomerKey’, ‘CustomerSecret’, ‘ResourceEndPt’ with grant type as “client_credentials” in the body parameters and ‘‘TenantId’ in the url parameter. The Resource Uri endpoint authenticates the requests for which the access token is valid. In general to perform database operation through client Web application (C#) , the Uri end point( or Resource Uri) is:
https://management.azure.com/
To invoke rest api url to fetch token, the conmplete Uri is formed as:
string uri = "https://login.microsoftonline.com/"<TenantId>"/oauth2/token";
Below is the C# code to send request for access token:
var webClient = new WebClient() { BaseAddress = uri }; var collection = new NameValueCollection(); collection.Add("grant_type", "client_credentials"); collection.Add("client_id", <CustomerKey>); collection.Add("client_secret", <CustomerSecret>); collection.Add("resource", <ResourceEndPt>); byte[] responseBytes = webClient.UploadValues("", "POST", collection); string response = Encoding.UTF8.GetString(responseBytes); string decodedResponse = HttpUtility.UrlDecode(response); JavaScriptSerializer js = new JavaScriptSerializer(); dynamic token = js.Deserialize<dynamic>(decodedResponse);
The result response parameters include access_token along with token_type, expires_in, ext_expires_in expires_on,not_before, resource information.
2. Url Parameters, header and request body Initialization:
Below is the screenshot from the microsoft site that expalins the parameters required in url, body part for creating the copy of database on Azure along with the response parameters:
General Uri Scheme in this case is:
string uri = <ResourceEndPt>"subscriptions/"<SubscriptionId>"/resourceGroups/"<ResourceGroup>“/providers/Microsoft.Sql/servers/"<ServerName>"/databases/"<NewDatabaseName>"?api-version="ApiVersion";
So you must have the knowledge of SubscriptionId, ResourceGroup, ServerName and require New Database Name in the parameters that is to be created. If your server is myserver.database.windows.net, then “myserver” is ServerName here to be filled in the url.
Request body for the request can be prepared as follows:
dynamic Properties = new { createMode = “Copy”, sourceDatabaseId= "/subscriptions/" <SubscriptionId> "/resourceGroups/" <ResourceGroup>" /providers/Microsoft.Sql/servers/" <ServerName> ”/databases/" <OldDatabaseName> }; dynamic Parameters = new { location = <Location>, properties = Properties };
Convert the body parameters into Json string:
string json = JsonConvert.SerializeObject(Parameters);
Access token is inserted into the header of a httprequest message which is used for Bearer Authentication of requested call on Azure.
3. Invoking the Azure Sql Database Rest Api to perform copy operation on existing database:
Below is the C# code to perform httprequest to Azure Rest api to create copy of database:
Uri address = new Uri(uri); // Uri from (2) step try { using (var client = new HttpClient()) { client.Timeout = new TimeSpan(1, 0, 0); client.BaseAddress = address; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.access_token); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); Task<HttpResponseMessage> taskResponse = client.PutAsync("", content); taskResponse.Wait(); HttpResponseMessage response = taskResponse.Result; if (response.IsSuccessStatusCode) { Task<string> taskread = response.Content.ReadAsStringAsync(); taskread.Wait(); result = taskread.Result; } else { Task<string> taskread = response.Content.ReadAsStringAsync(); taskread.Wait(); result = taskread.Result; System.Diagnostics.Trace.WriteLine(response.StatusCode.ToString()); System.Diagnostics.Trace.WriteLine(result); } }
One comment