Example #1
0
        public async Task<EventHubDescription> CreateEventHubAsync()
        {

            string serviceBusNamespace = "iotmc-ns";
            string serviceBusManageKey = "<< Add your SAS here >>";
            string eventHubName = "IoTMC";
            string eventHubSASKeyName = "Device01";

            Uri serviceBusUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty);
            TokenProvider tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", serviceBusManageKey);
            NamespaceManager nameSpaceManager = new NamespaceManager(string.Format("//{0}/", serviceBusUri.Host), tokenProvider);
            string eventHubKey = SharedAccessAuthorizationRule.GenerateRandomKey();

            EventHubDescription eventHubDescription = new EventHubDescription(eventHubName)
            {
                PartitionCount = 8,
                MessageRetentionInDays = 1
            };
            SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule(eventHubSASKeyName, eventHubKey, new[] { AccessRights.Send, AccessRights.Listen });
            eventHubDescription.Authorization.Add(eventHubSendRule);
            eventHubDescription = await nameSpaceManager.CreateEventHubIfNotExistsAsync(eventHubDescription);

            string eventHubSASKey = ((SharedAccessAuthorizationRule)eventHubDescription.Authorization.First()).PrimaryKey;

            return eventHubDescription;
        }
Example #2
0
        public void TestConsumerGroup()
        {
            string              name = "testConsumerGroupEventHub";
            string              consumerGroupName = "consumergroup1";
            NamespaceManager    ns          = NamespaceManager.CreateFromConnectionString(eventHubConnectionString);
            EventHubDescription description = ns.CreateEventHub(name);

            Assert.IsTrue(null != description);
            ConsumerGroupDescription cgDescription = ns.CreateConsumerGroup(name, consumerGroupName);

            if (!ns.ConsumerGroupExists(name, consumerGroupName, out cgDescription))
            {
                Assert.Fail("Consumer Group did not exist");
            }
            else
            {
                Assert.IsTrue(null != cgDescription);
                ns.DeleteConsumerGroup(name, consumerGroupName);
                if (ns.ConsumerGroupExists(name, consumerGroupName, out cgDescription))
                {
                    Assert.Fail("Consumer Group was not deleted");
                }

                ns.DeleteEventHub(name);
                if (ns.EventHubExists(name, out description))
                {
                    Assert.Fail("EventHub was not deleted");
                }
            }
        }
        public void getSasKey()
        {
            try
            {
                // Create namespace manager.
                Uri              uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, string.Empty);
                TokenProvider    td  = TokenProvider.CreateSharedAccessSignatureTokenProvider(namespaceManageKeyName, namespaceManageKey);
                NamespaceManager nm  = new NamespaceManager(uri, td);

                // Create event hub with a SAS rule that enables sending to that event hub
                EventHubDescription ed = new EventHubDescription(ehubname)
                {
                    PartitionCount = 32
                };
                string eventHubSendKeyName = "EventHubSendKey";
                string eventHubSendKey     = SharedAccessAuthorizationRule.GenerateRandomKey();
                SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule
                                                                     (eventHubSendKeyName, eventHubSendKey, new[] { AccessRights.Send });
                ed.Authorization.Add(eventHubSendRule);
                nm.CreateEventHub(ed);
                string resource = "insightsehub.servicebus.windows.net/" + ehubname;

                //Copy this SAS Key for use in configuring the VM Diagnostics
                string saskey = SharedAccessSignatureTokenProvider.GetSharedAccessSignature(eventHubSendKeyName,
                                                                                            eventHubSendKey, resource, TimeSpan.FromDays(365));
                Console.WriteLine("Event HUb Endpoint created");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception " + ex.StackTrace);
            }
        }
Example #4
0
        public async Task <string> OpenAsync(CancellationToken cancellationToken)
        {
            try
            {
                var nsm = NamespaceManager.CreateFromConnectionString(_ehConnString);
                EventHubDescription desc = new EventHubDescription(_ehPath);
                await nsm.CreateEventHubIfNotExistsAsync(desc);

                _client = new EventProcessorClient(new EventprocessorClientOptions
                {
                    Host              = Environment.MachineName + " " + Guid.NewGuid().ToString(),
                    ConnString        = _ehConnString,
                    HubPath           = _ehPath,
                    StorageConnString = _storageConnString,
                    OnMessageAction   = (message) =>
                    {
                        this._messageCallback?.Invoke(message);
                    },
                    OnError = (error) =>
                    {
                        this._loggerAction?.Invoke(error);
                    }
                });
                _client.Start();
                //return Task.FromResult($"EventHub at {this._ehPath}");
                return($"EventHub at {this._ehPath}");
            }
            catch (Exception e)
            {
                this._loggerAction?.Invoke(e);
                return($"Not listening on {this._ehPath}");
            }
        }
        public void Run(string connectionString, string hubName)
        {
            NamespaceManager    nsmgr = NamespaceManager.CreateFromConnectionString(connectionString);
            EventHubDescription desc  = nsmgr.GetEventHub(hubName);

            string consumerGroupName = _consumerGroupPrefix + DateTime.UtcNow.Ticks.ToString();
            ConsumerGroupDescription consumerGroupDesc = nsmgr.CreateConsumerGroupIfNotExists(new ConsumerGroupDescription(hubName, consumerGroupName));

            EventHubClient client = EventHubClient.CreateFromConnectionString(connectionString, hubName);

            int numPartitions = desc.PartitionCount;

            _receivers = new EventHubReceiver[numPartitions];
            //_receiversLastUpdate = new DateTime[numPartitions];
            //for (int i = 0; i < numPartitions; i++)
            //{
            //    _receiversLastUpdate[i] = DateTime.UtcNow;
            //}

            _tasks   = new Task[numPartitions];
            _buffers = new Dictionary <string, CircularBuffer <SensorDataContract> >();

            for (int iPart = 0; iPart < desc.PartitionCount; iPart++)
            {
                EventHubReceiver receiver = client.GetConsumerGroup(consumerGroupName).CreateReceiver(
                    desc.PartitionIds[iPart], DateTime.UtcNow - TimeSpan.FromMinutes(2));
                _receivers[iPart] = receiver;

                Task <IEnumerable <EventData> > task = receiver.ReceiveAsync(1000, TimeSpan.FromSeconds(1));

                int thisPart = iPart;
                task.ContinueWith(new Action <Task <IEnumerable <EventData> > >((t) => OnTaskComplete(t, thisPart)));
                _tasks[iPart] = task;
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            // Start a worker that consumes messages from the event hub.
            EventHubClient eventHubReceiveClient = EventHubClient.CreateFromConnectionString(GetAmqpConnectionString(), eventHubName);
            var            subscriberGroup       = eventHubReceiveClient.GetDefaultConsumerGroup();

            EventHubDescription eventHub = NamespaceManager.CreateFromConnectionString(GetAmqpConnectionString()).GetEventHub(eventHubName);

            // Register event processor with each shard to start consuming messages

            List <Worker> allWorkers = new List <Worker>();

            foreach (var partitionId in eventHub.PartitionIds)
            {
                Worker temp = new Worker(subscriberGroup, partitionId);
                allWorkers.Add(temp);
            }

            // Wait for the user to exit this application.
            Console.WriteLine("\nPress ENTER to exit...\n");
            Console.ReadLine();
            foreach (var w in allWorkers)
            {
                w.RequestStop();
            }
        }
Example #7
0
    static void Main(string[] args)
    {
        string           serviceBusNamespace = "Please Provide Your ServiceBus Namespace";
        string           serviceBusManageKey = "Please Provide Your ServiceBus Shared Access Key";
        Uri              serviceBusUri       = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty);
        TokenProvider    tokenProvider       = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", serviceBusManageKey);
        NamespaceManager nameSpaceManager    = new NamespaceManager(string.Format("//{0}/", serviceBusUri.Host), tokenProvider);

        string eventHubName    = "EventHubCreatedWithCode";
        string eventHubKeyName = "EventHubKey";
        string eventHubKey     = SharedAccessAuthorizationRule.GenerateRandomKey();

        EventHubDescription eventHubDescription = new EventHubDescription(eventHubName)
        {
            PartitionCount = 8, MessageRetentionInDays = 1
        };
        SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule(eventHubKeyName, eventHubKey, new[] { AccessRights.Send, AccessRights.Listen });

        eventHubDescription.Authorization.Add(eventHubSendRule);
        eventHubDescription = nameSpaceManager.CreateEventHubIfNotExists(eventHubDescription);
        string primaryKey = ((SharedAccessAuthorizationRule)eventHubDescription.Authorization.First()).PrimaryKey;

        Console.WriteLine("Primary Key: {0}", primaryKey);
        Console.ReadLine();
    }
Example #8
0
        public async Task <EventHubDescription> CreateEventHubAsync()
        {
            string serviceBusNamespace = "iotmc-ns";
            string serviceBusManageKey = "<< Add your SAS here >>";
            string eventHubName        = "IoTMC";
            string eventHubSASKeyName  = "Device01";

            Uri              serviceBusUri    = ServiceBusEnvironment.CreateServiceUri("sb", serviceBusNamespace, string.Empty);
            TokenProvider    tokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider("RootManageSharedAccessKey", serviceBusManageKey);
            NamespaceManager nameSpaceManager = new NamespaceManager(string.Format("//{0}/", serviceBusUri.Host), tokenProvider);
            string           eventHubKey      = SharedAccessAuthorizationRule.GenerateRandomKey();

            EventHubDescription eventHubDescription = new EventHubDescription(eventHubName)
            {
                PartitionCount         = 8,
                MessageRetentionInDays = 1
            };
            SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule(eventHubSASKeyName, eventHubKey, new[] { AccessRights.Send, AccessRights.Listen });

            eventHubDescription.Authorization.Add(eventHubSendRule);
            eventHubDescription = await nameSpaceManager.CreateEventHubIfNotExistsAsync(eventHubDescription);

            string eventHubSASKey = ((SharedAccessAuthorizationRule)eventHubDescription.Authorization.First()).PrimaryKey;

            return(eventHubDescription);
        }
Example #9
0
        private static void CreateEventHubWithOtherConfiguration()
        {
            try
            {
                string eventhubName = GetInput("Eventhub Name");
                EventHubDescription ehd = new EventHubDescription(eventhubName);
                ehd.PartitionCount = 32; //Number of partition must be between 8 & 32. Can't change once provisioned.

                //Create the EventHub if it doesn't exist
                if (!namespaceManager.EventHubExists(eventhubName))
                {
                    namespaceManager.CreateEventHub(ehd);
                    Write("Eventhub created : " + eventhubName);
                }
                else
                {
                    Write("Eventhub already exists : " + eventhubName);
                }
                Write("Done");
            }
            catch (Exception ex)
            {
                Write(ex.Message);
            }
        }
        private async Task <string[]> GetPartitionIdsAsync()
        {
            NamespaceManager    namespaceManager = NamespaceManager.CreateFromConnectionString(hubSettings.ConnectionString);
            EventHubDescription hubDescription   = await namespaceManager.GetEventHubAsync(hubSettings.Path);

            return(hubDescription.PartitionIds);
        }
Example #11
0
        //this can not be done using code
        private static void CreateEventHubKeys()
        {
            const string eventHubName = "MyEventHub";
            NamespaceManager nsManager = NamespaceManager.CreateFromConnectionString(
                "Endpoint=sb://johnsonwangnz2.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=/wtH2nivH3W7ZKk3rSSwiid2zi98J+NYcMu52QGUqdM=");

            EventHubDescription eh = new EventHubDescription(eventHubName);

            if (nsManager.EventHubExists(eventHubName))
            {
                Console.WriteLine("{0} EventHub already exists, deleting it...", eventHubName);
                // delete it
                nsManager.DeleteEventHub(eventHubName);

            }

            var sendKeyMyEventHub = SharedAccessAuthorizationRule.GenerateRandomKey();
            var sendKeyNameMyEventHub = "SendAccessKeyMyEventHub";
            var listenKeyMyEventHub = SharedAccessAuthorizationRule.GenerateRandomKey();
            var listenKeyNameMyEventHub = "ListenAccessKeyMyEventHub";

            eh.Authorization.Add(new SharedAccessAuthorizationRule(listenKeyNameMyEventHub, listenKeyMyEventHub,
                    new List<AccessRights> { AccessRights.Listen }));
            eh.Authorization.Add(new SharedAccessAuthorizationRule(sendKeyNameMyEventHub, sendKeyMyEventHub,
                    new List<AccessRights> { AccessRights.Send }));

            try
            {

                //create EventHub

                nsManager.CreateEventHub(eh);

            }
            catch (AggregateException aex)
            {
                Console.WriteLine(aex.InnerException);
            }
            catch (MessagingException ex)
            {
                Console.WriteLine(ex);
            }

            using (StreamWriter file =
            new StreamWriter(@"MyEventHubKeys.txt", true))
            {
                file.WriteLine("EventHub Path:" + eh.Path);
                file.WriteLine("Listen Key Name:" + listenKeyNameMyEventHub);
                file.WriteLine("Listen Key:" + listenKeyMyEventHub);
                file.WriteLine("Send Key Name:" + sendKeyNameMyEventHub);
                file.WriteLine("Send Key:" + sendKeyMyEventHub);

            }

            Console.WriteLine("Listen access rule created with key '{0}' and name {2} on entity '{1}'", listenKeyMyEventHub, eh.Path, listenKeyNameMyEventHub);
            Console.WriteLine("Send access rule created with key '{0}' and name {2} on entity '{1}'", sendKeyMyEventHub, eh.Path, sendKeyNameMyEventHub);

            Console.ReadKey();
        }
 public HandleEventHubControl(WriteToLogDelegate writeToLog, ServiceBusHelper serviceBusHelper, EventHubDescription eventHubDescription)
 {
     this.writeToLog          = writeToLog;
     this.serviceBusHelper    = serviceBusHelper;
     this.eventHubDescription = eventHubDescription;
     InitializeComponent();
     InitializeControls();
 }
        /// <summary>
        /// Run Async
        /// </summary>
        /// <returns>Task</returns>
        public override async Task RunAsync()
        {
            var description = new EventHubDescription(name)
            {
                PartitionCount = this.partitionCount,
            };

            await this.manager.CreateEventHubIfNotExistsAsync(description);
        }
Example #14
0
        /// <summary>
        /// Create If Not Exists
        /// </summary>
        /// <returns>Created</returns>
        public virtual async Task <bool> CreateIfNotExists()
        {
            var description = new EventHubDescription(name)
            {
                PartitionCount = this.partitionCount,
            };

            var d = await this.manager.CreateEventHubIfNotExistsAsync(description);

            return(d.Status == EntityStatus.Creating);
        }
        public static string EventHubDescriptionAsString(EventHubDescription ehd)
        {
            var sb = new StringBuilder();

            sb.AppendLine("Path: ".PadRight(30) + ehd.Path);
            sb.AppendLine("PartitionCount: ".PadRight(30) + ehd.PartitionCount);
            sb.AppendLine("MessageRetentionInDays: ".PadRight(30) + ehd.MessageRetentionInDays);
            sb.AppendLine("Status: ".PadRight(30) + ehd.Status);
            sb.AppendLine("CreatedAt: ".PadRight(30) + ehd.CreatedAt);
            return(sb.ToString());
        }
Example #16
0
 public void RefreshData(EventHubDescription eventHub)
 {
     try
     {
         eventHubDescription = eventHub;
         InitializeData();
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
 }
Example #17
0
        /// <summary>
        /// Creates an event hub in given service bus namespace
        /// </summary>
        /// <param name="eventHubConnectionString">Connection string to access the service bus namespace</param>
        /// <param name="eventHubName">Name of event hub to be created</param>
        /// <param name="partitionCount">Number of partitions in event hub</param>
        public static void CreateEventHubIfNotExists(string eventHubConnectionString, string eventHubName, int partitionCount = 0)
        {
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(eventHubConnectionString);
            var eventHubDescription           = new EventHubDescription(eventHubName);

            if (partitionCount > 0)
            {
                eventHubDescription.PartitionCount = partitionCount;
            }

            RetryPolicy.ExecuteAsync(() => namespaceManager.CreateEventHubIfNotExistsAsync(eventHubDescription)).Wait();
        }
Example #18
0
        static void Main(string[] args)
        {
            var namespaceManager = NamespaceManager.CreateFromConnectionString(ServiceBusConnectionString);
            var hubs             = namespaceManager.GetEventHubs();


            var ehd = new EventHubDescription(EventHubName);


            _eventHubClient = EventHubClient.CreateFromConnectionString(ServiceBusConnectionString, EventHubName);
            //MessageSender();
        }
        public ContainerForm(ServiceBusHelper serviceBusHelper, MainForm mainForm, EventHubDescription eventHubDescription, PartitionDescription partitionDescription = null)
        {
            try
            {
                InitializeComponent();
                Task.Factory.StartNew(AsyncWriteToLog).ContinueWith(t =>
                {
                    if (t.IsFaulted && t.Exception != null)
                    {
                        WriteToLog(t.Exception.Message);
                    }
                });
                this.mainForm        = mainForm;
                mainSplitterDistance = mainSplitContainer.SplitterDistance;
                SuspendLayout();
                panelMain.SuspendDrawing();
                panelMain.Controls.Clear();
                panelMain.BackColor = SystemColors.GradientInactiveCaption;

                testEventHubControl = new TestEventHubControl(mainForm, WriteToLog, StopLog, StartLog, new ServiceBusHelper(WriteToLog, serviceBusHelper), eventHubDescription, partitionDescription)
                {
                    Location = new Point(1, panelMain.HeaderHeight + 1),
                    Size     = new Size(panelMain.Size.Width - 3, panelMain.Size.Height - 26),
                    Anchor   = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                };

                Text = partitionDescription == null
                    ? string.Format(SendEventsToEventHubFormat, eventHubDescription.Path)
                    : string.Format(SendEventsToEventHubPartitionFormat,
                                    partitionDescription.PartitionId,
                                    eventHubDescription.Path);

                testEventHubControl.btnCancel.Text   = CloseLabel;
                testEventHubControl.btnCancel.Click -= testEventHubControl.btnCancel_Click;
                testEventHubControl.btnCancel.Click += BtnCancelOnClick;
                testEventHubControl.Focus();

                panelMain.HeaderText = partitionDescription == null?
                                       string.Format(HeaderTextTestEventHubFormat, eventHubDescription.Path) :
                                           string.Format(HeaderTextTestEventHubPartitionFormat,
                                                         partitionDescription.PartitionId,
                                                         eventHubDescription.Path);

                panelMain.Controls.Add(testEventHubControl);
                SetStyle(ControlStyles.ResizeRedraw, true);
            }
            finally
            {
                panelMain.ResumeDrawing();
                ResumeLayout();
            }
        }
Example #20
0
        /// <summary>
        /// Get partition Ids from eventhub
        /// </summary>
        /// <returns></returns>
        protected virtual async Task <string[]> GetPartitionIdsAsync()
        {
#if NETSTANDARD
            EventHubRuntimeInformation runtimeInfo = await client.GetRuntimeInformationAsync();

            return(runtimeInfo.PartitionIds);
#else
            NamespaceManager    namespaceManager = NamespaceManager.CreateFromConnectionString(hubSettings.ConnectionString);
            EventHubDescription hubDescription   = await namespaceManager.GetEventHubAsync(hubSettings.Path);

            return(hubDescription.PartitionIds);
#endif
        }
Example #21
0
        static void Main(string[] args)
        {
            SBAdmin sbAdmin = new SBAdmin();

            Task <EventHubDescription> eventHubCreation = sbAdmin.CreateEventHubAsync();

            eventHubCreation.Wait();
            EventHubDescription eventHubDescription = eventHubCreation.Result;

            Console.WriteLine(eventHubDescription.Path);

            Console.ReadLine();
        }
Example #22
0
 public static void CreateEventHubIfNotExists(string eventHubName, int numberOfPartitions, NamespaceManager manager)
 {
     try
     {
         // Create the Event Hub
         Trace.WriteLine("Creating Event Hub...");
         EventHubDescription ehd = new EventHubDescription(eventHubName);
         ehd.PartitionCount = numberOfPartitions;
         manager.CreateEventHubIfNotExistsAsync(ehd).Wait();
     }
     catch (AggregateException agexp)
     {
         Trace.WriteLine(agexp.Flatten());
     }
 }
Example #23
0
 public static void CreateEventHub(string eventHubName, int numberOfPartitions, NamespaceManager manager)
 {
     try
     {
         // Create the Event Hub
         Console.WriteLine("Creating Event Hub...");
         EventHubDescription ehd = new EventHubDescription(eventHubName);
         ehd.PartitionCount = numberOfPartitions;
         manager.CreateEventHubIfNotExistsAsync(ehd).Wait();
     }
     catch (AggregateException agexp)
     {
         Console.WriteLine(agexp.Flatten());
     }
 }
Example #24
0
        public void TestParition()
        {
            string              name = "testpartitionEventHub";
            string              consumerGroupName = "consumergroup1";
            NamespaceManager    ns          = NamespaceManager.CreateFromConnectionString(eventHubConnectionString);
            EventHubDescription description = ns.CreateEventHub(name);

            Assert.IsTrue(null != description);
            ConsumerGroupDescription cgDescription = ns.CreateConsumerGroup(name, consumerGroupName);
            PartitionDescription     pd            = ns.GetEventHubPartition(name, consumerGroupName, "1");

            Assert.IsTrue(null != pd);

            ns.DeleteEventHub(name);
        }
        public async Task Send(ServiceMessage message)
        {
            var nsm = NamespaceManager.CreateFromConnectionString(_connString);

            EventHubDescription desc = new EventHubDescription(_path);
            await nsm.CreateEventHubIfNotExistsAsync(desc);

            var client = EventHubClient.CreateFromConnectionString(_connString, desc.Path);

            client.RetryPolicy = new RetryExponential(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), 5);

            var json  = JsonConvert.SerializeObject(message);
            var bytes = Encoding.UTF8.GetBytes(json);

            await client.SendAsync(new EventData(bytes));
        }
 public static void CreateEventHubAndConsumerGroup()
 {
     try
     {
         NamespaceManager manager = NamespaceManager.CreateFromConnectionString(GetServiceBusConnectionString());
         // Create the Event Hub
         Console.WriteLine("Creating Event Hub...");
         EventHubDescription ehd = new EventHubDescription(eventHubName);
         //ehd.PartitionCount = numberOfPartitions;
         manager.CreateEventHubIfNotExistsAsync(ehd.Path).Wait();
         manager.CreateConsumerGroupIfNotExistsAsync(ehd.Path, consumerGroupName).Wait();
     }
     catch (AggregateException agexp)
     {
         Console.WriteLine(agexp.Flatten());
     }
 }
        private static AMQPConfig PrepareAMQPConfig(string connectionString, string hubName,
                                                    string messageSubject, string messageDeviceId, string messageDeviceDisplayName)
        {
            try
            {
                NamespaceManager    nsmgr = NamespaceManager.CreateFromConnectionString(connectionString);
                EventHubDescription desc  = nsmgr.GetEventHub(hubName);

                foreach (var rule in desc.Authorization)
                {
                    var accessAuthorizationRule = rule as SharedAccessAuthorizationRule;
                    if (accessAuthorizationRule == null)
                    {
                        continue;
                    }
                    if (!accessAuthorizationRule.Rights.Contains(AccessRights.Send))
                    {
                        continue;
                    }

                    string amqpAddress = string.Format("amqps://{0}:{1}@{2}",
                                                       accessAuthorizationRule.KeyName,
                                                       Uri.EscapeDataString(accessAuthorizationRule.PrimaryKey), nsmgr.Address.Host);

                    AMQPConfig amqpConfig = new AMQPConfig
                    {
                        AMQPSAddress = amqpAddress,
                        EventHubName = hubName,
                        EventHubDeviceDisplayName =
                            string.IsNullOrEmpty(messageSubject) ? "SensorGatewayService" : messageSubject,
                        EventHubDeviceId =
                            string.IsNullOrEmpty(messageDeviceId)
                                ? "a94cd58f-4698-4d6a-b9b5-4e3e0f794618"
                                : messageDeviceId,
                        EventHubMessageSubject =
                            string.IsNullOrEmpty(messageDeviceDisplayName) ? "gtsv" : messageDeviceDisplayName
                    };
                    return(amqpConfig);
                }
            }
            catch (Exception)
            {
            }
            return(null);
        }
Example #28
0
        public static async Task <EventHubDescription> UpdateEventHub(string eventHubName, NamespaceManager namespaceManager)
        {
            // Add a consumer group
            EventHubDescription ehd = await namespaceManager.GetEventHubAsync(eventHubName);

            await namespaceManager.CreateConsumerGroupIfNotExistsAsync(ehd.Path, "consumerGroupName");

            // Create a customer SAS rule with Manage permissions
            ehd.UserMetadata = "Some updated info";
            string ruleName = "myeventhubmanagerule";
            string ruleKey  = SharedAccessAuthorizationRule.GenerateRandomKey();

            ehd.Authorization.Add(new SharedAccessAuthorizationRule(ruleName, ruleKey, new AccessRights[] { AccessRights.Manage, AccessRights.Listen, AccessRights.Send }));

            EventHubDescription ehdUpdated = await namespaceManager.UpdateEventHubAsync(ehd);

            return(ehd);
        }
Example #29
0
        /// <summary>
        /// Checks if a event hub by the provided <paramref name="hubName"/> exists and
        /// Checks if a consumer group by the provided <paramref name="consumerGroupNames"/> exists.
        /// </summary>
        protected virtual void CheckHubExists(NamespaceManager namespaceManager, string hubName, string consumerGroupNames)
        {
            // Configure Queue Settings
            var eventHubDescription = new EventHubDescription(hubName)
            {
                MessageRetentionInDays = long.MaxValue,
            };

            // Create the topic if it does not exist already
            namespaceManager.CreateEventHubIfNotExists(eventHubDescription);

            var subscriptionDescription = new SubscriptionDescription(eventHubDescription.Path, consumerGroupNames);

            if (!namespaceManager.SubscriptionExists(eventHubDescription.Path, consumerGroupNames))
            {
                namespaceManager.CreateSubscription(subscriptionDescription);
            }
        }
        public void Run(string connectionString, string hubName, string measureNameFilter)
        {
            NamespaceManager nsmgr = NamespaceManager.CreateFromConnectionString(connectionString);

            EventHubDescription desc = nsmgr.GetEventHub(hubName);

            //we use already defined consumerGroup name to not reach limit on CG count
            string consumerGroupName = _consumerGroupPrefix;
            ConsumerGroupDescription consumerGroupDesc = nsmgr.CreateConsumerGroupIfNotExists(new ConsumerGroupDescription(hubName, consumerGroupName));

            EventHubClient client = EventHubClient.CreateFromConnectionString(connectionString, hubName);

            int numPartitions = desc.PartitionCount;

            _receivers = new EventHubReceiver[numPartitions];

            _tasks = new Task[numPartitions];

            for (int iPart = 0; iPart < desc.PartitionCount; iPart++)
            {
                EventHubReceiver receiver = client.GetConsumerGroup(consumerGroupName).CreateReceiver(
                    desc.PartitionIds[iPart], DateTime.UtcNow - TimeSpan.FromMinutes(2));
                _receivers[iPart] = receiver;

                int part = iPart;
                Task.Factory.StartNew((state) =>
                {
                    try
                    {
                        while (true)
                        {
                            var messages = _receivers[part].Receive(1000, TimeSpan.FromSeconds(1));
                            Process(messages);
                        }
                    }
                    catch (Exception ex)
                    {
                        //FailureEvent.Set();
                        Trace.TraceError("Ignored invalid event data: {0}");
                    }
                }, iPart);
            }
        }
Example #31
0
        public string GetCreateEHAndConsumerGroup(string ConsumenrGroup, ref string eventHubName, ref string eventHubConnectionString, ref string storageConnectionString)
        {
            try
            {
                //Set connection strings
                eventHubConnectionString = "Endpoint=sb://[NAMESPACE].servicebus.windows.net/;SharedAccessKeyName=All;SharedAccessKey=[SharedAccessKey]";
                string eventHubConnectionStringAdmin = "Endpoint=sb://[NAMESPACE].servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[SharedAccessKey]";

                eventHubName = "[EVENTHUBNAME]";
                string storageAccountName = "[STORAGEACCOUNTNAME]";
                string storageAccountKey  = "[STORAGEACCOUNTKEY]";
                storageConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                                                        storageAccountName, storageAccountKey);
                //Create connection string
                var builder = new ServiceBusConnectionStringBuilder(eventHubConnectionString)
                {
                    TransportType = Microsoft.ServiceBus.Messaging.TransportType.Amqp
                };

                ConsoleWriteLine("Create/Open the EH", ConsoleColor.Magenta);
                NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(eventHubConnectionStringAdmin);
                var evenhubDesc = new EventHubDescription(eventHubName);
                namespaceManager.CreateEventHubIfNotExists(evenhubDesc);

                if (ConsumenrGroup == null)
                {
                    var client = EventHubClient.CreateFromConnectionString(builder.ToString(), eventHubName);
                    EventHubConsumerGroup eventHubConsumerGroup = client.GetDefaultConsumerGroup();
                    return(eventHubConsumerGroup.GroupName);
                }
                else
                {
                    namespaceManager.CreateConsumerGroupIfNotExists(eventHubName, ConsumenrGroup);
                    return(ConsumenrGroup);
                }
            }
            catch (Exception ex)
            {
                ConsoleWriteLine("ERROR-" + ex.Message, ConsoleColor.Red);
                return(null);
            }
        }
        static void Main(string[] args)
        {
            NamespaceManager namespaceManager      = NamespaceManager.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"]);
            EventHubClient   eventHubReceiveClient = EventHubClient.CreateFromConnectionString(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"], EventHubName);
            var consumerGroup            = eventHubReceiveClient.GetDefaultConsumerGroup();
            EventHubDescription eventHub = namespaceManager.GetEventHub(EventHubName);

            // Register event processor with each shard to start consuming messages
            foreach (var partitionId in eventHub.PartitionIds)
            {
                consumerGroup.RegisterProcessor <CustomEventProcessor>(new Lease()
                {
                    PartitionId = partitionId
                }, new CustomCheckpointManager());
            }

            // Wait for the user to exit this application.
            Console.WriteLine("\nPress ENTER to exit...\n");
            Console.ReadLine();
        }
Example #33
0
        // Please set the following connection strings in app.config for this WebJob to run:
        // AzureWebJobsDashboard and AzureWebJobsStorage
        static void Main()
        {
            string eventHubName  = ConfigurationManager.AppSettings["EventHubName"];
            string consumerGroup = ConfigurationManager.AppSettings["ConsumerGroup"];

            string              connectionString = GetServiceBusConnectionString();
            NamespaceManager    namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
            EventHubDescription ehd = namespaceManager.GetEventHub(eventHubName);

            namespaceManager.CreateConsumerGroupIfNotExists(ehd.Path, consumerGroup);

            var receiver = new Receiver(eventHubName, consumerGroup, connectionString);

            receiver.MessageProcessingWithPartitionDistribution();

            // The following code ensures that the WebJob will be running continuously
            var host = new JobHost();

            host.RunAndBlock();
        }
 private void ReadConfiguration()
 {
     try
     {
         txtNamespace.Text = ConfigurationManager.AppSettings[NamespaceParameter];
         txtKeyName.Text   = ConfigurationManager.AppSettings[KeyNameParameter];
         txtKeyValue.Text  = ConfigurationManager.AppSettings[KeyValueParameter];
         txtEventHub.Text  = ConfigurationManager.AppSettings[EventHubParameter] ?? DefaultEventHubName;
         var eventHubDescription = new EventHubDescription(txtEventHub.Text);
         int value;
         var setting = ConfigurationManager.AppSettings[PartitionCountParameter];
         txtPartitionCount.Text = int.TryParse(setting, out value) ?
                                  value.ToString(CultureInfo.InvariantCulture) :
                                  eventHubDescription.PartitionCount.ToString(CultureInfo.InvariantCulture);
         setting = ConfigurationManager.AppSettings[RetentionDaysParameter];
         txtMessageRetentionInDays.Text = int.TryParse(setting, out value) ?
                                          value.ToString(CultureInfo.InvariantCulture) :
                                          eventHubDescription.MessageRetentionInDays.ToString(CultureInfo.InvariantCulture);
         txtStatus.Text      = ConfigurationManager.AppSettings[StatusParameter];
         setting             = ConfigurationManager.AppSettings[DeviceCountParameter];
         txtDeviceCount.Text = int.TryParse(setting, out value) ?
                               value.ToString(CultureInfo.InvariantCulture) :
                               DefaultDeviceNumber.ToString(CultureInfo.InvariantCulture);
         setting = ConfigurationManager.AppSettings[EventIntervalParameter];
         txtEventIntervalInMilliseconds.Text = int.TryParse(setting, out value) ?
                                               value.ToString(CultureInfo.InvariantCulture) :
                                               DefaultEventIntervalInMilliseconds.ToString(CultureInfo.InvariantCulture);
         setting          = ConfigurationManager.AppSettings[MinValueParameter];
         txtMinValue.Text = int.TryParse(setting, out value) ?
                            value.ToString(CultureInfo.InvariantCulture) :
                            DefaultMinValue.ToString(CultureInfo.InvariantCulture);
         setting          = ConfigurationManager.AppSettings[MaxValueParameter];
         txtMaxValue.Text = int.TryParse(setting, out value) ?
                            value.ToString(CultureInfo.InvariantCulture) :
                            DefaultMaxValue.ToString(CultureInfo.InvariantCulture);
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
 }
Example #35
0
        private void CreateStreamAnalyticsJobs(AzurePrepInputs azurePrepIn, AzurePrepOutputs azurePrepOut)
        {
            string resourceGroupName = SelectResourceGroup(azurePrepIn);

            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly( ).Location);

            path += "\\..\\..\\..\\..\\StreamAnalyticsQueries";
            foreach (string filename in Directory.GetFiles(path))
            {
                string extension = Path.GetExtension(filename);
                if (extension != null && extension.Contains("sql"))
                {
                    string nameWithoutExtension  = Path.GetFileNameWithoutExtension(filename);
                    EventHubDescription ehOutput = (filename.ToLower( ).Contains("aggregates") || azurePrepOut.ehAlerts == null)
                        ? azurePrepOut.ehDevices
                        : azurePrepOut.ehAlerts;

                    if (ehOutput == null)
                    {
                        _ConsoleBuffer.Add(string.Format(" Skip creating {0} Stream Analytics job because there is no output Event Hub...", nameWithoutExtension));
                        continue;
                    }

                    string queryFilename = filename;
                    ConsoleHelper.AskAndPerformAction(
                        "Do you want to create " + nameWithoutExtension + " job?",
                        "Are you sure you want to create " + nameWithoutExtension + " job?",
                        "Are you sure you do not want to create " + nameWithoutExtension + " job?",
                        () =>
                    {
                        string query = File.ReadAllText(queryFilename);

                        _ConsoleBuffer.Add(string.Format("Creating {0} Stream Analytics job...", nameWithoutExtension));

                        CreateStreamAnalyticsJob(nameWithoutExtension, query, resourceGroupName,
                                                 azurePrepIn, azurePrepOut.ehDevices, ehOutput);
                    },
                        _ConsoleBuffer);
                }
            }
        }
Example #36
0
        public async Task<EventHubDescription> CreateEventHubByConnectionStringAsync()
        {
            string eventHubName = "IoTMC";
            string eventHubSASKeyName = "Device01";
            string serviceBusConnectionString = "Endpoint=sb://iotmc-ns.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<<Add your SAS here>>"; 

            NamespaceManager nameSpaceManager = NamespaceManager.CreateFromConnectionString(serviceBusConnectionString);
            string eventHubKey = SharedAccessAuthorizationRule.GenerateRandomKey();
            EventHubDescription eventHubDescription = new EventHubDescription(eventHubName)
            {
                PartitionCount = 8,
                MessageRetentionInDays = 1
            };
            SharedAccessAuthorizationRule eventHubSendRule = new SharedAccessAuthorizationRule(eventHubSASKeyName, eventHubKey, 
                new[] { AccessRights.Send, AccessRights.Listen });
            eventHubDescription.Authorization.Add(eventHubSendRule);
            eventHubDescription = await nameSpaceManager.CreateEventHubIfNotExistsAsync(eventHubDescription);

            string eventHubSASKey = ((SharedAccessAuthorizationRule)eventHubDescription.Authorization.First()).PrimaryKey;

            return eventHubDescription; 
        }
        private void InitializeControls()
        {

            // Set Grid style
            authorizationRulesDataGridView.EnableHeadersVisualStyles = false;

            // Set the selection background color for all the cells.
            authorizationRulesDataGridView.DefaultCellStyle.SelectionBackColor = Color.FromArgb(92, 125, 150);
            authorizationRulesDataGridView.DefaultCellStyle.SelectionForeColor = SystemColors.Window;

            // Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default 
            // value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
            authorizationRulesDataGridView.RowHeadersDefaultCellStyle.SelectionBackColor = Color.FromArgb(153, 180, 209);

            // Set the background color for all rows and for alternating rows.  
            // The value for alternating rows overrides the value for all rows. 
            authorizationRulesDataGridView.RowsDefaultCellStyle.BackColor = SystemColors.Window;
            authorizationRulesDataGridView.RowsDefaultCellStyle.ForeColor = SystemColors.ControlText;
            //authorizationRulesDataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.White;
            //authorizationRulesDataGridView.AlternatingRowsDefaultCellStyle.ForeColor = SystemColors.ControlText;

            // Set the row and column header styles.
            authorizationRulesDataGridView.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(215, 228, 242);
            authorizationRulesDataGridView.RowHeadersDefaultCellStyle.ForeColor = SystemColors.ControlText;
            authorizationRulesDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(215, 228, 242);
            authorizationRulesDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = SystemColors.ControlText;

            authorizationRulesDataGridView.AutoGenerateColumns = false;
            if (authorizationRulesDataGridView.Columns.Count == 0)
            {
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "IssuerName", DataPropertyName = "IssuerName" });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewComboBoxColumn { Name = "ClaimType", DataPropertyName = "ClaimType", DataSource = claimTypes, FlatStyle = FlatStyle.Flat });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "ClaimValue", DataPropertyName = "ClaimValue" });
                if (serviceBusHelper.IsCloudNamespace)
                {
                    authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "KeyName", DataPropertyName = "KeyName" });
                    authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "PrimaryKey", DataPropertyName = "PrimaryKey" });
                    authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "SecondaryKey", DataPropertyName = "SecondaryKey" });
                }
                authorizationRulesDataGridView.Columns.Add(new DataGridViewCheckBoxColumn { Name = "Manage", DataPropertyName = "Manage", Width = 50 });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewCheckBoxColumn { Name = "Send", DataPropertyName = "Send", Width = 50 });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewCheckBoxColumn { Name = "Listen", DataPropertyName = "Listen", Width = 50 });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "Revision", DataPropertyName = "Revision", Width = 50, ReadOnly = true });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "CreatedTime", DataPropertyName = "CreatedTime", ReadOnly = true });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "ModifiedTime", DataPropertyName = "ModifiedTime", ReadOnly = true });
            }

            // Set Grid style
            dataPointDataGridView.EnableHeadersVisualStyles = false;

            // Set the selection background color for all the cells.
            dataPointDataGridView.DefaultCellStyle.SelectionBackColor = Color.FromArgb(92, 125, 150);
            dataPointDataGridView.DefaultCellStyle.SelectionForeColor = SystemColors.Window;

            // Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default 
            // value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
            dataPointDataGridView.RowHeadersDefaultCellStyle.SelectionBackColor = Color.FromArgb(153, 180, 209);

            // Set the background color for all rows and for alternating rows.  
            // The value for alternating rows overrides the value for all rows. 
            dataPointDataGridView.RowsDefaultCellStyle.BackColor = SystemColors.Window;
            dataPointDataGridView.RowsDefaultCellStyle.ForeColor = SystemColors.ControlText;
            //filtersDataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.White;
            //filtersDataGridView.AlternatingRowsDefaultCellStyle.ForeColor = SystemColors.ControlText;

            // Set the row and column header styles.
            dataPointDataGridView.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(215, 228, 242);
            dataPointDataGridView.RowHeadersDefaultCellStyle.ForeColor = SystemColors.ControlText;
            dataPointDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(215, 228, 242);
            dataPointDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = SystemColors.ControlText;

            // Initialize the DataGridView.
            dataPointBindingSource.DataSource = dataPointBindingList;
            dataPointDataGridView.AutoGenerateColumns = false;
            dataPointDataGridView.AutoSize = true;
            dataPointDataGridView.DataSource = dataPointBindingSource;
            dataPointDataGridView.ForeColor = SystemColors.WindowText;

            if (eventHubDescription != null)
            {
                MetricInfo.GetMetricInfoListAsync(serviceBusHelper.Namespace, EventHubEntity, eventHubDescription.Path).ContinueWith(t => metricsManualResetEvent.Set());
            }

            if (dataPointDataGridView.Columns.Count == 0)
            {
                // Create the Metric column
                var metricColumn = new DataGridViewComboBoxColumn
                {
                    DataSource = MetricInfo.EntityMetricDictionary.ContainsKey(EventHubEntity) ?
                                 MetricInfo.EntityMetricDictionary[EventHubEntity] :
                                 null,
                    DataPropertyName = MetricProperty,
                    DisplayMember = DisplayNameProperty,
                    ValueMember = NameProperty,
                    Name = MetricProperty,
                    Width = 144,
                    DropDownWidth = 250,
                    FlatStyle = FlatStyle.Flat,
                    DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton
                };
                dataPointDataGridView.Columns.Add(metricColumn);

                // Create the Time Granularity column
                var timeGranularityColumn = new DataGridViewComboBoxColumn
                {
                    DataSource = timeGranularityList,
                    DataPropertyName = GranularityProperty,
                    Name = GranularityProperty,
                    Width = 72,
                    FlatStyle = FlatStyle.Flat
                };
                dataPointDataGridView.Columns.Add(timeGranularityColumn);

                // Create the Time Operator 1 column
                var operator1Column = new DataGridViewComboBoxColumn
                {
                    DataSource = operators,
                    DataPropertyName = TimeFilterOperator1Name,
                    HeaderText = TimeFilterOperator,
                    Name = TimeFilterOperator1Name,
                    Width = 72,
                    FlatStyle = FlatStyle.Flat
                };
                dataPointDataGridView.Columns.Add(operator1Column);

                // Create the Time Value 1 column
                var value1Column = new DataGridViewDateTimePickerColumn
                {
                    DataPropertyName = TimeFilterValue1Name,
                    HeaderText = TimeFilterValue,
                    Name = TimeFilterValue1Name,
                    Width = 136
                };
                dataPointDataGridView.Columns.Add(value1Column);

                // Create the Time Operator 1 column
                var operator2Column = new DataGridViewComboBoxColumn
                {
                    DataSource = operators,
                    DataPropertyName = TimeFilterOperator2Name,
                    HeaderText = TimeFilterOperator,
                    Name = TimeFilterOperator2Name,
                    Width = 72,
                    FlatStyle = FlatStyle.Flat
                };
                dataPointDataGridView.Columns.Add(operator2Column);

                // Create the Time Value 1 column
                var value2Column = new DataGridViewDateTimePickerColumn
                {
                    DataPropertyName = TimeFilterValue2Name,
                    HeaderText = TimeFilterValue,
                    Name = TimeFilterValue2Name,
                    Width = 136
                };
                dataPointDataGridView.Columns.Add(value2Column);

                // Create delete column
                var deleteButtonColumn = new DataGridViewButtonColumn
                {
                    Name = DeleteName,
                    CellTemplate = new DataGridViewDeleteButtonCell(),
                    HeaderText = string.Empty,
                    Width = 22
                };
                deleteButtonColumn.CellTemplate.ToolTipText = DeleteTooltip;
                deleteButtonColumn.UseColumnTextForButtonValue = true;
                dataPointDataGridView.Columns.Add(deleteButtonColumn);
            }

            if (eventHubDescription != null)
            {
                // Tab pages
                if (serviceBusHelper.IsCloudNamespace)
                {
                    EnablePage(MetricsTabPage);
                }
                else
                {
                    DisablePage(MetricsTabPage);
                }

                // Initialize buttons
                btnCreateDelete.Text = DeleteText;
                btnCancelUpdate.Text = UpdateText;
                btnChangeStatus.Text = eventHubDescription.Status == EntityStatus.Active ? DisableText : EnableText;
                btnRefresh.Visible = true;
                btnMetrics.Visible = true;
                btnCloseTabs.Visible = true;
                btnChangeStatus.Visible = true;
                
                // Initialize textboxes
                txtPath.ReadOnly = true;
                txtPath.BackColor = SystemColors.Window;
                txtPath.GotFocus += textBox_GotFocus;

                // TrackBar
                trackBarPartitionCount.Enabled = false;

                // Initialize Data
                InitializeData();

                toolTip.SetToolTip(txtPath, PathTooltip);
                toolTip.SetToolTip(txtUserMetadata, UserMetadataTooltip);
                toolTip.SetToolTip(txtMessageRetentionInDays, MessageRetentionInDaysTooltip);
                toolTip.SetToolTip(trackBarPartitionCount, PartitionCountTooltip);

                propertyListView.ContextMenuStrip = entityInformationContextMenuStrip;
            }
            else
            {
                // Tab pages
                DisablePage(MetricsTabPage);

                // Set Defaults
                var eventHub = new EventHubDescription("DUMMY");
                txtMessageRetentionInDays.Text = eventHub.MessageRetentionInDays.ToString(CultureInfo.InvariantCulture);
                trackBarPartitionCount.Value = eventHub.PartitionCount;

                // Initialize buttons
                btnCreateDelete.Text = CreateText;
                btnCancelUpdate.Text = CancelText;
                btnRefresh.Visible = false;
                btnChangeStatus.Visible = false;
                btnMetrics.Visible = false;
                btnCloseTabs.Visible = false;

                // Create BindingList for Authorization Rules
                var bindingList = new BindingList<AuthorizationRuleWrapper>(new List<AuthorizationRuleWrapper>())
                {
                    AllowEdit = true,
                    AllowNew = true,
                    AllowRemove = true
                };
                bindingList.ListChanged += bindingList_ListChanged;
                authorizationRulesBindingSource.DataSource = bindingList;
                authorizationRulesDataGridView.DataSource = authorizationRulesBindingSource;

                txtPath.Focus();
            }
        }
        private void btnCreateDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (serviceBusHelper == null)
                {
                    return;
                }
                if (btnCreateDelete.Text == DeleteText)
                {
                    using (var deleteForm = new DeleteForm(eventHubDescription.Path, EventHubEntity.ToLower()))
                    {
                        if (deleteForm.ShowDialog() == DialogResult.OK)
                        {
                            serviceBusHelper.DeleteEventHub(eventHubDescription);
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(txtPath.Text))
                    {
                        writeToLog(PathCannotBeNull);
                        return;
                    }
                    var description = new EventHubDescription(txtPath.Text)
                        {
                            UserMetadata = txtUserMetadata.Text
                        };

                    if (!string.IsNullOrEmpty(txtMessageRetentionInDays.Text))
                    {
                        description.MessageRetentionInDays = txtMessageRetentionInDays.IntegerValue;
                    }

                    description.PartitionCount = trackBarPartitionCount.Value;

                    var bindingList = authorizationRulesBindingSource.DataSource as BindingList<AuthorizationRuleWrapper>;
                    if (bindingList != null)
                    {
                        for (var i = 0; i < bindingList.Count; i++)
                        {
                            var rule = bindingList[i];
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.KeyName))
                                {
                                    writeToLog(string.Format(KeyNameCannotBeNull, i));
                                    continue;
                                }
                                if (string.IsNullOrWhiteSpace(rule.PrimaryKey))
                                {
                                    writeToLog(string.Format(PrimaryKeyCannotBeNull, i));
                                    continue;
                                }
                            }
                            var rightList = new List<AccessRights>();
                            if (rule.Manage)
                            {
                                rightList.AddRange(new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });
                            }
                            else
                            {
                                if (rule.Send)
                                {
                                    rightList.Add(AccessRights.Send);
                                }
                                if (rule.Listen)
                                {
                                    rightList.Add(AccessRights.Listen);
                                }
                            }
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey,
                                                                                                    rightList));
                                }
                                else
                                {
                                    description.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                    rule.PrimaryKey,
                                                                                                    rule.SecondaryKey,
                                                                                                    rightList));
                                }
                            }
                            else
                            {
                                description.Authorization.Add(new AllowRule(rule.IssuerName,
                                                                            rule.ClaimType,
                                                                            rule.ClaimValue,
                                                                            rightList));
                            }
                        }
                    }

                    eventHubDescription = serviceBusHelper.CreateEventHub(description);
                    InitializeControls();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
 public PartitionListenerControl(WriteToLogDelegate writeToLog,
                                 Action stopAndRestartLog,
                                 ServiceBusHelper serviceBusHelper, 
                                 ConsumerGroupDescription consumerGroupDescription,
                                 IEnumerable<PartitionDescription> partitionDescriptions)
 {
     Task.Factory.StartNew(AsyncTrackEventData).ContinueWith(t =>
     {
         if (t.IsFaulted && t.Exception != null)
         {
             writeToLog(t.Exception.Message);
         }
     });
     this.writeToLog = writeToLog;
     this.stopAndRestartLog = stopAndRestartLog;
     this.serviceBusHelper = serviceBusHelper;
     this.consumerGroupDescription = consumerGroupDescription;
     var descriptions = partitionDescriptions as IList<PartitionDescription> ?? partitionDescriptions.ToList();
     this.partitionDescriptions = descriptions;
     partitionCount = partitionDescriptions == null || descriptions.Count == 0? 0 : descriptions.Count;
     eventHubDescription = serviceBusHelper.NamespaceManager.GetEventHub(consumerGroupDescription.EventHubPath);    
     InitializeComponent();
     InitializeControls();
     checkBoxCheckpoint_CheckedChanged(null, null);
     Disposed += ListenerControl_Disposed;
 }
 public PartitionListenerControl()
 {
     eventHubDescription = null;
 }
 /// <summary>
 /// Deletes the event hub described by the relative name of the service namespace base address.
 /// </summary>
 /// <param name="eventHubDescription">The event hub to delete.</param>
 public void DeleteEventHub(EventHubDescription eventHubDescription)
 {
     if (eventHubDescription == null ||
         string.IsNullOrWhiteSpace(eventHubDescription.Path))
     {
         throw new ArgumentException(EventHubDescriptionCannotBeNull);
     }
     if (namespaceManager != null)
     {
         RetryHelper.RetryAction(() => namespaceManager.DeleteEventHubAsync(eventHubDescription.Path), writeToLog);
         WriteToLogIf(traceEnabled, string.Format(CultureInfo.CurrentCulture, EventHubDeleted, eventHubDescription.Path));
         OnDelete(new ServiceBusHelperEventArgs(eventHubDescription, EntityType.EventHub));
     }
     else
     {
         throw new ApplicationException(ServiceBusIsDisconnected);
     }
 }
 /// <summary>
 /// Retrieves the collection of consumer groups of the event hub passed as a parameter.
 /// </summary>
 /// <param name="description">A event hub belonging to the current service namespace base.</param>
 /// <returns>Returns an IEnumerable<SubscriptionDescription/> collection of consumer groups attached to the event hub passed as a parameter.</returns>
 public IEnumerable<ConsumerGroupDescription> GetConsumerGroups(EventHubDescription description)
 {
     if (description == null)
     {
         throw new ArgumentException(EventHubDescriptionCannotBeNull);
     }
     if (namespaceManager != null)
     {
         return RetryHelper.RetryFunc(() => namespaceManager.GetConsumerGroups(description.Path), writeToLog);
     }
     throw new ApplicationException(ServiceBusIsDisconnected);
 }
Example #43
0
 private IEnumerable<PartitionDescription> GetPartitionsFromPartitionIds(EventHubDescription eventHubDescription)
 {
     if (eventHubDescription == null)
     {
         yield break;
     }
     foreach (var partitionId in eventHubDescription.PartitionIds)
     {
         yield return new PartitionDescription(eventHubDescription.Path, partitionId);
     }
 }
 public void RefreshData(EventHubDescription eventHub)
 {
     try
     {
         eventHubDescription = eventHub;
         InitializeData();
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
 }
        public int Run()
        {
            // Obtain management via .publishsettings file from https://manage.windowsazure.com/publishsettings/index?schemaversion=2.0
            var creds = new CertificateCloudCredentials(SubscriptionId, ManagementCertificate);

            // Create Namespace
            var sbMgmt = new ServiceBusManagementClient(creds);

            ServiceBusNamespaceResponse nsResponse = null;

            Console.WriteLine("Creating Service Bus namespace {0} in location {1}", SBNamespace, Location);
            try
            {
                var resultSb = sbMgmt.Namespaces.Create(SBNamespace, Location);
                if (resultSb.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine("Error creating Service Bus namespace {0} in Location {1}: {2}", SBNamespace, Location, resultSb.StatusCode);
                    return 1;
                }
            }
            catch (CloudException)
            {
                try
                {
                    // There is (currently) no clean error code returned when the namespace already exists
                    // Check if it does
                    nsResponse = sbMgmt.Namespaces.Get(SBNamespace);
                    Console.WriteLine("Service Bus namespace {0} already existed.", SBNamespace);
                }
                catch (Exception)
                {
                    nsResponse = null;
                }
                if (nsResponse == null)
                {
                    throw;
                }
            }

            // Wait until the namespace is active
            while (nsResponse == null || nsResponse.Namespace.Status != "Active")
            {
                nsResponse = sbMgmt.Namespaces.Get(SBNamespace);
                if (nsResponse.Namespace.Status == "Active")
                {
                    break;
                }
                Console.WriteLine("Namespace {0} in state {1}. Waiting...", SBNamespace, nsResponse.Namespace.Status);
                System.Threading.Thread.Sleep(5000);
            }

            // Get the namespace connection string
            var nsDescription = sbMgmt.Namespaces.GetNamespaceDescription(SBNamespace);
            var nsConnectionString = nsDescription.NamespaceDescriptions.First(
                (d) => String.Equals(d.AuthorizationType, "SharedAccessAuthorization")
                ).ConnectionString;

            // Create EHs + device keys + consumer keys (WebSite*)
            var nsManager = NamespaceManager.CreateFromConnectionString(nsConnectionString);

            var ehDescriptionDevices = new EventHubDescription(EventHubNameDevices)
            {
                PartitionCount = 8,
            };
            ehDescriptionDevices.Authorization.Add(new SharedAccessAuthorizationRule("D1", new List<AccessRights> { AccessRights.Send }));
            ehDescriptionDevices.Authorization.Add(new SharedAccessAuthorizationRule("D2", new List<AccessRights> { AccessRights.Send }));
            ehDescriptionDevices.Authorization.Add(new SharedAccessAuthorizationRule("D3", new List<AccessRights> { AccessRights.Send }));
            ehDescriptionDevices.Authorization.Add(new SharedAccessAuthorizationRule("D4", new List<AccessRights> { AccessRights.Send }));

            ehDescriptionDevices.Authorization.Add(new SharedAccessAuthorizationRule("WebSite", new List<AccessRights> { AccessRights.Manage, AccessRights.Listen, AccessRights.Send }));

            ehDescriptionDevices.Authorization.Add(new SharedAccessAuthorizationRule("StreamingAnalytics", new List<AccessRights> { AccessRights.Manage, AccessRights.Listen, AccessRights.Send }));

            Console.WriteLine("Creating Event Hub {0}", EventHubNameDevices);
            EventHubDescription ehDevices = null;
            do
            {
                try
                {
                    ehDevices = nsManager.CreateEventHubIfNotExists(ehDescriptionDevices);
                }
                catch (System.UnauthorizedAccessException)
                {
                    Console.WriteLine("Service Bus connection string not valid yet. Waiting...");
                    System.Threading.Thread.Sleep(5000);
                }
            } while (ehDevices == null);

            var ehDescriptionAlerts = new EventHubDescription(EventHubNameAlerts)
            {
                PartitionCount = 8,
            };
            ehDescriptionAlerts.Authorization.Add(new SharedAccessAuthorizationRule("WebSite", new List<AccessRights> { AccessRights.Manage, AccessRights.Listen, AccessRights.Send }));
            ehDescriptionAlerts.Authorization.Add(new SharedAccessAuthorizationRule("StreamingAnalytics", new List<AccessRights> { AccessRights.Manage, AccessRights.Listen, AccessRights.Send }));

            Console.WriteLine("Creating Event Hub {0}", EventHubNameAlerts);
            var ehAlerts = nsManager.CreateEventHubIfNotExists(ehDescriptionAlerts);

            // Create Storage Account for Event Hub Processor
            var stgMgmt = new StorageManagementClient(creds);
            try
            {
                Console.WriteLine("Creating Storage Account {0} in location {1}", StorageAccountName, Location);
                var resultStg = stgMgmt.StorageAccounts.Create(
                    new StorageAccountCreateParameters { Name = StorageAccountName.ToLowerInvariant(), Location = Location, AccountType = "Standard_LRS" });

                if (resultStg.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine("Error creating storage account {0} in Location {1}: {2}", StorageAccountName, Location, resultStg.StatusCode);
                    return 1;
                }
            }
            catch (CloudException ce)
            {
                if (String.Equals(ce.ErrorCode, "ConflictError", StringComparison.InvariantCultureIgnoreCase))
                {
                    Console.WriteLine("Storage account {0} already existed.", StorageAccountName);
                }
                else
                {
                    throw;
                }
            }
            var keyResponse = stgMgmt.StorageAccounts.GetKeys(StorageAccountName.ToLowerInvariant());
            if (keyResponse.StatusCode != System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Error retrieving access keys for storage account {0} in Location {1}: {2}", StorageAccountName, Location, keyResponse.StatusCode);
                return 1;
            }

            var storageKey = keyResponse.PrimaryKey;
            string ehDevicesWebSiteConnectionString = new ServiceBusConnectionStringBuilder(nsConnectionString)
            {
                SharedAccessKeyName = "WebSite",
                SharedAccessKey = (ehDevices.Authorization.First((d)
                   => String.Equals(d.KeyName, "WebSite", StringComparison.InvariantCultureIgnoreCase)) as SharedAccessAuthorizationRule).PrimaryKey,
            }.ToString();

            string ehAlertsWebSiteConnectionString = new ServiceBusConnectionStringBuilder(nsConnectionString)
            {
                SharedAccessKeyName = "WebSite",
                SharedAccessKey = (ehAlerts.Authorization.First((d)
                   => String.Equals(d.KeyName, "WebSite", StringComparison.InvariantCultureIgnoreCase)) as SharedAccessAuthorizationRule).PrimaryKey,
            }.ToString();

            // Write a new web.config template file
            var doc = new XmlDocument();
            doc.PreserveWhitespace = true;

            var inputFileName = (this.Transform ? "\\web.PublishTemplate.config" : "\\web.config");
            var outputFileName = (this.Transform ? String.Format("\\web.{0}.config", NamePrefix) : "\\web.config");

            doc.Load(WebSiteDirectory + inputFileName);

            doc.SelectSingleNode("/configuration/appSettings/add[@key='Microsoft.ServiceBus.EventHubDevices']/@value").Value
                = EventHubNameDevices;
            doc.SelectSingleNode("/configuration/appSettings/add[@key='Microsoft.ServiceBus.EventHubAlerts']/@value").Value
                = EventHubNameAlerts;
            doc.SelectSingleNode("/configuration/appSettings/add[@key='Microsoft.ServiceBus.ConnectionString']/@value").Value
                = nsConnectionString;
            doc.SelectSingleNode("/configuration/appSettings/add[@key='Microsoft.ServiceBus.ConnectionStringDevices']/@value").Value
                = ehDevicesWebSiteConnectionString;
            doc.SelectSingleNode("/configuration/appSettings/add[@key='Microsoft.ServiceBus.ConnectionStringAlerts']/@value").Value
                = ehAlertsWebSiteConnectionString;
            doc.SelectSingleNode("/configuration/appSettings/add[@key='Microsoft.Storage.ConnectionString']/@value").Value =
                String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", StorageAccountName, storageKey);

            var outputFile = System.IO.Path.GetFullPath(WebSiteDirectory + outputFileName);

            doc.Save(outputFile);

            Console.WriteLine();
            Console.WriteLine("Service Bus management connection string (i.e. for use in Service Bus Explorer):");
            Console.WriteLine(nsConnectionString);
            Console.WriteLine();
            Console.WriteLine("Device AMQP address strings (for Raspberry PI/devices):");
            for (int i = 1; i <= 4; i++)
            {
                var deviceKeyName = String.Format("D{0}", i);
                var deviceKey = (ehDevices.Authorization.First((d)
                        => String.Equals(d.KeyName, deviceKeyName, StringComparison.InvariantCultureIgnoreCase)) as SharedAccessAuthorizationRule).PrimaryKey;

                Console.WriteLine("amqps://{0}:{1}@{2}.servicebus.windows.net", deviceKeyName, Uri.EscapeDataString(deviceKey), SBNamespace);

                //Console.WriteLine(new ServiceBusConnectionStringBuilder(nsConnectionString)
                //{
                //    SharedAccessKeyName = deviceKeyName,
                //    SharedAccessKey = deviceKey,
                //}.ToString());
            }
            Console.WriteLine();
            Console.WriteLine("Web.Config saved to {0}", outputFile);

            #if AZURESTREAMANALYTICS
            // Create StreamAnalyticsJobs + inputs + outputs + enter keys

            // Untested code. May require AAD authentication, no support for management cert?

            // Create Resource Group for the Stream Analytics jobs
            var groupCreateRequest = WebRequest.Create(String.Format("https://management.azure.com/subscriptions/{0}/resourcegroups/{1}?api-version=2014-04-01-preview",
                SubscriptionId, StreamAnalyticsGroup)) as HttpWebRequest;

            groupCreateRequest.ClientCertificates.Add(creds.ManagementCertificate);
            groupCreateRequest.ContentType = "application/json";
            groupCreateRequest.Method = "PUT";
            groupCreateRequest.KeepAlive = true;

            var bytesGroup = Encoding.UTF8.GetBytes("{\"location\":\"Central US\"}");
            groupCreateRequest.ContentLength = bytesGroup.Length;
            groupCreateRequest.GetRequestStream().Write(bytesGroup, 0, bytesGroup.Length);

            var groupCreateResponse = groupCreateRequest.GetResponse();

            //var streamMgmt = new ManagementClient(creds); //, new Uri("https://management.azure.com"));
            //HttpClient client = streamMgmt.HttpClient;

            var createJob = new StreamAnalyticsJob()
            {
                location = Location,
                inputs = new List<StreamAnalyticsEntity>
                {
                    new StreamAnalyticsEntity
                    {
                        name = "devicesInput",
                        properties = new Dictionary<string,object>
                        {
                            { "type" , "stream" },
                            { "serialization" , new Dictionary<string,object>
                                {
                                    { "type", "JSON"},
                                    { "properties", new Dictionary<string, object>
                                        {
                                            { "encoding", "UTF8"},
                                        }
                                    }
                                }
                            },
                            { "datasource", new Dictionary<string,object>
                                {
                                    { "type", "Microsoft.ServiceBus/EventHub" },
                                    { "properties", new Dictionary<string,object>
                                        {
                                            { "eventHubNamespace", Namespace },
                                            { "eventHubName", EventHubDevices },
                                            { "sharedAccessPolicyName", "StreamingAnalytics" },
                                            { "sharedAccessPolicyKey",
                                                (ehDevices.Authorization.First( (d)
                                                    => String.Equals(d.KeyName, "StreamingAnalytics", StringComparison.InvariantCultureIgnoreCase)) as SharedAccessAuthorizationRule).PrimaryKey },
                                        }
                                    }
                                }
                             }
                        },
                    },
                },
                transformation = new StreamAnalyticsEntity()
                {
                    name = "Aggregates",
                    properties = new Dictionary<string,object>
                    {
                        { "streamingUnits", 1 },
                        { "query" , "select * from devicesInput" },
                    }
                },
                outputs = new List<StreamAnalyticsEntity>
                {
                    new StreamAnalyticsEntity
                    {
                        name = "output",
                        properties = new Dictionary<string,object>
                        {
                            { "datasource", new Dictionary<string,object>
                                {
                                    { "type", "Microsoft.ServiceBus/EventHub" },
                                    { "properties", new Dictionary<string,object>
                                        {
                                            { "eventHubNamespace", Namespace },
                                            { "eventHubName", EventHubAlerts },
                                            { "sharedAccessPolicyName", "StreamingAnalytics" },
                                            { "sharedAccessPolicyKey",
                                                (ehAlerts.Authorization.First( (d) => String.Equals(d.KeyName, "StreamingAnalytics", StringComparison.InvariantCultureIgnoreCase)) as SharedAccessAuthorizationRule).PrimaryKey },
                                        }
                                    }
                                }
                            },
                            { "serialization" , new Dictionary<string,object>
                                {
                                    { "type", "JSON"},
                                    { "properties", new Dictionary<string, object>
                                        {
                                            { "encoding", "UTF8"},
                                        }
                                    }
                                }
                            },
                        },
                    },
                }
            };

            var jobCreateRequest = WebRequest.Create(String.Format("https://management.azure.com/subscriptions/{0}/resourcegroups/{1}/Microsoft.StreamAnalytics/streamingjobs/{2}?api-version=2014-10-01",
                SubscriptionId, StreamAnalyticsGroup, JobAggregates)) as HttpWebRequest;

            jobCreateRequest.ClientCertificates.Add(creds.ManagementCertificate);
            jobCreateRequest.ContentType = "application/json";
            jobCreateRequest.Method = "PUT";
            jobCreateRequest.KeepAlive = true;

            var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(createJob));
            jobCreateRequest.ContentLength = bytes.Length;
            jobCreateRequest.GetRequestStream().Write(bytes, 0, bytes.Length);

            var jobCreateResponse = jobCreateRequest.GetResponse();

            //var jobCreateTask = streamMgmt.HttpClient.PutAsync(
            //    String.Format("https://management.azure.com/subscriptions/{0}/resourcegroups/{1}/Microsoft.StreamAnalytics/streamingjobs/{2}?api-version=2014-10-01",
            //    SubscriptionId, StreamAnalyticsGroup, JobAggregates),
            //    new StringContent(JsonConvert.SerializeObject(createJob)));
            //jobCreateTask.Wait();
            //var jobCreateResponse = jobCreateTask.Result;
            #endif
            return 0;
        }
 public HandleEventHubControl(WriteToLogDelegate writeToLog, ServiceBusHelper serviceBusHelper, EventHubDescription eventHubDescription)
 {
     this.writeToLog = writeToLog;
     this.serviceBusHelper = serviceBusHelper;
     this.eventHubDescription = eventHubDescription;
     InitializeComponent();
     InitializeControls();
 } 
        private async void btnCancelUpdate_Click(object sender, EventArgs e)
        {
            bool ok = true;

            if (btnCancelUpdate.Text == CancelText)
            {
                if (OnCancel != null)
                {
                    OnCancel();
                }
            }
            else
            {
                try
                {
                    eventHubDescription.UserMetadata = txtUserMetadata.Text;

                    if (!string.IsNullOrEmpty(txtMessageRetentionInDays.Text))
                    {
                        eventHubDescription.MessageRetentionInDays = txtMessageRetentionInDays.IntegerValue;
                    }

                    var bindingList = authorizationRulesBindingSource.DataSource as BindingList<AuthorizationRuleWrapper>;
                    if (bindingList != null)
                    {
                        for (var i = 0; i < bindingList.Count; i++)
                        {
                            var rule = bindingList[i];

                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.KeyName))
                                {
                                    writeToLog(string.Format(KeyNameCannotBeNull, i));
                                    continue;
                                }
                            }
                            var rightList = new List<AccessRights>();
                            if (rule.Manage)
                            {
                                rightList.AddRange(new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen });
                            }
                            else
                            {
                                if (rule.Send)
                                {
                                    rightList.Add(AccessRights.Send);
                                }
                                if (rule.Listen)
                                {
                                    rightList.Add(AccessRights.Listen);
                                }
                            }
                            if (serviceBusHelper.IsCloudNamespace)
                            {
                                if (string.IsNullOrWhiteSpace(rule.PrimaryKey) && string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    eventHubDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rightList));
                                }
                                else if (string.IsNullOrWhiteSpace(rule.SecondaryKey))
                                {
                                    eventHubDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rule.PrimaryKey,
                                                                                                         rightList));
                                }
                                else
                                {
                                    eventHubDescription.Authorization.Add(new SharedAccessAuthorizationRule(rule.KeyName,
                                                                                                         rule.PrimaryKey,
                                                                                                         rule.SecondaryKey,
                                                                                                         rightList));
                                }
                            }
                            else
                            {
                                eventHubDescription.Authorization.Add(new AllowRule(rule.IssuerName,
                                                                                 rule.ClaimType,
                                                                                 rule.ClaimValue,
                                                                                 rightList));
                            }
                        }
                    }
                    serviceBusHelper.UpdateEventHub(eventHubDescription);
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                    ok = false;
                }
                finally
                {
                    InitializeControls();
                }
                if (ok)
                {
                    return;
                }
                try
                {
                    eventHubDescription = await serviceBusHelper.NamespaceManager.GetEventHubAsync(eventHubDescription.Path);
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
        }
 public HandleEventHubControl(WriteToLogDelegate writeToLog, ServiceBusHelper serviceBusHelper, EventHubDescription eventHubDescription)
 {
     this.writeToLog = writeToLog;
     this.serviceBusHelper = serviceBusHelper;
     this.eventHubDescription = eventHubDescription;
     dataPointBindingList = new BindingList<MetricDataPoint>
     {
         AllowNew = true,
         AllowEdit = true,
         AllowRemove = true
     };
     InitializeComponent();
     InitializeControls();
 } 
 /// <summary>
 /// Retrieves the collection of partitions of the event hub passed as a parameter.
 /// </summary>
 /// <param name="description">A event hub belonging to the current service namespace base.</param>
 /// <returns>Returns an IEnumerable<SubscriptionDescription/> collection of partitions attached to the event hub passed as a parameter.</returns>
 public IEnumerable<PartitionDescription> GetPartitions(EventHubDescription description)
 {
     if (description == null)
     {
         throw new ArgumentException(EventHubDescriptionCannotBeNull);
     }
     if (namespaceManager != null)
     {
         return description.PartitionIds.Select((t, i) => i).Select(index => RetryHelper.RetryFunc(() => namespaceManager.GetEventHubPartition(description.Path, description.PartitionIds[index]), writeToLog)).ToList();
     }
     throw new ApplicationException(ServiceBusIsDisconnected);
 }
Example #50
0
 private void CreateEventHubSubTree(EventHubDescription eventHub, TreeNode entityNode)
 {
     try
     {
         var partitions = GetPartitionsFromPartitionIds(eventHub);
         var partitionDescriptions = partitions as IList<PartitionDescription> ?? partitions.ToList();
         WriteToLog(string.Format(PartitionsRetrievedFormat, eventHub.PartitionCount, eventHub.Path));
         CreateEventHubConsumerGroups(eventHub, entityNode, partitionDescriptions);
     }
     catch (Exception ex)
     {
         HandleException(ex);
     }
 }
 /// <summary>
 /// Creates a new event hub in the service namespace with the given name.
 /// </summary>
 /// <param name="description">A EventHubDescription object describing the attributes with which the new event hub will be created.</param>
 /// <returns>Returns a newly-created EventHubDescription object.</returns>
 public EventHubDescription CreateEventHub(EventHubDescription description)
 {
     if (description == null)
     {
         throw new ArgumentException(DescriptionCannotBeNull);
     }
     if (namespaceManager != null)
     {
         var eventHub = RetryHelper.RetryFunc(() => namespaceManager.CreateEventHub(description), writeToLog);
         WriteToLogIf(traceEnabled, string.Format(CultureInfo.CurrentCulture, EventHubCreated, description.Path));
         OnCreate(new ServiceBusHelperEventArgs(eventHub, EntityType.EventHub));
         return eventHub;
     }
     throw new ApplicationException(ServiceBusIsDisconnected);
 }
Example #52
0
 private void CreateEventHubPartitions(EventHubDescription eventHub, TreeNode entityNode)
 {
     var partitions = GetPartitionsFromPartitionIds(eventHub);
     var partitionDescriptions = partitions as IList<PartitionDescription> ?? partitions.ToList();
     if (partitionDescriptions.Any())
     {
         var node = FindNode(PartitionEntities, entityNode);
         if (node != null)
         {
             entityNode.Nodes.Remove(node);
         }
         var partitionsNode = entityNode.Nodes.Add(PartitionEntities, PartitionEntities, PartitionListIconIndex, PartitionListIconIndex);
         partitionsNode.ContextMenuStrip = partitionsContextMenuStrip;
         partitionsNode.Tag = eventHub;
         foreach (var partition in partitionDescriptions)
         {
             CreateEventHubPartitionNode(partition, partitionsNode);
         }
         WriteToLog(string.Format(PartitionsRetrievedFormat, eventHub.PartitionCount, eventHub.Path));
     }
 }
 public TestEventHubControl(MainForm mainForm,
                            WriteToLogDelegate writeToLog,
                            Func<Task> stopLog,
                            Action startLog,
                            ServiceBusHelper serviceBusHelper,
                            EventHubDescription eventHubDescription,
                            PartitionDescription partitionDescription)
 {
     this.mainForm = mainForm;
     this.writeToLog = writeToLog;
     this.stopLog = stopLog;
     this.startLog = startLog;
     this.serviceBusHelper = serviceBusHelper;
     this.eventHubDescription = eventHubDescription;
     this.partitionDescription = partitionDescription;
     InitializeComponent();
     InitializeControls();
 }
Example #54
0
 private void CreateEventHubConsumerGroups(EventHubDescription eventHub, TreeNode entityNode, IList<PartitionDescription> partitionDescriptions)
 {
     var consumerGroups = serviceBusHelper.GetConsumerGroups(eventHub.Path);
     var consumerGroupDescriptions = consumerGroups as IList<ConsumerGroupDescription> ?? consumerGroups.ToList();
     if (consumerGroups != null && consumerGroupDescriptions.Any())
     {
         var node = FindNode(ConsumerGroupEntities, entityNode);
         if (node != null)
         {
             entityNode.Nodes.Remove(node);
         }
         var consumerGroupsNode = entityNode.Nodes.Add(ConsumerGroupEntities, ConsumerGroupEntities, ConsumerGroupListIconIndex, ConsumerGroupListIconIndex);
         consumerGroupsNode.ContextMenuStrip = consumerGroupsContextMenuStrip;
         consumerGroupsNode.Tag = eventHub;
         foreach (var consumerGroupDescription in consumerGroupDescriptions)
         {
             CreateEventHubConsumerGroupNode(eventHub, consumerGroupDescription, partitionDescriptions, consumerGroupsNode);
         }
         WriteToLog(string.Format(ConsumerGroupsRetrievedFormat, consumerGroupDescriptions.Count, eventHub.Path));
     }
 }
Example #55
0
 private TreeNode CreateEventHubConsumerGroupNode(EventHubDescription eventHub,
                                                  ConsumerGroupDescription consumerGroupDescription,
                                                  IList<PartitionDescription> partitionDescriptions,
                                                  TreeNode consumerGroupsNode)
 {
     if (consumerGroupsNode.Nodes.ContainsKey(consumerGroupDescription.Name))
     {
         return null;
     }
     var consumerGroupNode = consumerGroupsNode.Nodes.Add(consumerGroupDescription.Name,
                                                          consumerGroupDescription.Name,
                                                          ConsumerGroupIconIndex,
                                                          ConsumerGroupIconIndex);
     consumerGroupNode.ContextMenuStrip = consumerGroupContextMenuStrip;
     consumerGroupNode.Tag = consumerGroupDescription;
     if (partitionDescriptions == null || !partitionDescriptions.Any())
     {
         return consumerGroupNode;
     }
     consumerGroupNode.Nodes.Clear();
     var partitionsNode = consumerGroupNode.Nodes.Add(PartitionEntities, PartitionEntities, PartitionListIconIndex, PartitionListIconIndex);
     partitionsNode.ContextMenuStrip = partitionsContextMenuStrip;
     partitionsNode.Tag = eventHub;
     foreach (var partition in partitionDescriptions)
     {
         CreateEventHubPartitionNode(partition, partitionsNode);
     }
     return consumerGroupNode;
 }
