Created
June 12, 2018 20:20
-
-
Save mbellinaso/be92d4897fa4ee0f31de11e0237ad2c6 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Text; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Microsoft.Azure.ServiceBus; | |
using Newtonsoft.Json; | |
namespace ServiceBusTopicsCLI | |
{ | |
class Program | |
{ | |
const string SERVICEBUSCONNSTRING = "<your conn string here...or in settings file!>"; | |
const string TOPICNAME = "productstockchanged"; | |
const string SUBNAME = "BackInStockNotifications"; | |
static ITopicClient topicClient; | |
static void Main(string[] args) | |
{ | |
MainAsync().GetAwaiter().GetResult(); | |
} | |
static async Task MainAsync() | |
{ | |
topicClient = new TopicClient(SERVICEBUSCONNSTRING, TOPICNAME); | |
Console.WriteLine("======================================================="); | |
Console.WriteLine("Enter command (eg: 'instock 123' or 'outofstock 123')"); | |
Console.WriteLine("======================================================="); | |
string cmd = ""; | |
do | |
{ | |
cmd = Console.ReadLine().Trim().ToLower(); | |
if (cmd.Equals("quit", StringComparison.OrdinalIgnoreCase)) | |
break; | |
var tokens = cmd.Split(" "); | |
if (tokens.Length != 2) { | |
Console.WriteLine("=> Invalid command"); | |
continue; | |
} | |
if (tokens[0].Equals("instock")) { | |
await SendMessageAsync(new ProductStockChanged { | |
IsInStock = true, ProductId = tokens[1] }); | |
} else if (tokens[0].Equals("outofstock")) { | |
await SendMessageAsync(new ProductStockChanged { | |
IsInStock = false, ProductId = tokens[1] }); | |
} else { | |
Console.WriteLine("=> Unknown command"); | |
continue; | |
} | |
Console.WriteLine("=> Done"); | |
} while (true); | |
await topicClient.CloseAsync(); | |
} | |
static async Task SendMessageAsync(ProductStockChanged msg) | |
{ | |
try | |
{ | |
var message = new Message(Encoding.UTF8.GetBytes( | |
JsonConvert.SerializeObject(msg))); | |
message.UserProperties["IsInStock"] = msg.IsInStock; | |
await topicClient.SendAsync(message); | |
} | |
catch (Exception exception) | |
{ | |
Console.WriteLine($"Failed to send the stock update for product | |
{msg.ProductId} - {exception.Message}"); | |
} | |
} | |
} | |
class ProductStockChanged { | |
public string ProductId { get; set; } | |
public bool IsInStock { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment