Creating an Authority Using REST (C#)
[This document supports a preliminary release of a software product that may be changed substantially prior to final commercial release. This document is provided for informational purposes only.]
As described in Creating an Authority Using REST, the following C# example creates an authority. The application performs the following steps:
- Create an XML payload describing the authority.
- Initialize a
WebRequest
instance with the service URI as the parameter. Requests to create an authority are sent to the service. In the request, theContent-Type
request header is set toapplication/x-ssds+xml
because the request payload is XML. - Send the request.
- Process the response. If authority creation is successful, application prints the message accordingly.
Note
Credentials are required to access the service. To make a working sample, update following code and provide id
value for the authority.
If you are using the Microsoft Visual Studio integrated development environment, create a console application, and then add the following code.
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Security;
namespace CreateAuthorityUsingREST
{
class Program
{
// Provide your values for these members variables
private static string userName;
private static string password;
private const string sampleAuthorityId = "<ProvideAuthorityID>";
static void Main(string[] args)
{
Console.Write("Username: ");
userName = Console.ReadLine();
Console.Write("Password: ");
password = ReadPassword();
string ServiceUri = "https://data.database.windows.net/v1/";
string authorityUri = CreateAuthority(ServiceUri);
}
private static string CreateAuthority(string serviceUri)
{
// Template to create authority request body. The only thing that
// is variable is the authority id.
const string AuthorityTemplate =
@"<s:Authority xmlns:s='https://schemas.microsoft.com/sitka/2008/03/'>
<s:Id>{0}</s:Id>
</s:Authority>";
if (String.IsNullOrEmpty(serviceUri))
{
throw new ArgumentOutOfRangeException("ServiceUri");
}
string authorityUri = null;
try
{
// Data going over to the server
string requestPayload = string.Format(AuthorityTemplate, sampleAuthorityId);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(serviceUri);
// Security requirement - need to pass userid, password
request.Credentials = new NetworkCredential(userName, password);
// POST=create; PUT=update; DELETE=delete; GET=retrieve
request.Method = "POST";
UTF8Encoding encoding = new UTF8Encoding();
request.ContentLength = encoding.GetByteCount(requestPayload);
request.ContentType = "application/x-ssds+xml";
// Write the request data over the wire (1st container).
using (Stream reqStm = request.GetRequestStream())
{
reqStm.Write(encoding.GetBytes(requestPayload), 0, encoding.GetByteCount(requestPayload));
}
// Get the response and read it in to a string.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.Created)
{
Console.WriteLine("Authority created");
// Since current implementation returns response.Headers[HttpResponseHeader.Location]
// value null, construct authority URI
authorityUri = String.Format("https://{0}.data.database.windows.net/v1/", sampleAuthorityId);
}
else
{
Console.WriteLine("Failed to create authority");
}
}
}
catch (WebException ex)
{
using (HttpWebResponse response = ex.Response as HttpWebResponse)
{
if (response != null)
{
string errorMsg = ReadResponse(response);
Console.WriteLine(string.Format("Error: {0}", errorMsg));
Console.WriteLine("Unexpected status code returned: {0} ", response.StatusCode);
}
}
}
return authorityUri;
}
public static string ReadResponse(HttpWebResponse response)
{
// Begin by validating our inbound parameters.
//
if (response == null)
{
throw new ArgumentNullException("response", "Value cannot be null");
}
// Then, open up a reader to the response and read the contents to a string
// and return that to the caller.
//
string responseBody = "";
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// NOTE: Assumption here is that the string isn't large.
responseBody = reader.ReadToEnd();
reader.Close();
}
return responseBody;
}
private static string ReadPassword()
{
StringBuilder retval = new StringBuilder();
ConsoleKeyInfo keyInfo;
while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter)
{
Console.Write("*");
retval.Append(keyInfo.KeyChar);
}
Console.WriteLine();
return retval.ToString();
}
}
}
To verify that the authority was created, enter the authority URI in the Web browser.
https://<authority-id>.data.database.windows.net/v1/
Note
When querying for non-blob entities your browser need to be aware of the application/x-ssds+xml
SSDS content type. For Internet Explorer this can be done by adding a new key in the registry. For more information, see Guidelines and Limitations.
This returns authority metadata as shown in the following sample XML:
<s:Authority
xmlns:s="https://schemas.microsoft.com/sitka/2008/03/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:x="http://www.w3.org/2001/XMLSchema">
<s:Id>NewAuthorityID</s:Id>
<s:Version>version-number</s:Version>
</s:Authority>