Exemplo n.º 1
0
        public void HandleSubscribe_ThrowsEmailAlreadyTakenException_WhenEmailIsAlreadyTaken()
        {
            //Arrange
            SubscribeCommand command = new SubscribeCommand(
                fixture.Create <string>(),
                fixture.Create <string>(),
                fixture.Create <string>(),
                "*****@*****.**",
                fixture.Create <string>()
                );

            CancellationToken token = new CancellationToken();

            userReadRepository.GetByEmail(Arg.Is(command.Email)).Returns(
                new Budget.Users.Domain.ReadModel.User(
                    Guid.NewGuid(),
                    fixture.Create <string>(),
                    fixture.Create <string>(),
                    fixture.Create <string>(),
                    fixture.Create <string>(),
                    fixture.Create <DateTime>()
                    )
                );

            //Act
            Assert.ThrowsAsync <UsernameAlreadyTakenException>(() => handler.Handle(command, token));

            //Assert
        }
Exemplo n.º 2
0
        public void SubscribeCommandReceiveAndForgetTest()
        {
            var subscribeCommand = new SubscribeCommand("receiveandforget");

            Assert.IsTrue(subscribeCommand.IsValid);
            Assert.AreEqual(SubscriptionType.ReceiveAndForget, subscribeCommand.SubscriptionType);
        }
Exemplo n.º 3
0
        public void Subscribe_ReturnsStatus201_WhenSusbcriptionWorks()
        {
            //Arrange
            SubscribeCommand command = fixture.Create <SubscribeCommand>();

            //Act
            Task <ActionResult> task = controller.Subscribe(command);

            task.Wait();

            ActionResult response = task.Result;

            //Assert
            mediator.Received(1).Send(Arg.Is(command));

            response.Should().NotBeNull();
            response.Should().BeOfType <CreatedAtRouteResult>();

            CreatedAtRouteResult result = response as CreatedAtRouteResult;

            result.StatusCode.Should().Be(StatusCodes.Status201Created);

            result.Value.Should().NotBeNull();
            result.Value.Should().BeOfType <GetUserByUserNameRequest>();
            GetUserByUserNameRequest resultValue = result.Value as GetUserByUserNameRequest;

            resultValue.UserName.Should().Be(command.UserName);
        }
Exemplo n.º 4
0
        public async Task UserData_Information_SubscriptionTests()
        {
            //ensure users with no subscriptions don't error out
            var noSubUserName = "******";

            TestDataInitializer.CreateUser(noSubUserName);

            var userData = new Domain.UserData(noSubUserName);

            //var userData = new Domain.UserData(noSubUserName);
            Assert.AreEqual(0, userData.SubverseSubscriptions.Count());
            Assert.AreEqual(false, userData.HasSubscriptions());
            Assert.AreEqual(false, userData.HasSubscriptions(DomainType.Subverse));

            //test subscription
            var subUserName = "******";

            TestDataInitializer.CreateUser(subUserName);

            var user = TestHelper.SetPrincipal(subUserName);
            var cmd  = new SubscribeCommand(new DomainReference(DomainType.Subverse, SUBVERSES.Unit), Domain.Models.SubscriptionAction.Subscribe).SetUserContext(user);
            var x    = await cmd.Execute();

            VoatAssert.IsValid(x);

            userData = new Domain.UserData(subUserName);

            Assert.AreEqual(1, userData.SubverseSubscriptions.Count());
            Assert.AreEqual(SUBVERSES.Unit, userData.SubverseSubscriptions.First());
            Assert.AreEqual(true, userData.HasSubscriptions());
            Assert.AreEqual(true, userData.HasSubscriptions(DomainType.Subverse));
            Assert.AreEqual(true, userData.IsUserSubverseSubscriber(SUBVERSES.Unit));
        }
Exemplo n.º 5
0
        public void SubscribeCommandPeekAndCommitTest()
        {
            var subscribeCommand = new SubscribeCommand("peekandcommit");

            Assert.IsTrue(subscribeCommand.IsValid);
            Assert.AreEqual(SubscriptionType.PeekAndCommit, subscribeCommand.SubscriptionType);
        }
Exemplo n.º 6
0
        public async Task CreateSet_Test()
        {
            var userName = "******";
            var user     = TestHelper.SetPrincipal(userName);

            var set = new Set()
            {
                Name = "HolyHell", Title = "Some Title", Type = SetType.Normal, UserName = userName
            };
            var cmd    = new UpdateSetCommand(set).SetUserContext(user);
            var result = await cmd.Execute();

            VoatAssert.IsValid(result);

            Assert.AreNotEqual(0, result.Response.ID);
            var setID = result.Response.ID;

            VerifySubscriber(set, userName, 1);

            //Subscribe another user
            userName = "******";
            user     = TestHelper.SetPrincipal(userName);
            var subCmd    = new SubscribeCommand(new DomainReference(DomainType.Set, set.Name, set.UserName), SubscriptionAction.Subscribe).SetUserContext(user);
            var subResult = await subCmd.Execute();

            VoatAssert.IsValid(result);
            VerifySubscriber(set, userName, 2);

            //unsub user
            subCmd    = new SubscribeCommand(new DomainReference(DomainType.Set, set.Name, set.UserName), SubscriptionAction.Unsubscribe).SetUserContext(user);
            subResult = await subCmd.Execute();

            VoatAssert.IsValid(result);
            VerifySubscriber(set, userName, 1, false);
        }
Exemplo n.º 7
0
        public async Task <ActionResult> Subscribe([FromBody] SubscribeCommand subscription)
        {
            ActionResult response = new StatusCodeResult(StatusCodes.Status422UnprocessableEntity);

            try
            {
                await mediator.Send(subscription);

                var request = new GetUserByUserNameRequest(subscription.UserName);
                response = CreatedAtRoute("GetUserByUserName", request, request);
            }
            catch (UserApplicationException ex) when(ex is UsernameAlreadyTakenException || ex is EmailAlreadyTakenException)
            {
                response = Conflict(ex.Message);
            }
            catch (Exception ex) when(ex is FormatException || ex is ArgumentException || ex is ArgumentNullException)
            {
                response = BadRequest();
            }
            catch
            {
                response = new StatusCodeResult(StatusCodes.Status500InternalServerError);
            }

            return(response);
        }
Exemplo n.º 8
0
        private void HandleSubscribeCommand(SubscribeCommand subscribeCommand)
        {
            if (!_connection.ConnectionState.HasFlag(ConnectionState.LoggedIn))
            {
                _connection.Reply("subscribe unauthorized");
                return;
            }

            if (_connection.ConnectionState.HasFlag(ConnectionState.Subscribed))
            {
                _connection.Reply("subscribe already");
                _connection.Heartbeat();
                return;
            }

            if (!Enum.IsDefined(typeof(SubscriptionType), subscribeCommand.SubscriptionType) || subscribeCommand.SubscriptionType == SubscriptionType.None)
            {
                _connection.Reply("subscribe badcommand");
                return;
            }

            _connectionRegistry.PromoteToSubscribedConnection(_connection.DeviceId, subscribeCommand.SubscriptionType);
            _connection.Reply("subscribe ack");
            _connection.Heartbeat();
        }
Exemplo n.º 9
0
        public void HandleSubscribe_CreatesUser_ThenSavesItAndPublishesEvents()
        {
            //Arrange
            SubscribeCommand command = new SubscribeCommand(
                fixture.Create <string>(),
                fixture.Create <string>(),
                fixture.Create <string>(),
                "*****@*****.**",
                fixture.Create <string>()
                );

            CancellationToken token = new CancellationToken();

            //Act
            Task task = handler.Handle(command, token);

            task.Wait();

            //Assert
            cryptService.Received(1).Crypt(Arg.Is(command.Password)); //Called by the factory

            writeModelUnitOfWork.Received(1).BeginTransaction();
            writeModelUnitOfWork.Received(1).Commit();

            userWriteRepository.Received(1).Save(Arg.Is <User>(u =>
                                                               u.UserName == command.UserName &&
                                                               u.FirstName == command.FirstName &&
                                                               u.LastName == command.LastName &&
                                                               u.Email.Address == command.Email
                                                               ));

            eventPublisher.Received(1).PublishNewEvents(Arg.Is <User>(u => u.UserName == command.UserName));
        }
Exemplo n.º 10
0
        public void Subscribe <TValue>(Action <string> action)
        {
            var key     = typeof(TValue);
            var state   = _subscriberState.GetOrAdd(key, k => new SubscriberState());
            var command = new SubscribeCommand(state, action);

            _processor.ExecuteAndForget(key, command);
        }
Exemplo n.º 11
0
 public virtual void ProcessSubscribeCommand(SubscribeCommand cmd)
 {
     this.Session.AppendResponse(
         new ServerStatusResponse(cmd.Tag,
                                  ServerStatusResponseType.NO,
                                  "SUBSCRIBE State Error")
         );
 }
Exemplo n.º 12
0
 public override void ProcessSubscribeCommand(SubscribeCommand cmd)
 {
     this.Session.AppendResponse(
         new ServerStatusResponse(cmd.Tag,
                                  ServerStatusResponseType.NO,
                                  "SUBSCRIBE is unsupportted yet")
         );
 }
Exemplo n.º 13
0
 private void RaiseCommandExecutes()
 {
     StopPriceSourceCommand.RaiseCanExecuteChanged();
     StartPriceSourceCommand.RaiseCanExecuteChanged();
     SubscribeCommand.RaiseCanExecuteChanged();
     UnsubscribeCommand.RaiseCanExecuteChanged();
     SubscribeAllCommand.RaiseCanExecuteChanged();
     UnsubscribeAllCommand.RaiseCanExecuteChanged();
 }
        /// <summary>
        /// Подписка на оповещение по типу сообщения для сокета
        /// </summary>
        /// <param name="webSocket"></param>
        /// <param name="command"></param>
        public void SubscribeMessage(WebSocket webSocket, SubscribeCommand command)
        {
            if (!_connectionSockets.TryGetValue(webSocket, out var messageTypes))
            {
                return;
            }

            messageTypes.Add(command.MessageType);
        }
Exemplo n.º 15
0
        public async Task <JsonResult> Subscribe(Domain.Models.DomainType domainType, string name, Domain.Models.SubscriptionAction subscribeAction)
        {
            var domainReference = Domain.Models.DomainReference.Parse(name, domainType);

            var cmd    = new SubscribeCommand(domainReference, subscribeAction).SetUserContext(User);
            var result = await cmd.Execute();

            return(JsonResult(result));
        }
Exemplo n.º 16
0
        private async void OnUnsubscribeCommand()
        {
            canSubscribe = true;
            SubscribeCommand.RaiseCanExecuteChanged();
            canUnsubscribe = false;
            UnsubscribeCommand.RaiseCanExecuteChanged();

            await hub.Invoke <int>("Unsubscribe", new object[] { ClientId });

            if (connection.State == ConnectionState.Connected)
            {
                connection.Stop();
            }
        }
Exemplo n.º 17
0
        public async void SubscribeBook_Fail(Guid bookId, string bookName, Guid userId)
        {
            var mockUnitOfWork = new Mock <IUnitOfWork>();

            mockUnitOfWork.Setup(a => a.SaveAsync());
            var addBookCommandHandler = new SubscribeCommandHandler(_repositoryMock, mockUnitOfWork.Object);
            var addBookCommand        = new SubscribeCommand
            {
                BookId   = bookId,
                BookName = bookName,
                UserId   = userId
            };

            await Assert.ThrowsAsync <ValidateException>(() => addBookCommandHandler.HandleAsync(addBookCommand));
        }
Exemplo n.º 18
0
        public void WhenSubscribingItChecksPrefixOfMessageFilter(string filter, string destination, Type message)
        {
            MessageSinkStub sink = new MessageSinkStub();

            RouteManager.AddRoute(filter, destination);

            // Act
            Service.Subscribe(message, sink);

            // Assert
            Assert.AreEqual(destination, sink.LastDestination.Name);
            Assert.IsInstanceOf <SubscribeCommand>(sink.LastMessage.Body);
            SubscribeCommand sc = (SubscribeCommand)sink.LastMessage.Body;

            Assert.AreEqual(message.AssemblyQualifiedName, sc.SubscribedMessagesTypeName);
        }
Exemplo n.º 19
0
        public void ItCanHandleSubscribeMessage()
        {
            // Arrange
            SubscriptionMessageHandlers handlers = new SubscriptionMessageHandlers {
                SubscriptionService = Service
            };
            SubscribeCommand cmd = new SubscribeCommand(typeof(MessageToSubscribe1), "WhollyBob");

            // Act
            handlers.Handle(cmd);

            // Assert
            IList <QueueName> subscribers = Service.GetSubscribers(typeof(MessageToSubscribe1)).ToList();

            Assert.AreEqual(1, subscribers.Count);
            Assert.AreEqual(new QueueName("WhollyBob"), subscribers[0]);
        }
        public async Task <JsonResult> UnSubscribe(string subverseName)
        {
            //var loggedInUser = User.Identity.Name;

            //Voat.Utilities.UserHelper.UnSubscribeFromSubverse(loggedInUser, subverseName);
            //return Json("Unsubscribe request was successful." /* CORE_PORT: Removed , JsonRequestBehavior.AllowGet */);
            var cmd = new SubscribeCommand(new Domain.Models.DomainReference(Domain.Models.DomainType.Subverse, subverseName), Domain.Models.SubscriptionAction.Unsubscribe).SetUserContext(User);
            var r   = await cmd.Execute();

            if (r.Success)
            {
                return(Json("Unsubscribe request was successful." /* CORE_PORT: Removed , JsonRequestBehavior.AllowGet */));
            }
            else
            {
                return(Json(r.Message /* CORE_PORT: Removed , JsonRequestBehavior.AllowGet */));
            }
        }
Exemplo n.º 21
0
    public async Task <Result <SubscriptionDto> > Handle(SubscribeCommand command, CancellationToken cancellationToken)
    {
        var subscription = await _context.Subscriptions.Include(x => x.Subreddit)
                           .FirstOrDefaultAsync(subscription => subscription.SubredditId == command.SubredditId && subscription.Sort == command.Sort, cancellationToken);

        if (subscription == null)
        {
            subscription = _mapper.Map <Subscription>(command);
            await _context.Subscriptions.AddAsync(subscription, cancellationToken);

            subscription.Subreddit = await _context.Subreddits.FirstOrDefaultAsync(x => x.Id == command.SubredditId, cancellationToken);
        }

        var textChannel = await _context.GuildChannels.Include(x => x.ChannelSubscriptions).FirstOrDefaultAsync(guildChannel => guildChannel.Id == command.ChannelId, cancellationToken);

        if (textChannel == null)
        {
            throw new ArgumentNullException(nameof(textChannel));
        }

        if (textChannel.ChannelSubscriptions.Any(channelSubscripiton => channelSubscripiton.SubscriptionId == subscription.Id))
        {
            return(await Result <SubscriptionDto> .FailAsync("Already subscribed!"));
        }

        var guild = await _context.Guilds.Include(x => x.GuildSetting).Include(x => x.GuildChannels).ThenInclude(x => x.ChannelSubscriptions).FirstOrDefaultAsync(x => x.Id == textChannel.GuildId, cancellationToken);

        var count = guild.GuildChannels.SelectMany(x => x.ChannelSubscriptions).Count();

        if (count >= guild.GuildSetting.MaxSubscriptions)
        {
            return(await Result <SubscriptionDto> .FailAsync("Max subscriptions reached"));
        }

        await _context.ChannelSubscriptions.AddAsync(new ChannelSubscription
        {
            GuildChannelId = command.ChannelId,
            SubscriptionId = subscription.Id,
        }, cancellationToken);

        await _context.SaveChangesAsync(cancellationToken);

        return(await _mediator.Send(new GetSubscriptionByIdQuery(subscription.Id)));
    }
Exemplo n.º 22
0
        public void Constructor_AssignsProperties()
        {
            //Arrange
            string userName  = fixture.Create <string>();
            string firstName = fixture.Create <string>();
            string lastName  = fixture.Create <string>();
            string email     = fixture.Create <string>();
            string password  = fixture.Create <string>();

            //Act
            SubscribeCommand command = new SubscribeCommand(userName, firstName, lastName, email, password);

            //Assert
            command.UserName.Should().Be(userName);
            command.FirstName.Should().Be(firstName);
            command.LastName.Should().Be(lastName);
            command.Email.Should().Be(email);
            command.Password.Should().Be(password);
        }
Exemplo n.º 23
0
        public void WhenSubscribingItFollowsMatchingRoutes()
        {
            // Arrange
            MessageSinkStub sink = new MessageSinkStub();

            RouteManager.AddRoute("Xyperico.Agres.Tests.MessageBus", "Trilian");
            RouteManager.AddRoute("Rofl.abc", "Max");

            // Act
            Service.Subscribe(typeof(MessageToSubscribe1), sink);

            // Assert
            Assert.AreEqual("Trilian", sink.LastDestination.Name);
            Assert.IsInstanceOf <SubscribeCommand>(sink.LastMessage.Body);
            SubscribeCommand sc = (SubscribeCommand)sink.LastMessage.Body;

            Assert.AreEqual(MyQueueName.Name, sc.SubscriberQueueName);
            Assert.AreEqual(typeof(MessageToSubscribe1).AssemblyQualifiedName, sc.SubscribedMessagesTypeName);
        }
Exemplo n.º 24
0
        public void Subscribe_ReturnsBadRequest_WhenArgumentNullExceptionOccurs()
        {
            //Arrange
            SubscribeCommand command = fixture.Create <SubscribeCommand>();

            mediator.When(
                m => m.Send(Arg.Is(command))
                ).Do(args => throw new ArgumentNullException());

            //Act
            Task <ActionResult> task = controller.Subscribe(command);

            task.Wait();

            ActionResult response = task.Result;

            //Assert
            response.Should().NotBeNull();
            response.Should().BeOfType <BadRequestResult>();
        }
Exemplo n.º 25
0
        public void HandleSubscribe_RollbacksTransaction_WhenExceptionOccur()
        {
            //Arrange
            SubscribeCommand command = new SubscribeCommand(
                fixture.Create <string>(),
                fixture.Create <string>(),
                fixture.Create <string>(),
                "wololoo",
                fixture.Create <string>()
                );

            CancellationToken token = new CancellationToken();

            //Act
            handler.Handle(command, token);

            //Assert
            writeModelUnitOfWork.Received(1).BeginTransaction();
            writeModelUnitOfWork.Received(1).Rollback();
        }
