Last active
June 25, 2018 16:27
-
-
Save mbellinaso/0650b07f2e7cde7009600770f0441371 to your computer and use it in GitHub Desktop.
Misc-demos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#load "productstockchanged.csx" | |
using System; | |
using System.Threading.Tasks; | |
using System.Runtime.Serialization.Json; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Text; | |
public static void Run(string mySbMsg, TraceWriter log) | |
{ | |
log.Info($"C# ServiceBus topic trigger function processed message: {mySbMsg}"); | |
ProductStockChanged msg = GetProductStockChangedFromJson(mySbMsg); | |
if (msg.IsInStock) { | |
string postBody = $@"{{ | |
""audience"": {{ ""tag"" : ""notify-instock-{msg.ProductId}"" }}, | |
""notification"": {{ | |
""alert"": ""Product {msg.ProductId} is back in stock, hurry!"" | |
}}, | |
""device_types"": ""all"" | |
}}"; | |
HttpClient client = new HttpClient(); | |
var credentials = Encoding.ASCII.GetBytes( | |
"<UA credentials here, loaded from config or Key Vault>"); | |
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( | |
"Basic", Convert.ToBase64String(credentials)); | |
client.DefaultRequestHeaders.Accept.Clear(); | |
client.DefaultRequestHeaders.Add("Accept", | |
"application/vnd.urbanairship+json; version=3"); | |
var content = new StringContent(postBody, Encoding.UTF8, "application/json"); | |
var result = client.PostAsync("https://go.urbanairship.com/api/push", content).Result; | |
log.Info($"Notification for product {msg.ProductId} in-stock sent!"); | |
} else { | |
log.Info($"Skipped out-of-stock notification"); | |
} | |
} | |
public static ProductStockChanged GetProductStockChangedFromJson(string json) | |
{ | |
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) | |
{ | |
DataContractJsonSerializer ser = new DataContractJsonSerializer( | |
typeof(ProductStockChanged)); | |
ProductStockChanged msg = ser.ReadObject(ms) as ProductStockChanged; | |
return msg; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment