Skip to content

Instantly share code, notes, and snippets.

@crowcoder
Created October 14, 2019 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crowcoder/4db3151b3d0297816b2dbfb778982bd9 to your computer and use it in GitHub Desktop.
Save crowcoder/4db3151b3d0297816b2dbfb778982bd9 to your computer and use it in GitHub Desktop.
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace CosmosCreateSproc
{
class Program
{
static async Task Main(string[] args)
{
HttpClient client = new HttpClient();
string key = "*******************..........";
string dte = DateTime.UtcNow.ToString("R");
string cosmos_acct = "cosmos-***********";
string cosmos_db = "ToDoList";
string cosmos_container = $"Items";
string procName = "TESTSPROC_DELETE";
string procDef = "function() {\r\n var context = getContext();\r\nvar response = context.getResponse();\r\nresponse.setBody(%22Hello, World%22);\r\n}";
client.BaseAddress = new Uri($"https://{cosmos_acct}.documents.azure.com");
client.DefaultRequestHeaders.Add("x-ms-version", "2018-12-31");
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("x-ms-date", dte);
string authTkn = GenerateAuthToken("POST", "sprocs", $"dbs/{cosmos_db}/colls/{cosmos_container}", dte, key, "master", "1.0");
await CreateSproc(client, authTkn, procName, procDef, cosmos_db, cosmos_container);
client.Dispose();
Console.ReadKey();
}
static async Task CreateSproc(HttpClient client, string auth, string sprocname, string sprocDef, string database, string container)
{
string payload = $"{{ \"body\": \"{sprocDef}\", \"id\": \"{sprocname}\" }}";
using (var msg = new HttpRequestMessage(HttpMethod.Post, $"dbs/{database}/colls/{container}/sprocs"))
{
StringContent sc = new StringContent(payload);
msg.Content = sc;
msg.Headers.Add("authorization", auth);
using (var response = await client.SendAsync(msg))
{
string responseMsg = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseMsg);
response.EnsureSuccessStatusCode();
}
}
}
// Creates an Auth token for Cosmos REST API per spec.
static string GenerateAuthToken(string verb, string resourceType, string resourceId, string date, string key, string keyType, string tokenVersion)
{
var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };
verb = verb ?? "";
resourceType = resourceType ?? "";
resourceId = resourceId ?? "";
string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
verb.ToLowerInvariant(),
resourceType.ToLowerInvariant(),
resourceId,
date.ToLowerInvariant(),
""
);
byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
string signature = Convert.ToBase64String(hashPayLoad);
return System.Net.WebUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
keyType,
tokenVersion,
signature));
}
}
}
@Mike-Ubezzi-MSFT
Copy link

Can you send me your Cosmos account information? I am going to have the product team take a look at this. Please send to AzCommunity. Thank you!

@crowcoder
Copy link
Author

Can you send me your Cosmos account information? I am going to have the product team take a look at this. Please send to AzCommunity. Thank you!

What account information are you looking for? I obviously can't disclose anything private. I've recreated this issue in 3 separate subscriptions.

@Mike-Ubezzi-MSFT
Copy link

Mike-Ubezzi-MSFT commented Oct 18, 2019 via email

@crowcoder
Copy link
Author

I decided to install the Cosmos extension for VS Code and see what happened. I get "Error: Unexpected Token":

image

@Mike-Ubezzi-MSFT
Copy link

Mike-Ubezzi-MSFT commented Oct 21, 2019 via email

@Mike-Ubezzi-MSFT
Copy link

The product group responded and confirmed this is a product issue:

Thanks for your feedback. Right now, creating SP via REST api will accept unescaped js code. However, when portal read on stored procedures, it will run into invalid JSON issue. Our backend is working on a fix for this, but no timeline is known at this point.
I encourage you to create sp from portal, which will make sure you have valid sp for portal to consume.

Thank you!

@crowcoder
Copy link
Author

crowcoder commented Oct 21, 2019 via email

@crowcoder
Copy link
Author

Very good, thank you for all your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment