public void CancelSubscription(ServiceBusEnpointData value) {

            logger.Log(LogLevel.Info, "CancelSubscription {0} Declared {1} MessageTytpe {2}, IsReusable {3}", value.SubscriptionName, value.DeclaredType.ToString(), value.MessageType.ToString(), value.IsReusable);

            var subscription = mappings.FirstOrDefault(item => item.EndPointData.SubscriptionName.Equals(value.SubscriptionName, StringComparison.OrdinalIgnoreCase));

            if (subscription == null) {
                logger.Log(LogLevel.Info, "CancelSubscription Does not exist {0}", value.SubscriptionName);
                return;
            }

            subscription.Cancel = true;

            Task t = new Task(() => {
                //HACK find better way to wait for a cancel request so we are not blocking.
                logger.Log(LogLevel.Info, "CancelSubscription Deleting {0}", value.SubscriptionName);
                for (int i = 0; i < 100; i++) {
                    if (!subscription.Cancelled) {
                        Thread.Sleep(3000);
                    }
                    else {
                        break;
                    }
                }

                if (namespaceManager.SubscriptionExists(topic.Path, value.SubscriptionName)) {
                    var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
                    Helpers.Execute(() => {
                        namespaceManager.DeleteSubscription(topic.Path, value.SubscriptionName);
                    });
                    logger.Log(LogLevel.Info, "CancelSubscription Deleted {0}", value.SubscriptionName);
                }
            });
            t.Start();
        }
        public void CreateSubscription(ServiceBusEnpointData value) {
            //TODO determine how we can change the filters for an existing registered item

            logger.Log(LogLevel.Info, "CreateSubscription {0} Declared {1} MessageTytpe {2}, IsReusable {3}", value.SubscriptionName, value.DeclaredType.ToString(), value.MessageType.ToString(), value.IsReusable);

            SubscriptionDescription desc = null;

            var data = value.MessageType.FullName;

            if (!namespaceManager.SubscriptionExists(topic.Path, value.SubscriptionName)) {
                logger.Log(LogLevel.Info, "CreateSubscription Creating {0}", value.SubscriptionName);

                var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
                Helpers.Execute(() => {
                    desc = namespaceManager.CreateSubscription(topic.Path, value.SubscriptionName, filter);
                });
            }
            else {
                logger.Log(LogLevel.Info, "CreateSubscription Exists {0}", value.SubscriptionName);
                desc = namespaceManager.GetSubscription(topic.Path, value.SubscriptionName);
            }

            SubscriptionClient subscriptionClient = factory.CreateSubscriptionClient(topic.Path, value.SubscriptionName, ReceiveMode.PeekLock);

            var state = new AzureBusReceiverState() {
                Client = subscriptionClient,
                EndPointData = value,
                Subscription = desc
            };
            mappings.Add(state);

            Task t = new Task(ProcessMessagesForSubscription, state);
            t.Start();
        }
        public void CreateSubscription(ServiceBusEnpointData value) {
            Guard.ArgumentNotNull(value, "value");

            //TODO determine how we can change the filters for an existing registered item
            //ServiceBusNamespaceClient

            lock (lockObject) {

                logger.Info("CreateSubscription {0} Declared {1} MessageTytpe {2}, IsReusable {3} Custom Attribute {4}",
                    value.SubscriptionName,
                    value.DeclaredType.ToString(),
                    value.MessageType.ToString(),
                    value.IsReusable,
                    value.AttributeData != null ? value.AttributeData.ToString() : string.Empty);
                logger.Info("TRANSIENT ERROR HANDLING CAN CAUSE THIS CHECK TO TAKE UP TO 10 SECONDS IF THE SUBSCRIPTION DOES NOT EXIST");

                SubscriptionDescription desc = null;

                bool createNew = false;

                try {
                    logger.Info("CreateSubscription Try {0} ", value.SubscriptionName);
                    // First, let's see if a item with the specified name already exists.
                    minimalRetryPolicy.ExecuteAction(() => {
                        desc = namespaceManager.GetSubscription(topic.Path, value.SubscriptionName);
                    });

                    createNew = (topic == null);
                }
                catch (MessagingEntityNotFoundException) {
                    logger.Info("CreateSubscription Does Not Exist {0} ", value.SubscriptionName);
                    // Looks like the item does not exist. We should create a new one.
                    createNew = true;
                }

                // If a item with the specified name doesn't exist, it will be auto-created.
                if (createNew) {
                    var descriptionToCreate = new SubscriptionDescription(topic.Path, value.SubscriptionName);

                    if (value.AttributeData != null) {
                        var attr = value.AttributeData;
                        if (attr.DefaultMessageTimeToLiveSet()) {
                            descriptionToCreate.DefaultMessageTimeToLive = new TimeSpan(0, 0, attr.DefaultMessageTimeToLive);
                        }
                        descriptionToCreate.EnableBatchedOperations = attr.EnableBatchedOperations;
                        descriptionToCreate.EnableDeadLetteringOnMessageExpiration = attr.EnableDeadLetteringOnMessageExpiration;
                        if (attr.LockDurationSet()) {
                            descriptionToCreate.LockDuration = new TimeSpan(0, 0, attr.LockDuration);
                        }
                    }

                    try {
                        logger.Info("CreateSubscription CreateTopic {0} ", value.SubscriptionName);
                        var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
                        retryPolicy.ExecuteAction(() => {
                            desc = namespaceManager.CreateSubscription(descriptionToCreate, filter);
                        });
                    }
                    catch (MessagingEntityAlreadyExistsException) {
                        logger.Info("CreateSubscription GetTopic {0} ", value.SubscriptionName);
                        // A item under the same name was already created by someone else, perhaps by another instance. Let's just use it.
                        retryPolicy.ExecuteAction(() => {
                            desc = namespaceManager.GetSubscription(topic.Path, value.SubscriptionName);
                        });
                    }
                }

                SubscriptionClient subscriptionClient = null;
                var rm = ReceiveMode.PeekLock;

                if (value.AttributeData != null) {
                    rm = value.AttributeData.ReceiveMode;
                }

                retryPolicy.ExecuteAction(() => {
                    subscriptionClient = factory.CreateSubscriptionClient(topic.Path, value.SubscriptionName, rm);
                });

                if (value.AttributeData != null && value.AttributeData.PrefetchCountSet()) {
                    subscriptionClient.PrefetchCount = value.AttributeData.PrefetchCount;
                }

                var state = new AzureBusReceiverState() {
                    Client = subscriptionClient,
                    EndPointData = value,
                    Subscription = desc
                };


                var helper = new AzureReceiverHelper(retryPolicy, state);
                mappings.Add(helper);
                helper.ProcessMessagesForSubscription();

            } //lock end

        }
        public void CancelSubscription(ServiceBusEnpointData value) {
            Guard.ArgumentNotNull(value, "value");

            logger.Info("CancelSubscription {0} Declared {1} MessageTytpe {2}, IsReusable {3}", value.SubscriptionName, value.DeclaredType.ToString(), value.MessageType.ToString(), value.IsReusable);

            var subscription = mappings.FirstOrDefault(item => item.Data.EndPointData.SubscriptionName.Equals(value.SubscriptionName, StringComparison.OrdinalIgnoreCase));

            if (subscription == null) {
                logger.Info("CancelSubscription Does not exist {0}", value.SubscriptionName);
                return;
            }

            subscription.Data.Cancel();

            Task t = Task.Factory.StartNew(() => {
                //HACK find better way to wait for a cancel request so we are not blocking.
                logger.Info("CancelSubscription Deleting {0}", value.SubscriptionName);
                for (int i = 0; i < 100; i++) {
                    if (!subscription.Data.Cancelled) {
                        Thread.Sleep(1000);
                    }
                    else {
                        break;
                    }
                }

                if (namespaceManager.SubscriptionExists(topic.Path, value.SubscriptionName)) {
                    var filter = new SqlFilter(string.Format(TYPE_HEADER_NAME + " = '{0}'", value.MessageType.FullName.Replace('.', '_')));
                    retryPolicy.ExecuteAction(() => namespaceManager.DeleteSubscription(topic.Path, value.SubscriptionName));
                    logger.Info("CancelSubscription Deleted {0}", value.SubscriptionName);
                }
            });

            try {
                Task.WaitAny(t);
            }
            catch (Exception ex) {
                if (ex is AggregateException) {
                    //do nothing
                }
                else {
                    throw;
                }
            }
        }