public async void ReadUsingEventHubProcessor() { string serviceBusNamespace = "iotmc-ns"; string eventHubName = "iotmc"; string eventHubSASKeyName = "Device01"; string eventHubSASKey = "<< Add your SAS here >>"; string storageAccountName = "iotmc"; string storageAccountKey = "<< add your Storage Account key here >>"; string storageConnectionString = String.Format(@"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", storageAccountName, storageAccountKey); string eventHubConnectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty), eventHubSASKeyName, eventHubSASKey); EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString, eventHubName); EventHubConsumerGroup eventHubConsumerGroup = eventHubClient.GetDefaultConsumerGroup(); EventProcessorHost eventProcessorHost = new EventProcessorHost("MSTechDemoWorker", eventHubClient.Path, eventHubConsumerGroup.GroupName, eventHubConnectionString, storageConnectionString); //await eventProcessorHost.RegisterEventProcessorAsync<EventHubEventProcessor>(); //Ignore older messages even if they are still in the event hub store Task t = eventProcessorHost.RegisterEventProcessorAsync <EventHubEventProcessor>(new EventProcessorOptions() { InitialOffsetProvider = (partitionId) => { return(DateTime.UtcNow.AddHours(-1)); } }); t.Wait(); }
static void SendingRandomMessages(string deviceName, string hash, string eventHubName, string serviceBus) { var serviceBusUri = new Uri(String.Format("sb://{0}.servicebus.windows.net/", serviceBus)); var connStr = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey(serviceBusUri, deviceName, hash); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Using connection string:" + connStr); var eventHubClient = EventHubClient.CreateFromConnectionString(connStr, eventHubName); eventHubClient.RetryPolicy = RetryPolicy.Default; var rand = new Random(); int counter = 0; while (true) { try { var sensor = new SensorData { DeviceName = deviceName, RecordedAt = DateTime.UtcNow, SensorType = "Temperature", MeasuredValue = rand.Next(25, 27), MessageId = Guid.NewGuid().ToString() }; var dataString = JsonConvert.SerializeObject(sensor, Formatting.Indented); using (var eventData = new EventData(Encoding.UTF8.GetBytes(dataString))) { // Set user properties if needed eventData.Properties.Add("Type", "Telemetry_" + DateTime.Now.ToLongTimeString()); eventData.PartitionKey = deviceName; eventHubClient.Send(eventData); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Sent Message to Hub:" + (++counter)); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine(dataString); Thread.Sleep(500); } catch (Exception exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message); Console.ResetColor(); } Thread.Sleep(200); } }
private static NamespaceManager CreateNamespaceManager(Configuration configuration, TimeSpan timeout) { var endpoint = ServiceBusEnvironment.CreateServiceUri("sb", configuration.EventHubNamespace, string.Empty); var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey(endpoint, configuration.EventHubSasKeyName, configuration.EventHubSasKey); var nsm = NamespaceManager.CreateFromConnectionString(connectionString); nsm.Settings.OperationTimeout = timeout; return(nsm); }
public void ReadFromEventHubPartition() { string serviceBusNamespace = "iotmc-ns"; string eventHubName = "IoTMC"; string eventHubSASKeyName = "Device01"; int eventHubPartitionCount = 8; string eventHubSASKey = "<< Add your SAS here >>"; string eventHubConnectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty), eventHubSASKeyName, eventHubSASKey); EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString, eventHubName); EventHubConsumerGroup eventHubConsumerGroup = eventHubClient.GetDefaultConsumerGroup(); for (int i = 0; i < eventHubPartitionCount; i++) { string partitionId = i.ToString(); Task.Run(async() => { //Just "new" message -> DateTime.Now EventHubReceiver eventHubReceiver = eventHubConsumerGroup.CreateReceiver(partitionId, DateTime.Now); //All existing messages in partition -> -1 //EventHubReceiver eventHubReceiver = await eventHubConsumerGroup.CreateReceiverAsync(partitionId, "-1"); do { EventData eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(2)); if (eventData != null) { string message = Encoding.UTF8.GetString(eventData.GetBytes()); string messageDetails = String.Format("Received: Seq number={0} Offset={1} Partition={2} EnqueueTimeUtc={3} Message={4}", eventData.SequenceNumber, eventData.Offset, eventHubReceiver.PartitionId, eventData.EnqueuedTimeUtc.ToShortTimeString(), message); Console.WriteLine(messageDetails); //Store Partition-Id & Offset for further processing string restorePoint_PartitionId = eventHubReceiver.PartitionId; string restorePoint_Offset = eventData.Offset; } } while (true); }); } }
public void ReadFromEventHubPartition() { string serviceBusNamespace = "iotmc-ns"; string eventHubName = "IoTMC"; string eventHubSASKeyName = "Device01"; int eventHubPartitionCount = 8; string eventHubSASKey = "<< Add your SAS here >>"; string eventHubConnectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty), eventHubSASKeyName, eventHubSASKey); EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString, eventHubName); EventHubConsumerGroup eventHubConsumerGroup = eventHubClient.GetDefaultConsumerGroup(); for (int i = 0; i < eventHubPartitionCount; i++) { string partitionId = i.ToString(); Task.Run(async() => { //Just "new" message -> DateTime.Now EventHubReceiver eventHubReceiver = eventHubConsumerGroup.CreateReceiver(partitionId, DateTime.Now); //All existing messages in partition -> -1 //EventHubReceiver eventHubReceiver = await eventHubConsumerGroup.CreateReceiverAsync(partitionId, "-1"); do { EventData eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(2)); if (eventData != null) { Telemetry telemetry = JsonConvert.DeserializeObject <Telemetry>(Encoding.UTF8.GetString(eventData.GetBytes())); AnalyticsEngine._humidityTelemetryIngest.Push(telemetry.Humidity); AnalyticsEngine._pollutionTelemetryIngest.Push(telemetry.Pollution); Debug.WriteLine(telemetry.Pollution.ToString(), eventData.EnqueuedTimeUtc.ToString()); //Store Partition-Id & Offset for further processing string restorePoint_PartitionId = eventHubReceiver.PartitionId; string restorePoint_Offset = eventData.Offset; } } while (true); }); } }
public Task TelemetryIngest(Telemetry telemetry) { string serviceBusNamespace = "iotmc-ns"; string eventHubName = "IoTMC"; string eventHubSASKeyName = "Device01"; string eventHubSASKey = "<< Add your SAS here >>"; string eventHubConnectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty), eventHubSASKeyName, eventHubSASKey); EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString, eventHubName); return(Task.Run(async() => { EventData eventData = new EventData(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(telemetry))); eventData.PartitionKey = telemetry.DeviceId.ToString(); await eventHubClient.SendAsync(eventData); })); }
public async void ReadUsingEventHubProcessor() { string serviceBusNamespace = "iotmc-ns"; string eventHubName = "iotmc"; string eventHubSASKeyName = "Device01"; string eventHubSASKey = "<< Add your SAS here >>"; string storageAccountName = "iotmc"; string storageAccountKey = "<< Add your Storage Account Key here >>"; string storageConnectionString = String.Format(@"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", storageAccountName, storageAccountKey); string eventHubConnectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty), eventHubSASKeyName, eventHubSASKey); EventHubClient eventHubClient = EventHubClient.CreateFromConnectionString(eventHubConnectionString, eventHubName); EventHubConsumerGroup eventHubConsumerGroup = eventHubClient.GetDefaultConsumerGroup(); EventProcessorHost eventProcessorHost = new EventProcessorHost("IoT_MasterClass", eventHubClient.Path, eventHubConsumerGroup.GroupName, eventHubConnectionString, storageConnectionString); await eventProcessorHost.RegisterEventProcessorAsync <EventHubEventProcessor>(); }
static void Run() { var properties = new Dictionary <string, string> { { servicebusNamespace, null }, { servicebusEntityPath, null }, { servicebusFqdnSuffix, null }, { servicebusSendKey, null }, { servicebusListenKey, null }, { servicebusManageKey, null } }; // read the settings file created by the ./setup.ps1 file var settingsFile = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), samplePropertiesFileName); if (File.Exists(settingsFile)) { using (var fs = new StreamReader(settingsFile)) { while (!fs.EndOfStream) { var readLine = fs.ReadLine(); if (readLine != null) { var propl = readLine.Trim(); var cmt = propl.IndexOf('#'); if (cmt > -1) { propl = propl.Substring(0, cmt).Trim(); } if (propl.Length > 0) { var propi = propl.IndexOf('='); if (propi == -1) { continue; } var propKey = propl.Substring(0, propi - 1).Trim(); var propVal = propl.Substring(propi + 1).Trim(); if (properties.ContainsKey(propKey)) { properties[propKey] = propVal; } } } } } } // get overrides from the environment foreach (var prop in properties) { var env = Environment.GetEnvironmentVariable(prop.Key); if (env != null) { properties[prop.Key] = env; } } var hostName = properties[servicebusNamespace] + "." + properties[servicebusFqdnSuffix]; var rootUri = new UriBuilder("http", hostName, -1, "/").ToString(); var netTcpUri = new UriBuilder("sb", hostName, -1, properties[servicebusEntityPath] + "/NetTcp").ToString(); var httpUri = new UriBuilder("https", hostName, -1, properties[servicebusEntityPath] + "/Http").ToString(); var program = Activator.CreateInstance(typeof(Program)); if (program is ITcpListenerSampleUsingKeys) { ((ITcpListenerSampleUsingKeys)program).Run( netTcpUri, "samplelisten", properties[servicebusListenKey]) .GetAwaiter() .GetResult(); } else if (program is ITcpSenderSampleUsingKeys) { ((ITcpSenderSampleUsingKeys)program).Run(netTcpUri, "samplesend", properties[servicebusSendKey]) .GetAwaiter() .GetResult(); } if (program is IHttpListenerSampleUsingKeys) { ((IHttpListenerSampleUsingKeys)program).Run( httpUri, "samplelisten", properties[servicebusListenKey]) .GetAwaiter() .GetResult(); } else if (program is IHttpSenderSampleUsingKeys) { ((IHttpSenderSampleUsingKeys)program).Run(httpUri, "samplesend", properties[servicebusSendKey]) .GetAwaiter() .GetResult(); } if (program is ITcpListenerSample) { var token = TokenProvider.CreateSharedAccessSignatureTokenProvider( "samplelisten", properties[servicebusListenKey]) .GetWebTokenAsync(netTcpUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((ITcpListenerSample)program).Run(netTcpUri, token).GetAwaiter().GetResult(); } else if (program is ITcpSenderSample) { var token = TokenProvider.CreateSharedAccessSignatureTokenProvider( "samplesend", properties[servicebusSendKey]) .GetWebTokenAsync(netTcpUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((ITcpSenderSample)program).Run(netTcpUri, token).GetAwaiter().GetResult(); } if (program is IHttpListenerSample) { var token = TokenProvider.CreateSharedAccessSignatureTokenProvider( "samplelisten", properties[servicebusListenKey]) .GetWebTokenAsync(httpUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IHttpListenerSample)program).Run(httpUri, token).GetAwaiter().GetResult(); } else if (program is IHttpSenderSample) { var token = TokenProvider.CreateSharedAccessSignatureTokenProvider( "samplesend", properties[servicebusSendKey]) .GetWebTokenAsync(httpUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IHttpSenderSample)program).Run(httpUri, token).GetAwaiter().GetResult(); } else if (program is IDynamicSenderSample) { var token = TokenProvider.CreateSharedAccessSignatureTokenProvider( "rootsamplesend", properties[servicebusSendKey]) .GetWebTokenAsync(rootUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDynamicSenderSample)program).Run(hostName, token).GetAwaiter().GetResult(); } else if (program is IDynamicListenerSample) { var token = TokenProvider.CreateSharedAccessSignatureTokenProvider( "rootsamplelisten", properties[servicebusListenKey]) .GetWebTokenAsync(rootUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDynamicListenerSample)program).Run(hostName, token).GetAwaiter().GetResult(); } else if (program is IDynamicSample) { var token = TokenProvider.CreateSharedAccessSignatureTokenProvider( "rootsamplemanage", properties[servicebusManageKey]) .GetWebTokenAsync(rootUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDynamicSample)program).Run(hostName, token).GetAwaiter().GetResult(); } else if (program is IConnectionStringSample) { var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( new Uri(rootUri), "rootsamplemanage", properties[servicebusManageKey]); ((IConnectionStringSample)program).Run(connectionString).GetAwaiter().GetResult(); } }
// [DebuggerStepThrough] static void Run() { var properties = new Dictionary <string, string> { { servicebusNamespace, null }, { servicebusEntityPath, null }, { servicebusFqdnEndpoint, null }, { servicebusSendKey, null }, { servicebusListenKey, null }, { servicebusManageKey, null } }; // read the settings file created by the ./setup.ps1 file var settingsFile = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), samplePropertiesFileName); if (File.Exists(settingsFile)) { using (var fs = new StreamReader(settingsFile)) { while (!fs.EndOfStream) { var readLine = fs.ReadLine(); if (readLine != null) { var propl = readLine.Trim(); var cmt = propl.IndexOf('#'); if (cmt > -1) { propl = propl.Substring(0, cmt).Trim(); } if (propl.Length > 0) { var propi = propl.IndexOf('='); if (propi == -1) { continue; } var propKey = propl.Substring(0, propi).Trim(); var propVal = propl.Substring(propi + 1).Trim(); if (properties.ContainsKey(propKey)) { properties[propKey] = propVal; } } } } } } // get overrides from the environment foreach (var prop in properties.Keys.ToArray()) { var env = Environment.GetEnvironmentVariable(prop); if (env != null) { properties[prop] = env; } } var endpoint = new Uri(properties[servicebusFqdnEndpoint]); var hostName = endpoint.Host; var rootUri = new UriBuilder(hostName).ToString(); var sbUri = new UriBuilder("sb", hostName, -1, "/").ToString(); var program = Activator.CreateInstance(typeof(Program)); if (program is IDynamicSample) { var token = TokenProvider.CreateSharedAccessSignatureTokenProvider( SampleManageKeyName, properties[servicebusManageKey]) .GetWebTokenAsync(rootUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDynamicSample)program).Run(sbUri, token).GetAwaiter().GetResult(); } else if (program is IDynamicSampleWithKeys) { ((IDynamicSampleWithKeys)program).Run( sbUri, SampleManageKeyName, properties[servicebusManageKey], SampleSendKeyName, properties[servicebusSendKey], SampleSendKeyName, properties[servicebusListenKey]).GetAwaiter().GetResult(); } else if (program is IBasicQueueSendReceiveSample) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicQueueSendReceiveSample)program).Run(sbUri, entityName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is IBasicQueueSendSample) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicQueueSendSample)program).Run(sbUri, entityName, sendToken).GetAwaiter().GetResult(); } else if (program is IBasicQueueReceiveSample) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicQueueReceiveSample)program).Run(sbUri, entityName, receiveToken).GetAwaiter().GetResult(); } else if (program is IPartitionedQueueSendReceiveSample) { var entityName = PartitionedQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IPartitionedQueueSendReceiveSample)program).Run(sbUri, entityName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is IPartitionedQueueSendSample) { var entityName = PartitionedQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IPartitionedQueueSendSample)program).Run(sbUri, entityName, sendToken).GetAwaiter().GetResult(); } else if (program is IPartitionedQueueReceiveSample) { var entityName = PartitionedQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IPartitionedQueueReceiveSample)program).Run(sbUri, entityName, receiveToken).GetAwaiter().GetResult(); } else if (program is ISessionQueueSendReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, SessionQueueName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((ISessionQueueSendReceiveSample)program).Run(sbUri, SessionQueueName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is ISessionQueueSendSample) { var entityName = SessionQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((ISessionQueueSendSample)program).Run(sbUri, entityName, sendToken).GetAwaiter().GetResult(); } else if (program is ISessionQueueReceiveSample) { var entityName = SessionQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((ISessionQueueReceiveSample)program).Run(sbUri, entityName, receiveToken).GetAwaiter().GetResult(); } else if (program is IDupdetectQueueSendReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, DupdetectQueueName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDupdetectQueueSendReceiveSample)program).Run(sbUri, DupdetectQueueName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is IDupdetectQueueSendSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, DupdetectQueueName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDupdetectQueueSendSample)program).Run(sbUri, DupdetectQueueName, sendToken).GetAwaiter().GetResult(); } else if (program is IDupdetectQueueReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, DupdetectQueueName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDupdetectQueueReceiveSample)program).Run(sbUri, DupdetectQueueName, receiveToken).GetAwaiter().GetResult(); } else if (program is IBasicTopicSendReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, BasicTopicName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicTopicSendReceiveSample)program).Run(sbUri, BasicTopicName, sendToken, receiveToken).GetAwaiter().GetResult(); } else if (program is IBasicTopicSendSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, BasicTopicName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicTopicSendSample)program).Run(sbUri, BasicTopicName, sendToken).GetAwaiter().GetResult(); } else if (program is IBasicTopicReceiveSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, BasicTopicName).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IBasicTopicReceiveSample)program).Run(sbUri, BasicTopicName, receiveToken).GetAwaiter().GetResult(); } else if (program is IBasicTopicConnectionStringSample) { var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( new Uri(rootUri), SampleManageKeyName, properties[servicebusManageKey]); ((IBasicTopicConnectionStringSample)program).Run(BasicTopicName, connectionString).GetAwaiter().GetResult(); } else if (program is IConnectionStringSample) { var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( new Uri(rootUri), SampleManageKeyName, properties[servicebusManageKey]); ((IConnectionStringSample)program).Run(connectionString).GetAwaiter().GetResult(); } else if (program is IBasicQueueConnectionStringSample) { var connectionString = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( new Uri(rootUri), SampleManageKeyName, properties[servicebusManageKey]); ((IBasicQueueConnectionStringSample)program).Run(BasicQueueName, connectionString).GetAwaiter().GetResult(); } else if (program is IDualQueueSendReceiveSample) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var entity2Name = BasicQueue2Name; var entity2Uri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entity2Name).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entity2Uri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDualQueueSendReceiveSample)program).Run(sbUri, entityName, sendToken, entity2Name, receiveToken).GetAwaiter().GetResult(); } else if (program is IDualQueueSampleWithFullRights) { var entityName = BasicQueueName; var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entityName).ToString(); var token1 = TokenProvider.CreateSharedAccessSignatureTokenProvider( ManageKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var entity2Name = BasicQueue2Name; var entity2Uri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entity2Name).ToString(); var token2 = TokenProvider.CreateSharedAccessSignatureTokenProvider( ManageKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entity2Uri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDualQueueSampleWithFullRights)program).Run(sbUri, entityName, token1, entity2Name, token2).GetAwaiter().GetResult(); } else if (program is IDualQueueSendReceiveFlipsideSample) { var entityUri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, BasicQueue2Name).ToString(); var sendToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( SendKeyName, properties[servicebusSendKey]) .GetWebTokenAsync(entityUri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); var entity2Name = BasicQueueName; var entity2Uri = new UriBuilder(Uri.UriSchemeHttp, hostName, -1, entity2Name).ToString(); var receiveToken = TokenProvider.CreateSharedAccessSignatureTokenProvider( ReceiveKeyName, properties[servicebusListenKey]) .GetWebTokenAsync(entity2Uri, string.Empty, true, TimeSpan.FromHours(1)).GetAwaiter().GetResult(); ((IDualQueueSendReceiveFlipsideSample)program).Run(sbUri, BasicQueue2Name, sendToken, entity2Name, receiveToken). GetAwaiter(). GetResult(); } else if (program is IBasicQueueSampleWithKeys) { ((IBasicQueueSampleWithKeys)program).Run( sbUri, BasicQueueName, SendKeyName, properties[servicebusSendKey], ReceiveKeyName, properties[servicebusListenKey]).GetAwaiter().GetResult(); ; } else if (program is IDualBasicQueueSampleWithKeys) { ((IDualBasicQueueSampleWithKeys)program).Run( sbUri, BasicQueueName, BasicQueue2Name, SendKeyName, properties[servicebusSendKey], ReceiveKeyName, properties[servicebusListenKey]).GetAwaiter().GetResult(); } }
static void Main(string[] args) { if (1 > args.Length) { Usage(); return; } // // Perform the operation indicated by the first command line // argument // if (0 == String.Compare(args[0], OPERATION_REGISTER, true)) { // // Create an attested key // CngProvider cng = new CngProvider(SNKSP); CngKeyCreationParameters createParams = new CngKeyCreationParameters(); createParams.Provider = cng; createParams.KeyCreationOptions = CngKeyCreationOptions.None; CngKey snKey = CngKey.Create( CngAlgorithm2.Rsa, ATTESTED_KEY_NAME, createParams); // // Create a signed request message // StringBuilder pubKeyHashString = null; byte[] registrationRequest = CryptoHelper.CreateMessageWithPrependedSignatureAndPublicKey( snKey, ref pubKeyHashString); // // Save the message // File.WriteAllBytes(REQUEST_FILE_NAME, registrationRequest); Console.WriteLine( "Success: created registration request for publisher ID {0}", pubKeyHashString); } else if (0 == String.Compare(args[0], OPERATION_PROVIDETOKEN, true)) { // // Receive the publisher token request // byte[] publisherTokenRequest = File.ReadAllBytes(REQUEST_FILE_NAME); // // Check the signature // StringBuilder publisherPubKeyHashString = null; if (false == CryptoHelper.VerifyMessageWithPrependedSignatureAndPublicKey( publisherTokenRequest, ref publisherPubKeyHashString)) { return; } // // Read the location of the StrongNet Attestation Server // RegistryKey snReg = Registry.LocalMachine.OpenSubKey(SNKSP_REG_KEY, false); string snAsUri = (string)snReg.GetValue(SNSERVICEURI_REG_VALUE); // // Confirm with the StrongNet Attestation Server that this is // an attested key // var client = new RestClient(String.Format( "{0}/{1}", snAsUri, SNAPI_ROOT)); var request = new RestRequest("MbkAttestation", Method.GET); request.AddQueryParameter( "publicKeyHash", publisherPubKeyHashString.ToString()); var response = client.Execute(request); if (System.Net.HttpStatusCode.OK != response.StatusCode || ResponseStatus.Completed != response.ResponseStatus) { Console.WriteLine("Error: invalid publisher token request public key"); return; } // // Using Publisher Policy, acquire a shared access token, // simulating registration. This would happen on the server in // order to limit exposure of the Azure access key. // // http://blogs.msdn.com/b/servicebus/archive/2015/02/02/event-hub-publisher-policy-in-action.aspx // // Timespan can be long if the registration server checks every // publisher with the attestation server, the event processor checks a // signature on every message, publisher IDs can be revoked, and // you trust the storage of your policy key. // string token = SharedAccessSignatureTokenProvider.GetPublisherSharedAccessSignature( new Uri(SERVICE_BUS_URI), EVENT_HUB_NAME, publisherPubKeyHashString.ToString(), SENDER_POLICY_KEY_NAME, args[1], new TimeSpan(0, 30, 0)); // // Send the token back to the requestor // File.WriteAllText(TOKEN_FILE_NAME, token); Console.WriteLine( "Success: issued SAS policy '{0}' token to publisher ID {1}", SENDER_POLICY_KEY_NAME, publisherPubKeyHashString); } else if (0 == String.Compare(args[0], OPERATION_SENDDATA, true)) { // // Read back a previously acquired Azure Service Bus publisher token // string token = File.ReadAllText(TOKEN_FILE_NAME); // // Open the attested key // CngProvider cng = new CngProvider(SNKSP); CngKey snKey = CngKey.Open(ATTESTED_KEY_NAME, cng); // // Create a new signed message to simulate what will get posted // by each sender to the event hub. // StringBuilder pubKeyHashString = null; byte[] signedMessage = CryptoHelper.CreateMessageWithPrependedSignatureAndPublicKey( snKey, ref pubKeyHashString); // // Create a connection string for this policy and hub. Using // the hash of the public key as the publisher identity // allows correlation between security policy compliance and // sender data streams (but only if the processor verifies a // message signature and that the public key is known to the // attestation server). // string connStr = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessSignature( new Uri(SERVICE_BUS_URI), EVENT_HUB_NAME, pubKeyHashString.ToString(), token); // // Create a sender for this connection // EventHubSender sender = EventHubSender.CreateFromConnectionString(connStr); // // Send the signed message // sender.Send(new EventData(signedMessage)); Console.WriteLine("Success: message sent"); } else if (0 == String.Compare(args[0], OPERATION_LISTENDATA, true)) { // // Create a receiver for the indicated policy // string evtConnStr = ServiceBusConnectionStringBuilder.CreateUsingSharedAccessKey( new Uri(SERVICE_BUS_URI), LISTEN_POLICY_KEY_NAME, args[1]); string storageConnStr = string.Format( "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", args[2], args[3]); // // Use a variation of multi-threaded listener sample code from // Microsoft. This saves us from having to know which partition // the test message got queued to. // // http://azure.microsoft.com/en-us/documentation/articles/service-bus-event-hubs-csharp-ephcs-getstarted/ // var processorHost = new EventProcessorHost( Guid.NewGuid().ToString(), EVENT_HUB_NAME, EventHubConsumerGroup.DefaultGroupName, evtConnStr, storageConnStr); processorHost.RegisterEventProcessorAsync <SignatureCheckingEventProcessor>().Wait(); Console.WriteLine("Receiving. Press enter key to stop worker."); Console.ReadLine(); } else if (0 == String.Compare(args[0], OPERATION_REVOKEPUBLISHER, true)) { // // Create a namespace manager from a connection string acquired // from the Azure management portal // var nsm = Microsoft.ServiceBus.NamespaceManager.CreateFromConnectionString( args[1]); // // Revoke this publisher // nsm.RevokePublisher(EVENT_HUB_NAME, args[2]); // // List revoked publishers // var revokedPublishers = nsm.GetRevokedPublishers(EVENT_HUB_NAME); // // Restore this publisher // nsm.RestorePublisher(EVENT_HUB_NAME, args[2]); } else { Usage(); } }