public async Task Handle(UserOrgAuthStatusChangedEvent message, IMessageHandlerContext context)
        {
            using (LogContext.PushProperty("IntegrationEventContext", $"{message.Id}-{Program.AppName}"))
            {
                _logger.LogInformation("----- Handling UserOrgAuthStatusChangedEvent: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", message.Id, Program.AppName, message);

                #region 设置用户团体认证状态
                var command = new SetOrgAuthStatusCommand {
                    UserId = message.UserId, Status = (AuthStatus)message.Status
                };
                await _mediator.Send(command);

                #endregion

                #region 通知用户
                if (message.Status == 2 || message.Status == 3)
                {
                    var eventCommand = new CreateEventCommand
                    {
                        ToUserId    = message.UserId,
                        EventType   = message.Status == 2 ? EventType.UserOrgAuthSuccess : EventType.UserOrgAuthFailed,
                        PushMessage = message.Status == 2 ? "团体认证成功" : "团体认证未通过"
                    };

                    await _mediator.Send(eventCommand);
                }
                #endregion
            }
        }
Ejemplo n.º 2
0
        public ActionResult <int> Post([FromBody] CreateEventDTO request)
        {
            var command = new CreateEventCommand(_mapper.Map <Event>(request));
            var handler = _commandHandler.Build(command);

            return(Ok(handler.Execute()));
        }
Ejemplo n.º 3
0
        public void CreateEventWithEmptyModel_ThrowsException()
        {
            var cmd     = new CreateEventCommand(_ctx);
            var request = new CreateEventRequest(new ReservationModel());

            Assert.Throws <ArgumentNullException>(() => cmd.Handle(request, CancellationToken.None).Wait());
        }
Ejemplo n.º 4
0
        public async Task <Event> CreateEvent(CreateEventCommand newEvent)
        {
            Event model = new Event();

            try
            {
                //Create RestClient
                var client = CreateRestClient(_eventbriteSettings.Value.OrganizationId);

                //Get Payload
                IRestResponse response = await CreateEvent(client, newEvent);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    _logger.LogInformation("Error");
                }
                else
                {
                    model = JsonConvert.DeserializeObject <Event>(response.Content);
                }
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.Message);
            }

            return(model);
        }
Ejemplo n.º 5
0
        public static Command Create(CommandType type, string[] parameters, CommandRequest commandRequest)
        {
            Command command = null;

            switch (type)
            {
            case CommandType.CreateEvent:
                command = new CreateEventCommand(parameters, commandRequest);
                break;

            case CommandType.SubscribeToEvent:
                command = new SubscribeToEventCommand(parameters, commandRequest);
                break;

            case CommandType.Split:
                command = new SplitFixCommand(parameters, commandRequest, CommandType.Split);
                break;

            case CommandType.Fix:
                command = new SplitFixCommand(parameters, commandRequest, CommandType.Fix);
                break;

            case CommandType.PayFor:
                command = new PayForCommand(parameters, commandRequest);
                break;

            case CommandType.AddReminder:
                command = new AddReminderCommand(parameters, commandRequest);
                break;
            }

            return(command);
        }
        public async Task <ActionResult <bool> > Create([FromBody] CreateEventCommand command)
        {
            var result = await _mediator.Send(command);


            return(Ok(result.Successful));
        }
Ejemplo n.º 7
0
        public async Task Handle_Given_Invalid_EventTypeId_Throws_ValidationException()
        {
            // Arrange
            var validTitle         = "Event Created from Unit Tests.";
            var validDescription   = "This event was created from a Unit Test.";
            var validStartDate     = new DateTime(2020, 3, 1);
            var validEndDate       = new DateTime(2020, 3, 2);
            var validRegStartDate  = new DateTime(2020, 2, 1);
            var validRegEndDate    = new DateTime(2020, 2, 2);
            var validMaxRegs       = 10;
            var inValidEventTypeId = 20;
            var command            = new CreateEventCommand
            {
                Title        = validTitle,
                Description  = validDescription,
                StartDate    = validStartDate,
                EndDate      = validEndDate,
                RegStartDate = validRegStartDate,
                RegEndDate   = validRegEndDate,
                MaxRegsCount = validMaxRegs,
                EventTypeId  = inValidEventTypeId
            };

            // Act/Assert
            var ex = await Assert.ThrowsAsync <ValidationException>(() => _sut.Handle(command, CancellationToken.None));

            Assert.Equal(1, ex.Failures.Count);
        }
Ejemplo n.º 8
0
        public async Task Handle(PostPublishedEvent message, IMessageHandlerContext context)
        {
            using (LogContext.PushProperty("IntegrationEventContext", $"{message.Id}-{Program.AppName}"))
            {
                _logger.LogInformation("----- Handling PostPublishedEvent: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", message.Id, Program.AppName, message);

                #region 创建帖子
                var postCommand = new CreatePostCommand {
                    PostId = message.PostId, Image = message.Image
                };
                await _mediator.Send(postCommand);

                #endregion

                #region 发布@用户通知
                foreach (var atUserId in message.AtUserIds)
                {
                    var eventCommand = new CreateEventCommand
                    {
                        FromUserId  = message.UserId,
                        ToUserId    = atUserId,
                        PostId      = message.PostId,
                        EventType   = EventType.AtUserInPost,
                        PushMessage = $"{message.Nickname}在作品中@了你"
                    };

                    await _mediator.Send(eventCommand);
                }
                #endregion
            }
        }
        public async Task CreateEvent(Guid eventId, CreateEventCommand createEventCommand)
        {
            await CreateUrlKey(eventId, createEventCommand.UrlKey);

            var document = new Document <EventDocument>
            {
                Id      = eventId.ToString(),
                Content = new EventDocument
                {
                    Subject     = createEventCommand.Subject,
                    UrlKey      = createEventCommand.UrlKey,
                    Description = createEventCommand.Description,
                    Address     = createEventCommand.Address,
                    Date        = createEventCommand.Date,
                    EndDate     = createEventCommand.EndDate,
                    Capacity    = createEventCommand.Capacity,
                    GroupId     = createEventCommand.GroupId,
                    Status      = EventStatuses.ACTIVE,
                    Location    = new EventLocationDocument
                    {
                        Lat = createEventCommand.Latitude,
                        Lon = createEventCommand.Longitude
                    }
                }
            };

            var documentResult = await _eventsBucket.InsertAsync(document);

            if (!documentResult.Success)
            {
                await DeleteUrlKey(createEventCommand.UrlKey);

                throw documentResult.Exception;
            }
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> CreateEvent([FromBody] CreateEventRequest request)
        {
            var createEventCommand = new CreateEventCommand(request);
            var result             = await mediator.Send(createEventCommand);

            return(StatusCode((int)result.Code, result.Value));
        }
Ejemplo n.º 11
0
        public async Task Handle_Given_StartDate_InPast_Throws_ValidationException()
        {
            // Arrange
            var validTitle        = "Event Created from Unit Tests.";
            var validDescription  = "This event was created from a Unit Test.";
            var inValidStartDate  = new DateTime(2019, 3, 1);
            var validEndDate      = new DateTime(2020, 3, 2);
            var validRegStartDate = new DateTime(2019, 1, 1);
            var validRegEndDate   = new DateTime(2019, 2, 1);
            var validMaxRegs      = 10;
            var validEventTypeId  = 1;
            var command           = new CreateEventCommand
            {
                Title        = validTitle,
                Description  = validDescription,
                StartDate    = inValidStartDate,
                EndDate      = validEndDate,
                RegStartDate = validRegStartDate,
                RegEndDate   = validRegEndDate,
                MaxRegsCount = validMaxRegs,
                EventTypeId  = validEventTypeId
            };
            var validator = new CreateEventCommandValidator(new DateTimeTestProvider()); // manually invoke to test the Validator
            // Act/Assert
            var result = await validator.ValidateAsync(command);

            Assert.False(result.IsValid);
            Assert.Equal(1, result.Errors.Count);
            Assert.Contains(result.Errors, x => x.PropertyName == "StartDate");
        }
Ejemplo n.º 12
0
        public async Task Handle_Given_RegEndDate_Before_RegStartDate_Throw_ValidationException()
        {
            // Arrange
            var validTitle        = "Event Created from Unit Tests.";
            var validDescription  = "This event was created from a Unit Test.";
            var validStartDate    = new DateTime(2020, 3, 3);
            var validEndDate      = new DateTime(2020, 3, 4);
            var validRegStartDate = new DateTime(2020, 2, 1);
            var inValidRegEndDate = new DateTime(2020, 1, 1);
            var validMaxRegs      = 10;
            var validEventTypeId  = 1;
            var command           = new CreateEventCommand
            {
                Title        = validTitle,
                Description  = validDescription,
                StartDate    = validStartDate,
                EndDate      = validEndDate,
                RegStartDate = validRegStartDate,
                RegEndDate   = inValidRegEndDate,
                MaxRegsCount = validMaxRegs,
                EventTypeId  = validEventTypeId
            };
            var validator = new CreateEventCommandValidator(new DateTimeTestProvider());

            // Act/Assert
            var result = await validator.ValidateAsync(command);

            var ex = await Assert.ThrowsAsync <ValidationException>(() => _sut.Handle(command, CancellationToken.None));

            Assert.Equal(1, ex.Failures.Count);
            Assert.False(result.IsValid);
            Assert.Equal(1, result.Errors.Count);
            Assert.Contains(result.Errors, x => x.PropertyName == "RegStartDate");
        }
        public async Task <ActionResult <EventCreateResponse> > Post([FromBody] EventCreateRequest value)
        {
            var command = new CreateEventCommand();

            command.Data = value;
            var response = await Go(command);

            return(Ok(response));
        }
Ejemplo n.º 14
0
        public void Handle_ShouldReturnDto()
        {
            var name    = "Name";
            var dates   = Enumerable.Empty <LocalDate>();
            var command = new CreateEventCommand(name, dates);

            var result = _handler.Handle(command, new CancellationToken());

            result.Result.ShouldBeOfType <EventCreatedDto>();
        }
Ejemplo n.º 15
0
        public async Task <ActionResult <long> > Create([FromBody] CreateEventRequest request)
        {
            var command         = new CreateEventCommand(request.Name, request.Dates);
            var eventCreatedDto = await _mediator.Send(command);

            return(CreatedAtAction(
                       nameof(GetById),
                       new { version = "1.0", id = eventCreatedDto.Id },
                       eventCreatedDto));
        }
Ejemplo n.º 16
0
        public void Handle_ShouldCreateEvent()
        {
            var name    = "Name";
            var dates   = Enumerable.Empty <LocalDate>();
            var command = new CreateEventCommand(name, dates);

            var result = _handler.Handle(command, new CancellationToken());

            _eventRepository.Received(1).Add(Arg.Is <EventEntity>(e => e.Name == name));
            _unitOfWork.Received(1).Save(Arg.Any <CancellationToken>());
        }
Ejemplo n.º 17
0
        public async Task <ActionResult <int> > PostEvent([FromRoute] int id, [FromBody] CreateEventCommand command)
        {
            if (id != command.TopicId)
            {
                return(BadRequestNonMatchingIds());
            }

            int result = await _Mediator.Send(command);

            return(Ok(new { result }));
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> Post(CreateEventCommand command)
        {
            var result = await _handler.Handle(command);

            if (!_handler.IsValid())
            {
                return(BadRequest(_handler.GetErrors()));
            }

            return(Ok(result));
        }
Ejemplo n.º 19
0
 static void Main(string[] args)
 {
     var eventCreateCommand = new CreateEventCommand()
     {
         EventDate = DateTime.Now,
         EventName = "test",
         Latitude  = 1,
         Longitude = 2,
         SeatCount = 23,
         VenueName = "t"
     }.Execute();
 }
        public async Task Handle(PostForwardedEvent message, IMessageHandlerContext context)
        {
            using (LogContext.PushProperty("IntegrationEventContext", $"{message.Id}-{Program.AppName}"))
            {
                _logger.LogInformation("----- Handling PostForwardedEvent: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", message.Id, Program.AppName, message);

                foreach (var info in message.ForwardInfos)
                {
                    #region 创建新帖子,由于是转发的帖子,其图片为原帖子的图片
                    var originalPost = await _postRepository.GetByIdAsync(info.OriginalPostId);

                    var createPostCommand = new CreatePostCommand
                    {
                        PostId = info.NewPostId,
                        Image  = originalPost.Image
                    };
                    await _mediator.Send(createPostCommand);

                    #endregion

                    var fromUser = await _userRepository.GetByIdAsync(info.ForwardUserId);

                    #region 发布转发通知
                    var createEventCommand = new CreateEventCommand
                    {
                        FromUserId  = info.ForwardUserId,
                        ToUserId    = info.OriginalPostUserId,
                        PostId      = info.OriginalPostId,
                        EventType   = EventType.ForwardPost,
                        PushMessage = $"{fromUser.Nickname}转发了你的作品"
                    };
                    await _mediator.Send(createEventCommand);

                    #endregion

                    #region 发布@用户通知
                    foreach (var atUserId in info.AtUserIds)
                    {
                        var eventCommand = new CreateEventCommand
                        {
                            FromUserId  = info.ForwardUserId,
                            ToUserId    = atUserId,
                            PostId      = info.OriginalPostId,
                            EventType   = EventType.AtUserInPost,
                            PushMessage = $"{fromUser.Nickname}在作品中@了你"
                        };

                        await _mediator.Send(eventCommand);
                    }
                    #endregion
                }
            }
        }
        public async Task Handle(JoinedCircleEvent message, IMessageHandlerContext context)
        {
            using (LogContext.PushProperty("IntegrationEventContext", $"{message.Id}-{Program.AppName}"))
            {
                _logger.LogInformation("----- Handling JoinedCircleEvent: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", message.Id, Program.AppName, message);

                var fromUser = await _userRepository.GetByIdAsync(message.JoinedUserId);

                #region 给圈主发通知
                var createEventCommand = new CreateEventCommand
                {
                    FromUserId  = message.JoinedUserId,
                    ToUserId    = message.CircleOwnerId,
                    CircleId    = message.CircleId,
                    CircleName  = message.CircleName,
                    EventType   = Domain.AggregatesModel.EventAggregate.EventType.JoinCircle,
                    PushMessage = $"{fromUser.Nickname}加入{message.CircleName}"
                };

                await _mediator.Send(createEventCommand);

                #endregion

                #region 给申请入圈用户发通知
                var joinCircleAcceptedCommand = new CreateEventCommand
                {
                    FromUserId  = message.CircleOwnerId,
                    ToUserId    = message.JoinedUserId,
                    CircleId    = message.CircleId,
                    CircleName  = message.CircleName,
                    EventType   = Domain.AggregatesModel.EventAggregate.EventType.ApplyJoinCircleAccepted,
                    PushMessage = $"申请通过,已加入{message.CircleName}"
                };

                await _mediator.Send(joinCircleAcceptedCommand);

                #endregion

                #region 将申请入圈事件标记为已处理
                var processEventCommand = new ProcessEventCommand
                {
                    FromUserId = message.JoinedUserId,
                    ToUserId   = message.CircleOwnerId,
                    EventType  = Domain.AggregatesModel.EventAggregate.EventType.ApplyJoinCircle
                };

                await _mediator.Send(processEventCommand);

                #endregion
            }
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> InsertAsync(CreateEventCommand data)
        {
            var operationResult = Event.Create(data);

            if (!operationResult.IsValid)
            {
                ModelState.AddFromOperationResult(operationResult);
                return(BadRequest(ModelState));
            }

            await _eventRepository.InsertAsync(operationResult.Result);

            return(Created($"/api/events/{operationResult.Result.Id}", null));
        }
Ejemplo n.º 23
0
        public void CreateEvent_CallEventFactory(
            [Frozen] IEventFactory eventFactory,
            CreateEventCommand message,
            Event @event,
            CreateEventCommandHandler createEventCommandHandler)
        {
            //Information
            A.CallTo(() => eventFactory.Create(message.Event)).Returns(@event);

            //Act
            createEventCommandHandler.ExecuteAsync(message);

            //Test
            A.CallTo(() => eventFactory.Create(message.Event)).MustHaveHappened();
        }
Ejemplo n.º 24
0
        public ActionResult CreateEvent(TournamentEvent tournamentEvent)
        {
            ISystemResponseMessages systemMessages = new SystemResponseMessages(ApplicationResponseMessagesEnum.NoAction, "");

            var command = new CreateEventCommand(tournamentEvent, _context);

            _tournamentDomainClient.PerformCommand(command, out systemMessages);

            if (systemMessages.MessageState().Equals(ApplicationResponseMessagesEnum.Success))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.OK));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Data not captured"));
        }
        public async Task <IActionResult> CreateEvent([FromBody] CreateEventCommand command)
        {
            using (MiniProfiler.Current.Step("Create Event"))
            {
                var model = await _mediator.Send(command);

                if (model != null)
                {
                    return(CreatedAtAction(
                               nameof(GetEventById), new { id = model.id }, model));
                }
                ;
                return(BadRequest(ModelState));
            }
        }
Ejemplo n.º 26
0
        public string Dispatch(string input)
        {
            string result = String.Empty;

            string[] args = input.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

            string cmdName = args.Length >= 0 ? args[0] : string.Empty;

            args = args.Skip(1).ToArray();

            switch (cmdName)
            {
            case "RegisterUser": result = new RegisterUserCommand().Execute(args); break;

            case "Login": result = new LoginCommand().Execute(args); break;

            case "Logout": result = new LogoutCommand().Execute(args); break;

            case "DeleteUser": result = new DeleteUserCommand().Execute(args); break;

            case "CreateEvent": result = new CreateEventCommand().Execute(args); break;

            case "CreateTeam": result = new CreateTeamCommand().Execute(args); break;

            case "InviteToTeam": result = new InviteToTeamCommand().Execute(args); break;

            case "AcceptInvite": result = new AcceptInviteCommand().Execute(args); break;

            case "DeclineInvite": result = new DeclineInviteCommand().Execute(args); break;

            case "KickMember": result = new KickMemberCommand().Execute(args); break;

            case "Disband": result = new DisbandCommand().Execute(args); break;

            case "AddTeamTo": result = new AddTeamToCommand().Execute(args); break;

            case "ShowEvent": result = new ShowEventCommand().Execute(args); break;

            case "ShowTeam": result = new ShowTeamCommand().Execute(args); break;

            case "Exit": result = new ExitCommand().Execute(args); break;

            default:
                throw new NotSupportedException($"Command {cmdName} not supported!");
            }

            return(result);
        }
Ejemplo n.º 27
0
        public string DispatchCommand(string[] commandParameters)
        {
            string commandName = commandParameters[0];

            commandParameters = commandParameters.Skip(1).ToArray();
            string result = string.Empty;

            EventService eventService = new EventService();

            switch (commandName)
            {
            case "CreateEvent":
                CreateEventCommand createEvent = new CreateEventCommand(eventService);
                result = createEvent.Execute(commandParameters);
                break;

            case "DeleteEvent":
                DeleteEventCommand deleteEvent = new DeleteEventCommand(eventService);
                result = deleteEvent.Execute(commandParameters);
                break;

            case "EditEvent":
                EditEventCommand editEvent = new EditEventCommand(eventService);
                result = editEvent.Execute(commandParameters);
                break;

            case "ListEvents":
                ListEventsCommand listEvents = new ListEventsCommand(eventService);
                result = listEvents.Execute(commandParameters);
                break;

            case "Help":
                HelpCommand help = new HelpCommand();
                result = help.Execute(commandParameters);
                break;

            case "Exit":
                ExitCommand exit = new ExitCommand(eventService);
                result = exit.Execute(commandParameters);
                break;

            default:
                result = $@"Command {commandName} does not exist. Type ""Help"" to check the available commands.";
                break;
            }

            return(result);
        }
Ejemplo n.º 28
0
        public Task CreateEvent(CreateEventCommand command)
        {
            var gameEvent = new GameEvent
            {
                TeamAId   = command.TeamAId,
                TeamBId   = command.TeamBId,
                EventDate = command.EventDate,
                Status    = command.Status,
                EventType = command.Type,
                Name      = command.Name,
            };

            _dbContext.Events.Add(gameEvent);

            return(_dbContext.SaveChangesAsync());
        }
        public async Task Handle(UserFeedbackCreatedEvent message, IMessageHandlerContext context)
        {
            using (LogContext.PushProperty("IntegrationEventContext", $"{message.Id}-{Program.AppName}"))
            {
                _logger.LogInformation("----- Handling UserFeedbackCreatedEvent: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", message.Id, Program.AppName, message);

                var command = new CreateEventCommand
                {
                    ToUserId    = message.UserId,
                    EventType   = EventType.FeedbackCreated,
                    PushMessage = "已收到您的意见反馈,我们将尽快处理,感谢您对我们的支持。"
                };

                await _mediator.Send(command);
            }
        }
Ejemplo n.º 30
0
        public async Task <ApiResponse <Guid> > CreateEvent(EventDetailViewModel eventDetailViewModel)
        {
            try
            {
                CreateEventCommand createEventCommand = _mapper.Map <CreateEventCommand>(eventDetailViewModel);
                var newId = await _client.AddEventAsync(createEventCommand);

                return(new ApiResponse <Guid>()
                {
                    Data = newId, Success = true
                });
            }
            catch (ApiException ex)
            {
                return(ConvertApiExceptions <Guid>(ex));
            }
        }