Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
209 lines (158 sloc) 9.06 KB
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Formatting;
using System.Threading;
namespace REST_from.NET
{
//This is used when executing a query via REST
//DocumentDB expects a specific Content-Type for queries
//When setting the Content-Type header it must not have a charset, currently.
//This custom class sets the correct Content-Type and clears the charset
public class NoCharSetJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public override void SetDefaultContentHeaders(Type type, System.Net.Http.Headers.HttpContentHeaders headers, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
{
base.SetDefaultContentHeaders(type, headers, new System.Net.Http.Headers.MediaTypeHeaderValue("application/query+json"));
headers.ContentType.CharSet = "";
}
}
//A custom extension of HttpClient that adds a new PostWithNoCharSet async method
//that uses the custom MediaTypeFormatter class to post with the correct Content-Type header
public static class HttpClientExtensions
{
public static async Task<HttpResponseMessage> PostWithNoCharSetAsync<T>(this HttpClient client, Uri requestUri, T value) { return await client.PostAsync(requestUri, value, new NoCharSetJsonMediaTypeFormatter()); }
}
class SqlQuerySpec
{
public string query { get; set; }
}
class Program
{
static readonly string endpoint = "";
static readonly string masterKey = "";
static readonly Uri baseUri = new Uri(endpoint);
//DocumentDB supports two different ways of addressing resources,
//This sample shows you how to deal with both ways.
//Uncomment the appropriate code below based on the way you prefer to address resources
//1. Using internal resource ids (_rid). These are encoded ids that are generated by the system
//static readonly string databaseId = "prdnAA==";
//static readonly string collectionId = "prdnAIbaDQA=";
//static readonly string documentId = "prdnAIbaDQAGAAAAAAAAAA==";
//static bool idBased = false;
//2. User settable ids (id). These are the id values you give a resource when you create it
static readonly string databaseId = "sandpit";
static readonly string collectionId = "data";
static readonly string documentId = "test";
static bool idBased = true;
static readonly string utc_date = DateTime.UtcNow.ToString("r");
static void Main(string[] args)
{
var client = new System.Net.Http.HttpClient();
string response = string.Empty;
string authHeader = string.Empty;
string verb = string.Empty;
string resourceType = string.Empty;
string resourceId = string.Empty;
string resourceLink = string.Empty;
client.DefaultRequestHeaders.Add("x-ms-date", utc_date);
client.DefaultRequestHeaders.Add("x-ms-version", "2015-08-06");
//LIST all databases
verb = "GET";
resourceType = "dbs";
resourceId = string.Empty;
resourceLink = string.Format("dbs");
authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0");
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", authHeader);
response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result;
Console.WriteLine(response);
Console.ReadKey();
//GET a database
verb = "GET";
resourceType = "dbs";
resourceLink = "dbs/" + databaseId;
resourceId = (idBased) ? resourceLink : databaseId.ToLowerInvariant();
authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0");
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", authHeader);
response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result;
Console.WriteLine(response);
Console.ReadKey();
//LIST all collections
verb = "GET";
resourceType = "colls";
resourceLink = string.Format("dbs/{0}/colls", databaseId);
resourceId = (idBased) ? string.Format("dbs/{0}", databaseId) : databaseId.ToLowerInvariant();
authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0");
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", authHeader);
response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result;
Console.WriteLine(response);
Console.ReadKey();
//GET a collections
verb = "GET";
resourceType = "colls";
resourceLink = string.Format("dbs/{0}/colls/{1}", databaseId, collectionId);
resourceId = (idBased) ? resourceLink : collectionId.ToLowerInvariant();
authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0");
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", authHeader);
response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result;
Console.WriteLine(response);
Console.ReadKey();
//LIST all documents in a collection
verb = "GET";
resourceType = "docs";
resourceLink = string.Format("dbs/{0}/colls/{1}/docs", databaseId, collectionId);
resourceId = (idBased) ? string.Format("dbs/{0}/colls/{1}", databaseId, collectionId) : collectionId.ToLowerInvariant();
authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0");
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", authHeader);
response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result;
Console.WriteLine(response);
Console.ReadKey();
//GET a document
verb = "GET";
resourceType = "docs";
resourceLink = string.Format("dbs/{0}/colls/{1}/docs/{2}", databaseId, collectionId, documentId);
resourceId = (idBased) ? resourceLink : documentId.ToLowerInvariant();
authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0");
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", authHeader);
response = client.GetStringAsync(new Uri(baseUri, resourceLink)).Result;
Console.WriteLine(response);
Console.ReadKey();
//EXECUTE a query
verb = "POST";
resourceType = "docs";
resourceLink = string.Format("dbs/{0}/colls/{1}/docs", databaseId, collectionId);
resourceId = (idBased) ? string.Format("dbs/{0}/colls/{1}", databaseId, collectionId) : collectionId.ToLowerInvariant();
authHeader = GenerateMasterKeyAuthorizationSignature(verb, resourceId, resourceType, masterKey, "master", "1.0");
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", authHeader);
client.DefaultRequestHeaders.Add("x-ms-documentdb-isquery", "True");
var qry = new SqlQuerySpec { query = "SELECT * FROM root" };
var r = client.PostWithNoCharSetAsync(new Uri(baseUri, resourceLink), qry).Result;
Console.WriteLine(r.Content.ToString());
}
private static string GenerateMasterKeyAuthorizationSignature(string verb, string resourceId, string resourceType, string key, string keyType, string tokenVersion)
{
var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };
string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
verb.ToLowerInvariant(),
resourceType.ToLowerInvariant(),
resourceId,
utc_date.ToLowerInvariant(),
""
);
byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
string signature = Convert.ToBase64String(hashPayLoad);
return System.Web.HttpUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
keyType,
tokenVersion,
signature));
}
}
}
You can’t perform that action at this time.