Exemple #1
0
        public void EnsureImAbleToAddAndRetrieveSubscriptions()
        {
            var subscriptionManager = new SubscriptionManager();
            var subscriptions       = new List <ISubscription>()
            {
                subscriptionManager.AddSubscription <EventOne>(),
                subscriptionManager.AddSubscription <EventTwo>(),
                subscriptionManager.AddSubscription <EventThree>(),
                new Subscription <Event>()
            };

            Assert.IsTrue(subscriptions.Contains(subscriptionManager.FindSubscription <EventOne>()));
            Assert.IsTrue(subscriptions.Contains(subscriptionManager.FindSubscription <EventTwo>()));
            Assert.IsTrue(subscriptions.Contains(subscriptionManager.FindSubscription <EventThree>()));
            Assert.IsFalse(subscriptions.Contains(subscriptionManager.FindSubscription <Event>()));
        }
Exemple #2
0
        public Task <ResponseBase> Handle(HttpInformation context, SubscribeCommand command,
                                          ExecutionContext executionContext)
        {
            if (databaseOptions.DisableIncludePrefilter && command.Prefilters.Any(p => p is IncludePrefilter))
            {
                throw new IncludeNotAllowedException(command.ContextName, command.CollectionName);
            }

            if (databaseOptions.DisableSelectPrefilter && command.Prefilters.Any(p => p is SelectPrefilter))
            {
                throw new SelectNotAllowedException(command.ContextName, command.CollectionName);
            }

            SapphireDbContext           db       = GetContext(command.ContextName);
            KeyValuePair <Type, string> property = CollectionHelper.GetCollectionType(db, command);

            if (property.Key.GetModelAttributesInfo().DisableQueryAttribute != null)
            {
                throw new OperationDisabledException("Query", command.ContextName, command.CollectionName);
            }

            command.Prefilters.ForEach(prefilter => prefilter.Initialize(property.Key));
            ResponseBase response = CollectionHelper.GetCollection(db, command, property, command.Prefilters, context, serviceProvider);

            subscriptionManager.AddSubscription(command.ContextName, command.CollectionName, command.Prefilters, Connection, command.ReferenceId);

            return(Task.FromResult(response));
        }
        public void SuccessfulyAddNewSubsription()
        {
            var subsriptionManager = new SubscriptionManager();

            subsriptionManager.AddSubscription(Mock.Of <IChannel>(), new [] { "topic" });

            Assert.IsTrue(true);
        }
        public void ReturnChannelsByTopic()
        {
            var subsriptionManager = new SubscriptionManager();

            var ch1 = new Mock <IChannel>();

            ch1.Setup(c => c.IsOpened).Returns(true);

            subsriptionManager.AddSubscription(ch1.Object, new[] { "topic1", "topic2" });
            subsriptionManager.AddSubscription(Mock.Of <IChannel>(), new[] { "topic1" });
            subsriptionManager.AddSubscription(Mock.Of <IChannel>(), new[] { "topic3" });

            var channels = subsriptionManager.GetChannelsByTopic("topic1");


            Assert.AreEqual(1, channels.Length);
            Assert.AreEqual(ch1.Object, channels[0]);
        }
Exemple #5
0
        public void Any_Empty_True()
        {
            // Arrange
            var subscription = new SubscriptionManager();

            subscription.AddSubscription <UserCreatedEvent, UserEventHandler>();

            // Act & Assert
            Assert.True(subscription.Any());
        }
        public void SubscriptionAddTest()
        {
            var subscription = new Subscription()
            {
                SubscriptionId = Guid.NewGuid(),
                StartDate      = DateTime.Now,
                EndDate        = DateTime.Now.AddDays(90),
                Price          = 1000
            };

            _subManager.AddSubscription(subscription);
        }
        public Task<ResponseBase> Handle(HttpInformation context, SubscribeCommand command)
        {
            ResponseBase response = CollectionHelper.GetCollection(GetContext(command.ContextName), command, context, serviceProvider);

            if (response.Error == null)
            {
                subscriptionManager.AddSubscription(command.ContextName, command.CollectionName, command.Prefilters,
                    Connection, command.ReferenceId);
            }

            return Task.FromResult(response);
        }
Exemple #8
0
        public void Subscribe <TMessage, THandler>()
            where TMessage : BusMessage
            where THandler : IMessageHandler <TMessage>
        {
            var routingKey = GetRoutingKey <TMessage>();

            // add subscription
            _subscriptionManager.AddSubscription(routingKey, typeof(TMessage), typeof(THandler));

            // start consume
            StartConsuming(routingKey);
        }
