I was working with the latest Windows Azure SDK 1.7 REST
APIs for various operations related to services, roles and virtual machines.
Here I’m posting on how we can create a hosted service using
REST APIs using the basic HTTPRequest POST methods.
First we need to know where we need to POST our request. The
URL will be:
You have to replace your Azure subscription id.
Next step is what we need to post in our request. So we’ll
create our request body. It is an XML file which will have some of the
properties related to the service which we want to host.
So I’ll call my xml file as CreateHostedService.xml and it
will be like:
<?xml
version="1.0" encoding="utf-8"?>
<CreateHostedService
xmlns="http://schemas.microsoft.com/windowsazure">
<ServiceName>service-name</ServiceName>
<Label>base64-encoded-service-label</Label>
<Description>description</Description>
<Location>location</Location>
<AffinityGroup>affinity-group</AffinityGroup>
<ExtendedProperties>
<ExtendedProperty>
<Name>property-name</Name>
<Value>property-value</Value>
</ExtendedProperty>
</ExtendedProperties>
</CreateHostedService>
The mandatory properties here are Service Name, Label,
Location or Affinity Group (either one of them).
Now we will have to use this XML in our C# code to POST the
request to the URL specified above.
I’ll write a function called CreatedHostedService which will
accept parameters like URL, SubscriptionId, and the location of XML file which
needs to be posted.
private void CreateHostedService(string url, string
subscriptionId, string xmlLocationPath)
{
Uri
uri = new Uri(String.Format(url, subscriptionId));
XDocument
document = null;
HttpWebRequest request =
HttpWebRequest)HttpWebRequest.Create(txtRestCommand.Text);
request.Timeout
= 50000;
request.Headers.Add("x-ms-version", “2012-03-01”);
request.ClientCertificates.Add(certificate);
request.ContentType
= "application/xml";
If(xmlLocationPath
!= null || !string.IsNullorEmpty(xmlLocationPath)
{
document
= XDocument.Load(xmlLocationPath);
request.Method
= "POST";
StreamWriter writer = new
StreamWriter(request.GetRequestStream());
writer.Write(document);
writer.Close();
}
HttpStatusCode statusCode;
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException
ex)
{
// GetResponse throws a WebException for 400
and 500 status codes
response = (HttpWebResponse)ex.Response;
}
statusCode
= response.StatusCode;
response.Close();
}
We can customize this method. I’ve written a very basic
example to explain this.
Please note that you should have a valid X509 certificate in
your cert store as well a matching certificate uploaded on Azure portal for
your subscription ID. You can retrieve the certificate using the thumbprint of
the certificate.
The XML mentioned above is for MS Version “2012-03-01”.
For more detailed
explanation of the properties specified in XML, please refer to:
Cheers
Ankit
No comments:
Post a Comment