Exemplo n.º 26
0
        public async Task <IActionResult> SubscribeCommand([FromBody] SubscribeDto value, [FromHeader] Guid userId)
        {
            _logger.LogInformation("Subscribe for user:{0}, bookid:{1} ", userId, value.BookId);
            var book = await _client.GetRequest(new BookDto(), $"{_options.Value.CatalogueUrl}{_options.Value.BookQueryPath}{value.BookId}");

            if (book == null)
            {
                throw new InvalidDataException("book provided does not exist");
            }
            var command = new SubscribeCommand
            {
                BookId   = value.BookId,
                BookName = book.Name,
                UserId   = userId
            };
            await _mediator.DispatchAsync(command);

            _logger.LogInformation("Subscribed for user:{0}, bookid:{1} ", userId, value.BookId);
            return(Ok());
        }
Exemplo n.º 27
0
        public void Subscribe_ReturnsConflict_WhenEmailAlreadyTaken()
        {
            //Arrange
            SubscribeCommand command = fixture.Create <SubscribeCommand>();

            mediator.When(
                m => m.Send(Arg.Is(command))
                ).Do(args => throw new EmailAlreadyTakenException());

            //Act
            Task <ActionResult> task = controller.Subscribe(command);

            task.Wait();

            ActionResult response = task.Result;

            //Assert
            response.Should().NotBeNull();
            response.Should().BeOfType <ConflictObjectResult>();
        }
Exemplo n.º 28
0
        public async void SubscribeBook_Success()
        {
            var mockUnitOfWork = new Mock <IUnitOfWork>();

            mockUnitOfWork.Setup(a => a.SaveAsync());
            var commandHandler = new SubscribeCommandHandler(_repositoryMock, mockUnitOfWork.Object);
            var command        = new SubscribeCommand
            {
                BookId   = Guid.NewGuid(),
                BookName = "Test 1",
                UserId   = Guid.NewGuid()
            };

            await commandHandler.HandleAsync(command);

            var dbCheck = _repositoryMock as MockBookRepository <Domain.Entities.Subscription>;

            Assert.Single(dbCheck.Table);
            Assert.Contains(dbCheck.Table.Values, a => a.UserId == command.UserId && a.BookId == command.BookId && a.BookName == command.BookName);
        }
Exemplo n.º 29
0
        private async void OnSubscribeCommand()
        {
            canSubscribe = false;
            SubscribeCommand.RaiseCanExecuteChanged();
            canUnsubscribe = true;
            UnsubscribeCommand.RaiseCanExecuteChanged();

            if (connection.State != ConnectionState.Connected)
            {
                await connection.Start();
            }

            try
            {
                await hub.Invoke <int>("Subscribe", new object[] { ClientId });
            }
            catch (Exception ex)
            {
                Message = ex.Message;
            }
        }
Exemplo n.º 30
0
        public async Task <IActionResult> OnGet()
        {
            if (TempData.Peek <UserRegistration>("UserRegistration") == null)
            {
                await _mediator.Send(new ThrowAlertCommand(AlertType.DANGER, $"An Error Has Occurred", "An error has occurred during user onboarding. Please contact support."));

                return(RedirectToPage("~/Error"));
            }

            var subscriptionReg = TempData.Get <UserRegistration>("UserRegistration");

            if (subscriptionReg == null)
            {
                await _mediator.Send(new ThrowAlertCommand(AlertType.DANGER, "Registration issue", "There was an issue with setting up your subscription."));

                return(RedirectToPage("/Account/Register"));
            }

            Instructor = await _mediator.Send(new GetAppProfileByIdQuery(subscriptionReg.InstructorId));

            // check if provided id is an instructor
            if (Instructor.IsInstructor())
            {
                // get subscriptions
                SubscriptionOptions = await _mediator.Send(new GetInstructorSubscriptionsQuery(subscriptionReg.InstructorId));

                Data = new SubscribeCommand {
                    InstructorId = Instructor.Id,
                    ProfileId    = subscriptionReg.ProfileId
                };
                return(Page());
            }
            else
            {
                // redirect to default registration page
                await _mediator.Send(new ThrowAlertCommand(AlertType.WARNING, "Instructor Not Found", "There is no instructor that matches the instructor Id provided."));

                return(RedirectToPage("/Account/Register"));
            }
        }