Example #56
0
        private void ShowEventHub(EventHubDescription eventHub)
        {
            HandleEventHubControl eventHubControl = null;

            try
            {
                panelMain.SuspendDrawing();
                foreach (var userControl in panelMain.Controls.OfType<UserControl>())
                {
                    userControl.Dispose();
                }
                panelMain.Controls.Clear();
                panelMain.BackColor = SystemColors.GradientInactiveCaption;
                eventHubControl = new HandleEventHubControl(WriteToLog, serviceBusHelper, eventHub);
                eventHubControl.SuspendDrawing();
                eventHubControl.Location = new Point(1, panelLog.HeaderHeight + 1);
                panelMain.Controls.Add(eventHubControl);
                SetControlSize(eventHubControl);
                eventHubControl.OnCancel += MainForm_OnCancel;
                eventHubControl.OnRefresh += MainForm_OnRefresh;
                eventHubControl.OnChangeStatus += MainForm_OnChangeStatus;
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            finally
            {
                panelMain.ResumeDrawing();
                if (eventHubControl != null)
                {
                    eventHubControl.ResumeDrawing();
                }
            }
        }
 public PartitionListenerControl(WriteToLogDelegate writeToLog,
                                 Func<Task> stopLog,
                                 Action startLog,
                                 ServiceBusHelper serviceBusHelper,
                                 ConsumerGroupDescription consumerGroupDescription,
                                 IEnumerable<PartitionDescription> partitionDescriptions)
 {
     Task.Factory.StartNew(AsyncTrackEventData).ContinueWith(t =>
     {
         if (t.IsFaulted && t.Exception != null)
         {
             writeToLog(t.Exception.Message);
         }
     });
     this.writeToLog = writeToLog;
     this.stopLog = stopLog;
     this.startLog = startLog;
     this.serviceBusHelper = serviceBusHelper;
     eventHubDescription = serviceBusHelper.NamespaceManager.GetEventHub(consumerGroupDescription.EventHubPath);
     eventHubClient = EventHubClient.CreateFromConnectionString(GetAmqpConnectionString(serviceBusHelper.ConnectionString),
                                                                                        consumerGroupDescription.EventHubPath);
     consumerGroup = string.Compare(consumerGroupDescription.Name,
                                    DefaultConsumerGroupName,
                                    StringComparison.InvariantCultureIgnoreCase) == 0
                                    ? eventHubClient.GetDefaultConsumerGroup()
                                    : eventHubClient.GetConsumerGroup(consumerGroupDescription.Name);
     IList<string> partitionIdList = partitionDescriptions.Select(pd => pd.PartitionId).ToList();
     foreach (var id in partitionIdList)
     {
         partitionRuntumeInformationList.Add(eventHubClient.GetPartitionRuntimeInformation(id));
     }
     partitionCount = partitionRuntumeInformationList.Count;
     InitializeComponent();
     InitializeControls();
     Disposed += ListenerControl_Disposed;
 }
 public static string EventHubDescriptionAsString(EventHubDescription ehd)
 {
     var sb = new StringBuilder();
     sb.AppendLine("Path: ".PadRight(30) + ehd.Path);
     sb.AppendLine("PartitionCount: ".PadRight(30) + ehd.PartitionCount);
     sb.AppendLine("MessageRetentionInDays: ".PadRight(30) + ehd.MessageRetentionInDays);
     sb.AppendLine("Status: ".PadRight(30) + ehd.Status);
     sb.AppendLine("CreatedAt: ".PadRight(30) + ehd.CreatedAt);
     return sb.ToString();
 }
        public ContainerForm(ServiceBusHelper serviceBusHelper, MainForm mainForm, EventHubDescription eventHubDescription, PartitionDescription partitionDescription = null)
        {
            try
            {
                InitializeComponent();
                Task.Factory.StartNew(AsyncWriteToLog).ContinueWith(t =>
                {
                    if (t.IsFaulted && t.Exception != null)
                    {
                        WriteToLog(t.Exception.Message);
                    }
                });
                this.mainForm = mainForm;
                mainSplitterDistance = mainSplitContainer.SplitterDistance;
                SuspendLayout();
                panelMain.SuspendDrawing();
                panelMain.Controls.Clear();
                panelMain.BackColor = SystemColors.GradientInactiveCaption;

                testEventHubControl = new TestEventHubControl(mainForm, WriteToLog, StopLog, StartLog, new ServiceBusHelper(WriteToLog, serviceBusHelper), eventHubDescription, partitionDescription)
                {
                    Location = new Point(1, panelMain.HeaderHeight + 1),
                    Size = new Size(panelMain.Size.Width - 3, panelMain.Size.Height - 26),
                    Anchor = AnchorStyles.Bottom | AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right
                };

                Text = partitionDescription == null
                    ? string.Format(SendEventsToEventHubFormat, eventHubDescription.Path)
                    : string.Format(SendEventsToEventHubPartitionFormat,
                        partitionDescription.PartitionId,
                        eventHubDescription.Path);

                testEventHubControl.btnCancel.Text = CloseLabel;
                testEventHubControl.btnCancel.Click -= testEventHubControl.btnCancel_Click;
                testEventHubControl.btnCancel.Click += BtnCancelOnClick;
                testEventHubControl.Focus();

                panelMain.HeaderText = partitionDescription == null ?
                                       string.Format(HeaderTextTestEventHubFormat, eventHubDescription.Path) :
                                       string.Format(HeaderTextTestEventHubPartitionFormat, 
                                                     partitionDescription.PartitionId, 
                                                     eventHubDescription.Path);

                panelMain.Controls.Add(testEventHubControl);
                SetStyle(ControlStyles.ResizeRedraw, true);
            }
            finally
            {
                panelMain.ResumeDrawing();
                ResumeLayout();
            }
        }
        private void InitializeControls()
        {

            // Set Grid style
            authorizationRulesDataGridView.EnableHeadersVisualStyles = false;

            // Set the selection background color for all the cells.
            authorizationRulesDataGridView.DefaultCellStyle.SelectionBackColor = Color.FromArgb(92, 125, 150);
            authorizationRulesDataGridView.DefaultCellStyle.SelectionForeColor = SystemColors.Window;

            // Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default 
            // value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
            authorizationRulesDataGridView.RowHeadersDefaultCellStyle.SelectionBackColor = Color.FromArgb(153, 180, 209);

            // Set the background color for all rows and for alternating rows.  
            // The value for alternating rows overrides the value for all rows. 
            authorizationRulesDataGridView.RowsDefaultCellStyle.BackColor = SystemColors.Window;
            authorizationRulesDataGridView.RowsDefaultCellStyle.ForeColor = SystemColors.ControlText;
            //authorizationRulesDataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.White;
            //authorizationRulesDataGridView.AlternatingRowsDefaultCellStyle.ForeColor = SystemColors.ControlText;

            // Set the row and column header styles.
            authorizationRulesDataGridView.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(215, 228, 242);
            authorizationRulesDataGridView.RowHeadersDefaultCellStyle.ForeColor = SystemColors.ControlText;
            authorizationRulesDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(215, 228, 242);
            authorizationRulesDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = SystemColors.ControlText;

            authorizationRulesDataGridView.AutoGenerateColumns = false;
            if (authorizationRulesDataGridView.Columns.Count == 0)
            {
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "IssuerName", DataPropertyName = "IssuerName" });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewComboBoxColumn { Name = "ClaimType", DataPropertyName = "ClaimType", DataSource = claimTypes, FlatStyle = FlatStyle.Flat });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "ClaimValue", DataPropertyName = "ClaimValue" });
                if (serviceBusHelper.IsCloudNamespace)
                {
                    authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "KeyName", DataPropertyName = "KeyName" });
                    authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "PrimaryKey", DataPropertyName = "PrimaryKey" });
                    authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "SecondaryKey", DataPropertyName = "SecondaryKey" });
                }
                authorizationRulesDataGridView.Columns.Add(new DataGridViewCheckBoxColumn { Name = "Manage", DataPropertyName = "Manage", Width = 50 });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewCheckBoxColumn { Name = "Send", DataPropertyName = "Send", Width = 50 });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewCheckBoxColumn { Name = "Listen", DataPropertyName = "Listen", Width = 50 });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "Revision", DataPropertyName = "Revision", Width = 50, ReadOnly = true });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "CreatedTime", DataPropertyName = "CreatedTime", ReadOnly = true });
                authorizationRulesDataGridView.Columns.Add(new DataGridViewTextBoxColumn { Name = "ModifiedTime", DataPropertyName = "ModifiedTime", ReadOnly = true });
            }

            if (eventHubDescription != null)
            {
                // Initialize buttons
                btnCreateDelete.Text = DeleteText;
                btnCancelUpdate.Text = UpdateText;
                btnChangeStatus.Text = eventHubDescription.Status == EntityStatus.Active ? DisableText : EnableText;
                btnRefresh.Visible = true;
                btnChangeStatus.Visible = true;
                

                // Initialize textboxes
                txtPath.ReadOnly = true;
                txtPath.BackColor = SystemColors.Window;
                txtPath.GotFocus += textBox_GotFocus;

                // TrackBar
                trackBarPartitionCount.Enabled = false;

                // Initialize Data
                InitializeData();

                toolTip.SetToolTip(txtPath, PathTooltip);
                toolTip.SetToolTip(txtUserMetadata, UserMetadataTooltip);
                toolTip.SetToolTip(txtMessageRetentionInDays, MessageRetentionInDaysTooltip);
                toolTip.SetToolTip(trackBarPartitionCount, PartitionCountTooltip);

                propertyListView.ContextMenuStrip = entityInformationContextMenuStrip;
            }
            else
            {
                // Set Defaults
                var eventHub = new EventHubDescription("DUMMY");
                txtMessageRetentionInDays.Text = eventHub.MessageRetentionInDays.ToString(CultureInfo.InvariantCulture);
                trackBarPartitionCount.Value = eventHub.PartitionCount;

                // Initialize buttons
                btnCreateDelete.Text = CreateText;
                btnCancelUpdate.Text = CancelText;
                btnRefresh.Visible = false;
                btnChangeStatus.Visible = false;

                // Create BindingList for Authorization Rules
                var bindingList = new BindingList<AuthorizationRuleWrapper>(new List<AuthorizationRuleWrapper>())
                {
                    AllowEdit = true,
                    AllowNew = true,
                    AllowRemove = true
                };
                bindingList.ListChanged += bindingList_ListChanged;
                authorizationRulesBindingSource.DataSource = bindingList;
                authorizationRulesDataGridView.DataSource = authorizationRulesBindingSource;

                txtPath.Focus();
            }
        }