Exemple #9
0
        /// <summary> 订阅消息 </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TH"></typeparam>
        /// <param name="handler"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public override Task Subscribe <T, TH>(Func <TH> handler, SubscribeOption option = null)
        {
            _consumerChannel = _consumerChannel ?? CreateConsumerChannel();

            var opt = (option ?? GetSubscription(typeof(TH))) as RabbitMqSubscribeOption ??
                      new RabbitMqSubscribeOption();

            if (opt.PrefetchCount > 0)
            {
                //同时只能接受1条消息
                _consumerChannel.BasicQos(0, (ushort)opt.PrefetchCount, false);
            }

            var    queue    = opt.Queue;
            var    dataType = typeof(T);
            string key;

            if (typeof(DEvent).IsAssignableFrom(dataType))
            {
                key = !string.IsNullOrWhiteSpace(opt.RouteKey)
                    ? opt.RouteKey
                    : typeof(T).GetRouteKey();
            }
            else
            {
                key = string.IsNullOrWhiteSpace(opt.RouteKey) ? opt.Queue : opt.RouteKey;
            }

            DeclareAndBindQueue(queue, key, opt);
            if (!_connection.IsConnected)
            {
                _connection.TryConnect();
            }

            var consumer = new EventingBasicConsumer(_consumerChannel);

            consumer.Received += async(model, ea) =>
            {
                try
                {
                    await ReceiveMessage(queue, ea, opt);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"MQ订阅处理异常:{ex.Message}");
                }
            };

            _consumerChannel.BasicConsume(queue, false, consumer);

            SubscriptionManager.AddSubscription <T, TH>(handler, queue);
            return(Task.CompletedTask);
        }
Exemple #10
0
        public void AddSubscription_EventHasNotSubscription_HandlerNotEmpty()
        {
            // Arrange
            var subscription = new SubscriptionManager();

            // Act
            subscription.AddSubscription <UserCreatedEvent, UserEventHandler>();

            // Assert
            var subscriptionEvent = subscription.FindSubscription <UserCreatedEvent, UserEventHandler>();

            Assert.NotNull(subscriptionEvent);
        }
Exemple #11
0
        public void Clear_Subscriptions_Empty()
        {
            // Arrange
            var subscription = new SubscriptionManager();

            subscription.AddSubscription <UserCreatedEvent, UserEventHandler>();

            // Act
            subscription.Clear();

            // Assert
            Assert.False(subscription.Any());
        }
Exemple #12
0
        public void GetHandlers_EventRegistered_EventHandlers()
        {
            // Arrange
            var subscription = new SubscriptionManager();

            subscription.AddSubscription <UserCreatedEvent, UserEventHandler>();

            // Act
            var handlers = subscription.GetHandlers <UserCreatedEvent>();

            // Assert
            Assert.Contains(handlers, handler => handler.EventHandlerType == typeof(UserEventHandler));
        }
Exemple #13
0
        public void HasSubscriptionsForEvent_EventRegistered_True()
        {
            // Arrange
            var subscription = new SubscriptionManager();

            subscription.AddSubscription <UserCreatedEvent, UserEventHandler>();

            // Act
            var hasSubscription = subscription.HasSubscriptionsForEvent <UserCreatedEvent>();

            // Assert
            Assert.True(hasSubscription);
        }
Exemple #14
0
        public void RemoveSubscription_EventRegistered_NotRemove()
        {
            // Arrange
            var subscription = new SubscriptionManager();

            subscription.AddSubscription <UserCreatedEvent, UserEventHandler>();

            // Act
            subscription.RemoveSubscription <UserCreatedEvent, UserEventHandler>();

            // Assert
            Assert.False(subscription.Any());
        }
        public Task <ResponseBase> Handle(HttpInformation context, SubscribeQueryCommand queryCommand,
                                          ExecutionContext executionContext)
        {
            SapphireDbContext           db       = GetContext(queryCommand.ContextName);
            KeyValuePair <Type, string> property = CollectionHelper.GetCollectionType(db, queryCommand);

            List <IPrefilterBase> prefilters =
                CollectionHelper.GetQueryPrefilters(property, queryCommand, Connection.Information, serviceProvider);

            ResponseBase response = CollectionHelper.GetCollection(db, queryCommand, property, prefilters, context, serviceProvider);

            subscriptionManager.AddSubscription(queryCommand.ContextName, queryCommand.CollectionName, prefilters, Connection, queryCommand.ReferenceId);

            return(Task.FromResult(response));
        }
Exemple #16
0
        public void FindSubscription_EventHasSubscription_Subscription()
        {
            // Arrange
            var subscription = new SubscriptionManager();

            subscription.AddSubscription <UserCreatedEvent, UserEventHandler>();

            // Act
            var subscriptionEvent = subscription.FindSubscription <UserCreatedEvent, UserEventHandler>();

            // Assert
            Assert.NotNull(subscriptionEvent);
            Assert.Equal(typeof(UserCreatedEvent), subscriptionEvent.EventType);
            Assert.Equal(typeof(UserEventHandler), subscriptionEvent.EventHandlerType);
            Assert.Equal(typeof(UserCreatedEvent).Name, subscriptionEvent.EventName);
        }
Exemple #17
0
        public void AddSubscription_EventHasSubscription_EventHandlerAlreadyRegisteredException()
        {
            // Arrange
            var eventType        = typeof(UserCreatedEvent);
            var eventHandlerType = typeof(UserEventHandler);
            var subscription     = new SubscriptionManager();

            subscription.AddSubscription <UserCreatedEvent, UserEventHandler>();

            // Act & Assert
            var exception = Assert.Throws <EventHandlerAlreadyRegisteredException <UserCreatedEvent, UserEventHandler> >(() => subscription.AddSubscription <UserCreatedEvent, UserEventHandler>());

            // Assert
            Assert.NotEmpty(exception.Message);
            Assert.Equal(eventType, exception.EventType);
            Assert.Equal(eventHandlerType, exception.EventHandlerType);
        }
Exemple #18
0
        public void FindSubscriptions_EventHasSubscription_Subscriptions()
        {
            // Arrange
            var subscription = new SubscriptionManager();

            subscription.AddSubscription <UserCreatedEvent, UserEventHandler>();

            // Act
            var subscriptionsEvents = subscription.FindSubscriptions <UserCreatedEvent>();

            // Assert
            Assert.NotEmpty(subscriptionsEvents);
            Assert.Contains(subscriptionsEvents, x =>
                            x.EventType == typeof(UserCreatedEvent) &&
                            x.EventHandlerType == typeof(UserEventHandler) &&
                            x.EventName == typeof(UserCreatedEvent).Name
                            );
        }
 public void Subscribe <TEvent, TEventHandler>() where TEvent : Event where TEventHandler : IEventHandler <TEvent>
 {
     _subscriptionManager.AddSubscription <TEvent, TEventHandler>();
 }
 public CampaignStockCheckHandler(IRepository <Sale> saleRepository, IRepository <Campaign> campaignRepository, SubscriptionManager subscriptionManager)
 {
     _saleRepository     = saleRepository;
     _campaignRepository = campaignRepository;
     subscriptionManager.AddSubscription <NewProductOrderCreatedEvent, CampaignStockCheckHandler>();
 }
 public NewOrderCreatedEventHandler(IRepository <Sale> saleRepository, IRepository <Product> productRepository, SubscriptionManager subscriptionManager)
 {
     _saleRepository    = saleRepository;
     _productRepository = productRepository;
     subscriptionManager.AddSubscription <NewProductOrderCreatedEvent, NewOrderCreatedEventHandler>();
 }
Exemple #22
0
        public async Task <TaskModuleContinueResponse> OnTeamsTaskModuleSubmitAsync(ITurnContext context, CancellationToken cancellationToken)
        {
            var state = await _stateAccessor.GetAsync(context, () => new SkillState());

            var activityValueObject = JObject.FromObject(context.Activity.Value);

            var     isDataObject = activityValueObject.TryGetValue("data", StringComparison.InvariantCultureIgnoreCase, out JToken dataValue);
            JObject dataObject   = null;

            if (isDataObject)
            {
                dataObject = dataValue as JObject;

                // Get filterUrgency
                var filterUrgency = dataObject.GetValue("UrgencyFilter");

                // Get filterName
                var filterName = dataObject.GetValue("FilterName");

                //// Get NotificationNamespace name
                var notificationNameSpace = dataObject.GetValue("NotificationNameSpace");

                //// Get filterName
                var postNotificationAPIName = dataObject.GetValue("PostNotificationAPIName");

                // Check if this BusinessRule is already created if not create proactivesubscription
                var isNewSubscription = await _subscriptionManager.AddSubscription(context, filterName.Value <string>(), context.Activity.GetConversationReference(), cancellationToken);

                // Create Managemenet object
                if (isNewSubscription)
                {
                    var management = _serviceManager.CreateManagementForSubscription(_settings, state.AccessTokenResponse, state.ServiceCache);

                    // Create Subscription New RESTAPI for callback from ServiceNow
                    var response = await management.CreateNewRestMessage(notificationNameSpace.Value <string>(), postNotificationAPIName.Value <string>());

                    // Create Subscription BusinessRule
                    var result = await management.CreateSubscriptionBusinessRule(filterUrgency.Value <string>(), filterName.Value <string>(), notificationNameSpace.Value <string>(), postNotificationAPIName.Value <string>());

                    if (result == System.Net.HttpStatusCode.OK)
                    {
                        var serviceNowSub = new ServiceNowSubscription
                        {
                            FilterName            = filterName.Value <string>(),
                            FilterCondition       = "UrgencyChanges, DescriptionChanges, PriorityChanges, AssignedToChanges",
                            NotificationNameSpace = notificationNameSpace.Value <string>(),
                            NotificationApiName   = postNotificationAPIName.Value <string>(),
                        };
                        ActivityReferenceMap activityReferenceMap = await _activityReferenceMapAccessor.GetAsync(
                            context,
                            () => new ActivityReferenceMap(),
                            cancellationToken)
                                                                    .ConfigureAwait(false);

                        // Return Added Incident Envelope
                        // Get saved Activity Reference mapping to conversation Id
                        activityReferenceMap.TryGetValue(context.Activity.Conversation.Id, out var activityReference);

                        // Update Create Ticket Button with another Adaptive card to Update/Delete Ticket
                        await _teamsTicketUpdateActivity.UpdateTaskModuleActivityAsync(
                            context,
                            activityReference,
                            SubscriptionTaskModuleAdaptiveCard.BuildSubscriptionCard(serviceNowSub, _settings.MicrosoftAppId),
                            cancellationToken);
                    }
                }

                // Create ProactiveModel
                // Get Conversation from Activity
                var conversation = context.Activity.GetConversationReference();

                // ProactiveConversationReferenceMap to save list of conversation
                var proactiveConversationReferenceMap = await _proactiveStateConversationReferenceMapAccessor.GetAsync(
                    context,
                    () => new ConversationReferenceMap(),
                    cancellationToken)
                                                        .ConfigureAwait(false);

                // Get Conversations from map
                proactiveConversationReferenceMap.TryGetValue(filterName.Value <string>(), out var listOfConversationReferences);

                if (listOfConversationReferences == null)
                {
                    proactiveConversationReferenceMap[filterName.Value <string>()] = new List <ConversationReference> {
                        conversation
                    };
                }
                else if (!listOfConversationReferences.Contains(conversation))
                {
                    listOfConversationReferences.Add(conversation);
                    proactiveConversationReferenceMap[filterName.Value <string>()] = listOfConversationReferences;
                }

                // Save ActivityReference and ProactiveState Accessor
                await _proactiveStateConversationReferenceMapAccessor.SetAsync(context, proactiveConversationReferenceMap).ConfigureAwait(false);

                // Save Conversation State
                await _proactiveState.SaveChangesAsync(context, false, cancellationToken);

                await _conversationState.SaveChangesAsync(context, false, cancellationToken);

                return(new TaskModuleContinueResponse()
                {
                    Value = new TaskModuleTaskInfo()
                    {
                        Title = "Subscription",
                        Height = "medium",
                        Width = 500,
                        Card = new Attachment
                        {
                            ContentType = AdaptiveCard.ContentType,
                            Content = SubscriptionTaskModuleAdaptiveCard.SubscriptionResponseCard($"Created Subscription With Business RuleName: {filterName} in ServiceNow")
                        }
                    }
                });
            }

            return(new TaskModuleContinueResponse()
            {
                Value = new TaskModuleTaskInfo()
                {
                    Title = "Subscription",
                    Height = "medium",
                    Width = 500,
                    Card = new Attachment
                    {
                        ContentType = AdaptiveCard.ContentType,
                        Content = SubscriptionTaskModuleAdaptiveCard.SubscriptionResponseCard("Failed To Create Subscription")
                    }
                }
            });
        }
 public CampaignProductUpdateHandler(IRepository <Product> productRepository, IRepository <Campaign> campaignRepository, SubscriptionManager subscriptionManager)
 {
     _productRepository  = productRepository;
     _campaignRepository = campaignRepository;
     subscriptionManager.AddSubscription <UpdateCampaignCurrentManipulationEvent, CampaignProductUpdateHandler>();
 }
Exemple #24
0
 public CampaignDeactivedEventHandler(IRepository <Product> productRepository, SubscriptionManager subscriptionManager)
 {
     _productRepository = productRepository;
     subscriptionManager.AddSubscription <CampaignDeactivedEvent, CampaignDeactivedEventHandler>();
 }
Exemple #25
0
 public SubscriptionToken Subscribe <TEvent, THandler>()
     where TEvent : IntegrationEvent
     where THandler : IIntegrationEventHandler <TEvent>
 {
     return(SubscriptionManager.AddSubscription <TEvent, THandler>());
 }
Exemple #26
0
        public JsonResult Subscription(string mail)
        {
            string proc = SubscriptionManager.AddSubscription(mail);

            return(Json(proc, JsonRequestBehavior.AllowGet));
        }