public async Task <IActionResult> RegisterAsync([FromBody] RegisterFlight command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // insert flight
                    Flight flight = Mapper.Map <Flight>(command);
                    _dbContext.Flights.Add(flight);
                    await _dbContext.SaveChangesAsync();

                    // send event
                    var e = Mapper.Map <FlightRegistered>(command);
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                    //return result
                    return(CreatedAtRoute("GetByFlightNumber", new { flightNumber = flight.FlightNumber }, flight));
                }
                return(BadRequest());
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Beispiel #2
0
        public async Task CreateTweet(string id, string tweetContent)
        {
            var tweet = new Entities.Tweet
            {
                TweetDateTime = DateTime.Now.ToString("d/MM/yyyy"),
                TimeStamp     = DateTime.Now,
                Id            = Guid.NewGuid().ToString(),
                UserId        = id,
                TweetContent  = tweetContent
            };

            if (await CheckForProfanity(tweet))
            {
                await _messagePublisher.PublishMessageAsync("NewProfanityTweetMessage", new { TweetDateTime = tweet.TweetDateTime, TimeStamp = tweet.TimeStamp, Id = tweet.Id, UserId = tweet.UserId, TweetContent = tweet.TweetContent });
            }

            if (tweetContent.Contains("#"))
            {
                await _messagePublisher.PublishMessageAsync("NewTopicTweetMessage", new { Id = tweet.Id, TweetContent = tweet.TweetContent });
            }

            await _messagePublisher.PublishMessageAsync("NewPostedTweetMessage", new { TweetDateTime = tweet.TweetDateTime, TimeStamp = tweet.TimeStamp, Id = tweet.Id, UserId = tweet.UserId, TweetContent = tweet.TweetContent });

            _tweets.InsertOne(tweet);
        }
Beispiel #3
0
        public async Task <bool> FollowUser(string followerId, string followingId)
        {
            if (followerId == followingId)
            {
                return(false);
            }

            if (FollowExists(followerId, followingId))
            {
                return(false);
            }

            var follow = new Follow
            {
                Id        = Guid.NewGuid().ToString(),
                Follower  = followerId,
                Following = followingId
            };

            await _messagePublisher.PublishMessageAsync("AddFollowerMessage", new { Id = follow.Id, FollowerId = follow.Follower, FollowingId = follow.Following });

            await _followRepository.AddOneFollower(follow);

            return(true);
        }
Beispiel #4
0
        public async Task <IActionResult> RegisterBaggageSetAsync([FromBody] RegisterBaggageSet command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // insert baggageset
                    BaggageSet baggageSet = Mapper.Map <BaggageSet>(command);
                    baggageSet.LoadedOnFlight          = false;
                    baggageSet.DeliveredToBaggageClaim = false;
                    _dbContext.BaggageSets.Add(baggageSet);
                    await _dbContext.SaveChangesAsync();

                    // send event
                    var e = Mapper.Map <BaggageSetRegistered>(command);
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                    // return result
                    return(CreatedAtRoute("GetByScheduledFlightId", new { scheduledFlightId = baggageSet.ScheduledFlightId }, baggageSet));
                }
                return(BadRequest());
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Beispiel #5
0
        public async Task <bool> EditProfile(EditProfileMessage message)
        {
            var user = await GetUserById(message.Id);

            if (user == null)
            {
                return(false);
            }

            if (user.Email != message.Email)
            {
                if (_userService.VerifyUniqueEmail(message.Email))
                {
                    return(false);
                }

                await _messagePublisher.PublishMessageAsync("EmailChangedMessage", new { Id = user.Id, Email = message.Email });
            }

            if (user.Nickname != message.Nickname)
            {
                await _messagePublisher.PublishMessageAsync("ProfileChangedMessage", new { Id = user.Id, Nickname = message.Nickname });
            }

            user.Email    = message.Email;
            user.Nickname = message.Nickname;

            _userContext.Update(user);
            await _userContext.SaveChangesAsync();

            return(true);
        }
Beispiel #6
0
        public async Task <bool> RegisterUser(RegisterMessage message)
        {
            var user = new User
            {
                Id             = Guid.NewGuid().ToString(),
                Email          = message.Email,
                Username       = message.Username,
                Nickname       = message.Username,
                Image          = "default.png",
                Location       = "",
                FollowersCount = 0,
                FollowingCount = 0,
                Verified       = false
            };

            _userContext.Add(user);
            _userContext.SaveChanges();

            await _messagePublisher.PublishMessageAsync("NewUserMessage", new { Id = user.Id, Email = user.Email, Username = user.Username, Password = message.Password });

            await _messagePublisher.PublishMessageAsync("NewProfileMessage",
                                                        new { Id = user.Id, Username = user.Username, Nickname = user.Nickname, Image = user.Image });

            return(true);
        }
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterVehicle command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // insert vehicle
                    Vehicle vehicle = command.MapToVehicle();
                    _dbContext.Vehicles.Add(vehicle);
                    await _dbContext.SaveChangesAsync();

                    // send event
                    var e = Mappers.MapToVehicleRegistered(command);
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                    //return result
                    return(CreatedAtRoute("GetByLicenseNumber", new { licenseNumber = vehicle.LicenseNumber }, vehicle));
                }
                return(BadRequest());
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Beispiel #8
0
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterCustomer command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // insert customer
                    Customer customer = Mapper.Map <Customer>(command);
                    _dbContext.Customers.Add(customer);
                    await _dbContext.SaveChangesAsync();

                    // send event
                    CustomerRegistered e = Mapper.Map <CustomerRegistered>(customer);
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                    // return result
                    return(CreatedAtRoute("GetByCustomerId", new { customerId = customer.CustomerId }, customer));
                }
                return(BadRequest());
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
        public async Task <ShipService> CreateShipService(ShipService shipService)
        {
            var addedShipService = await _shipServiceService.AddAsync(shipService);

            await _messagePublisher.PublishMessageAsync(MessageTypes.ServiceCreated, shipService);

            return(addedShipService);
        }
Beispiel #10
0
        public async Task <bool> HandleMessageAsync(string messageType, string message, IDictionary <string, object> userproperties)
        {
            try
            {
                var id          = Encoding.UTF8.GetString((byte[])userproperties["Id"]);
                var ordertype   = Encoding.UTF8.GetString((byte[])userproperties["OrderType"]);
                var sendingdate = Encoding.UTF8.GetString((byte[])userproperties["SendingDate"]);

                List <ValueDTO> values = new List <ValueDTO>();
                values.Add(new ValueDTO()
                {
                    Key = "Id", Value = id
                });
                values.Add(new ValueDTO()
                {
                    Key = "OrderType", Value = ordertype
                });
                values.Add(new ValueDTO()
                {
                    Key = "SendingDate", Value = sendingdate
                });


                var valresponse = await _service.Validate("CardCompos", ".json", message);

                var streamid = Guid.NewGuid();
                var filename = string.Format("{0}_{1}.json", id, messageType);
                if (await _service.AddToStorage(streamid, message, filename, "json", valresponse.Valid))
                {
                    Guid headerid = Guid.NewGuid();
                    var  xx       = await _service.AddHeader(headerid, "CardCompos");

                    var yy = await _service.AddFileExtension(headerid, streamid, filename, valresponse.Valid, string.Join("\n", valresponse.Messages), values);

                    DeliveryCompleted e = await _service.CreateFowardingCommand(headerid);

                    await _messagePublisher.PublishMessageAsync(messageType, e, "DataService", null);

                    //await _messagePublisher.PublishMessageAsync(messageType, e, "", null);
                    await _messagePublisher.PublishMessageAsync(messageType, e, "notification", null);
                }


                //scaler aanroepen

                //status terugkoppelen.
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(true);
        }
Beispiel #11
0
        public async Task <IActionResult> ApproveRequestToChef([FromBody] Request request)
        {
            if (request.RequestType == RequestType.Upgrade_To_Chef)
            {
                await _moderationService.ApproveRequest(request);

                await _messagePublisher.PublishMessageAsync("UserRoleUpdated", new { request.UserId, Role = 1 });

                return(Ok());
            }

            return(BadRequest());
        }
        private async Task ProcessTransferredFundEvent(TransferFundCommand request, Account sourceAccount, Account destinationAccount)
        {
            var transferredFundEvent = new TransferredFund
            {
                SourceAccount      = sourceAccount.AccountNumber,
                DestinationAccount = destinationAccount.AccountNumber,
                Amount             = request.Amount,
                Status             = TransactionStatus.SUCCESS,
                Remarks            = (string.IsNullOrEmpty(request.Remarks) ? "" : request.Remarks)
            };

            await _messagePublisher.PublishMessageAsync(transferredFundEvent.MessageType, transferredFundEvent, "");
        }
        public async Task <IActionResult> PlanMaintenanceJobAsync(DateTime date, [FromBody] PlanMaintenanceJob command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // get planning
                    WorkshopPlanning planning = await _planningRepo.GetWorkshopPlanningAsync(date);

                    if (planning == null)
                    {
                        return(NotFound());
                    }

                    // handle command
                    try
                    {
                        IEnumerable <Event> events = planning.PlanMaintenanceJob(command);

                        // persist
                        await _planningRepo.SaveWorkshopPlanningAsync(planning, events);

                        // publish event
                        foreach (var e in events)
                        {
                            await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");
                        }

                        // return result
                        return(CreatedAtRoute("GetByDate", new { date = planning.Date }, planning));
                    }
                    catch (BusinessRuleViolationException ex)
                    {
                        return(StatusCode(StatusCodes.Status409Conflict, new BusinessRuleViolation {
                            ErrorMessage = ex.Message
                        }));
                    }
                }
                return(BadRequest());
            }
            catch (ConcurrencyException)
            {
                ModelState.AddModelError("ErrorMessage", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
        public async Task <WorkshopPlanning> HandleCommandAsync(DateTime planningDate, FinishMaintenanceJob command)
        {
            // get planning
            var aggregateId = WorkshopPlanningId.Create(planningDate);
            var planning    = await _planningRepo.GetByIdAsync(aggregateId);

            if (planning == null)
            {
                return(null);
            }

            // handle command
            planning.FinishMaintenanceJob(command);

            // persist
            IEnumerable <Event> events = planning.GetEvents();
            await _planningRepo.SaveAsync(
                planning.Id, planning.OriginalVersion, planning.Version, events);

            // publish event
            foreach (var e in events)
            {
                await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");
            }

            // return result
            return(planning);
        }
        public async Task <WorkshopPlanning> HandleCommandAsync(DateTime planningDate, FinishMaintenanceJob command)
        {
            // get planning
            WorkshopPlanning planning = await _planningRepo.GetWorkshopPlanningAsync(planningDate);

            if (planning == null)
            {
                return(null);
            }

            // handle command
            IEnumerable <Event> events = planning.FinishMaintenanceJob(command);

            // persist
            await _planningRepo.SaveWorkshopPlanningAsync(planning, events);

            // publish event
            foreach (var e in events)
            {
                await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");
            }

            // return result
            return(planning);
        }
Beispiel #16
0
        public async Task <bool> UnApproveProfanityTweet(string tweetId)
        {
            var tweet = _tweets.Find(t => t.Id == tweetId).FirstOrDefault();

            if (tweet == null)
            {
                return(false);
            }

            tweet.TweetStatus = Status.Unapproved;
            await _tweets.ReplaceOneAsync(t => t.Id == tweetId, tweet);

            await _messagePublisher.PublishMessageAsync("UnApproveTweetMessage", new { TweetId = tweetId });

            return(true);
        }
Beispiel #17
0
        public async Task <IActionResult> PlaceOrder(string orderId, [FromBody] PlaceOrder orderCommand)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var order = await _dbContext.Orders.FirstOrDefaultAsync(o => o.OrderId == orderId);

            if (order == null)
            {
                return(NotFound());
            }

            order.AfterPayment = orderCommand.AfterPayment;

            if (order.AfterPayment)
            {
                order.AddStateChange(OrderState.AWAITINGAFTERPAYMENT);
            }
            else
            {
                order.AddStateChange(OrderState.PAYMENTINPROGRESS);
            }

            await _dbContext.SaveChangesAsync();

            OrderPlaced e = Mapper.Map <OrderPlaced>(order);
            await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

            return(AcceptedAtRoute("GetByOrderId", new { orderId = order.OrderId }, order));
        }
Beispiel #18
0
        private async Task <bool> SourceHasSufficientAmount(TransferFundCommand request)
        {
            var account = _unitOfWork.Account.GetFirstOrDefault(a => a.AccountNumber == request.SourceAccount);

            var inquireBalanceEvent = new InquireBalance
            {
                AccountId         = account.AccountId,
                Balance           = account.Balance,
                TransactionAmount = request.Amount,
                Status            = (account.Balance >= request.Amount ? TransactionStatus.SUCCESS : TransactionStatus.INSUFFICIENT_FUNDS)
            };

            await _messagePublisher.PublishMessageAsync(inquireBalanceEvent.MessageType, inquireBalanceEvent, "");

            return(account.Balance >= request.Amount);
        }
Beispiel #19
0
        public async Task <IActionResult> ResetPassword(string email) // This endpoint may not be used in production, instead sending email to admin for resetting password
        {
            var user = await _userManager.FindByEmailAsync(email);

            var restToken = await _userManager.GeneratePasswordResetTokenAsync(user);

            var resetLink = Url.Action("ResetPassword",
                                       "Account", new { token = restToken },
                                       protocol: HttpContext.Request.Scheme);

            // Send email - Send message to message queue(notificaiton) - integration event

            var emailBody = "";

            EmailNotificationEvent e = new EmailNotificationEvent(new Guid(), email, "Password Reset", emailBody);

            try
            {
                await _messagePublisher.PublishMessageAsync(e.MessageType, e, "notification");

                Log.Information("Message  {MessageType} with Id {MessageId} has been published successfully", e.MessageType, e.MessageId);
            }
            catch (Exception ex)
            {
                //throw ex;
                Log.Error(ex, "Error while publishing {MessageType} message with id {MessageId}.", e.MessageType, e.MessageId);
            }


            return(Ok(resetLink));
        }
Beispiel #20
0
        private async Task RealTimeJobs()
        {
            //initialiseren realtimejobs

            await _realtimeservice.InitAsync();



            while (true)
            {
                var triggers = await _realtimeservice.Process();

                //if (DateTime.Now.Subtract(_lastCheck).Days > 0)
                //{

                foreach (var tr in triggers)
                {
                    await _messagePublisher.PublishMessageAsync(tr.MessageType, tr, "");
                }


                //}
                await Task.Delay(60000);
            }
        }
        public async Task <WorkshopPlanning> HandleCommandAsync(DateTime planningDate, PlanMaintenanceJob command)
        {
            List <Event> events = new List <Event>();

            // get or create workshop-planning
            WorkshopPlanning planning = await _planningRepo.GetWorkshopPlanningAsync(planningDate);

            if (planning == null)
            {
                events.AddRange(WorkshopPlanning.Create(planningDate, out planning));
            }

            // handle command
            events.AddRange(planning.PlanMaintenanceJob(command));

            // persist
            await _planningRepo.SaveWorkshopPlanningAsync(
                planning.Id, planning.OriginalVersion, planning.Version, events);

            // publish event
            foreach (var e in events)
            {
                await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");
            }

            // return result
            return(planning);
        }
        public async Task <dynamic> Post([FromBody] UpdateStatus command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Status status = _mapper.Map <UpdateStatus, Status>(command);
                    _dbContext.Add(status);
                    int result = await _dbContext.SaveChangesAsync();

                    // send event
                    StatusReceived message = Mapper.Map <StatusReceived>(command);
                    await _messagePublisher.PublishMessageAsync(message.MessageType, message, "StatusReceived");

                    //return result
                    return(result > 0 ? new
                    {
                        Saved = true,
                    }
                                        : new
                    {
                        Saved = false,
                    });
                }
                return(BadRequest());
            }

            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterVehicle command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // check invariants
                    if (!Regex.IsMatch(command.LicenseNumber, NUMBER_PATTERN, RegexOptions.IgnoreCase))
                    {
                        return(BadRequest($"The specified license-number '{command.LicenseNumber}' was not in the correct format."));
                    }

                    // insert vehicle
                    Vehicle vehicle = command.MapToVehicle();
                    _dbContext.Vehicles.Add(vehicle);
                    await _dbContext.SaveChangesAsync();

                    // send event
                    var e = VehicleRegistered.FromCommand(command);
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                    //return result
                    return(CreatedAtRoute("GetByLicenseNumber", new { licenseNumber = vehicle.LicenseNumber }, vehicle));
                }
                return(BadRequest());
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Beispiel #24
0
        public async Task <bool> HandleMessageAsync(string messageType, string message, IDictionary <string, object> userproperties)
        {
            try
            {
                switch (messageType)
                {
                case "Fulfilment":
                default:
                    //hier aan de queue toevoegen
                    JObject order       = JObject.Parse(message);
                    var     id          = userproperties.ContainsKey("Id") ? userproperties["Id"].ToString() : string.Empty;
                    var     sendingdate = userproperties.ContainsKey("SendingDate") ? userproperties["SendingDate"].ToString() : string.Empty;
                    var     dict        = new Dictionary <string, object>()
                    {
                        { "Id", id }, { "OrderType", messageType }, { "SendingDate", sendingdate }
                    };
                    await _messagePublisher.PublishMessageAsync(messageType, order, string.Empty, dict);

                    break;
                }
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(true);
        }
Beispiel #25
0
        public async Task <WorkshopPlanning> HandleCommandAsync(DateTime planningDate, UpdateMaintenanceJob command)
        {
            // get or create workshop-planning
            WorkshopPlanning planning = await planningRepository.GetWorkshopPlanningAsync(planningDate);

            if (planning == null)
            {
                return(null);
            }

            // handle command
            planning.UpdateMaintenanceJob(command);

            // persist
            IEnumerable <Event> events = planning.GetEvents();
            await planningRepository.SaveWorkshopPlanningAsync(
                planning.Id, planning.OriginalVersion, planning.Version, events);

            // publish event
            foreach (var e in events)
            {
                await messagePublisher.PublishMessageAsync(e.MessageType, e, "");
            }

            // return result
            return(planning);
        }
        private async Task <bool> HasValidAccount(WithdrawCommand request)
        {
            var account = _unitOfWork.Account.GetFirstOrDefault(a => a.AccountNumber == request.AccountNumber);

            var checkAccountValidityEvent = new CheckAccountValidity
            {
                AccountId       = account.AccountId,
                TransactionType = TransactionTypes.WITHDRAWAL,
                Balance         = account.Balance,
                Status          = (account.IsValid ? AccountStatus.VALID : AccountStatus.ACCOUNT_DISABLED)
            };

            await _messagePublisher.PublishMessageAsync(checkAccountValidityEvent.MessageType, checkAccountValidityEvent, "");

            return(account.IsValid);
        }
Beispiel #27
0
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterInsurance command)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    // insert insurance
                    Insurance insurance = Mapper.Map <Insurance>(command);
                    _dbContext.Insurances.Add(insurance);
                    await _dbContext.SaveChangesAsync();

                    // send event
                    var e = Mapper.Map <InsuranceRegistered>(command);
                    await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                    //return result
                    return(CreatedAtRoute("GetInsuranceById", new { insuranceId = insurance.InsuranceId }, insurance));
                }
                return(BadRequest());
            }
            catch (DbUpdateException ex)
            {
                ModelState.AddModelError("", "Unable to save changes. " +
                                         "Try again, and if the problem persists " +
                                         "see your system administrator.");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Beispiel #28
0
        public async Task <IActionResult> PostAsync(string orderId, [FromBody] string bank)
        {
            OrderPayed e = new OrderPayed(Guid.NewGuid(), orderId, bank);

            await _messagePublisher.PublishMessageAsync(MessageTypes.OrderPayed, e, "");

            return(Ok());
        }
        public ApiResult GetRestList()
        {
            var stringList = _testService.getTestList();

            _messagePublisher.PublishMessageAsync("StringList", new { List = stringList });

            return(ApiResult.Success(stringList));
        }
Beispiel #30
0
        public async Task <IActionResult> PostAsync([FromBody] RegisterTransport command)
        {
            if (ModelState.IsValid)
            {
                // Insert Transport
                Transport transport = Mapper.Map <Transport>(command);
                _dbContext.Transports.Add(transport);
                await _dbContext.SaveChangesAsync();

                // Send Event
                TransportRegistered e = Mapper.Map <TransportRegistered>(transport);
                await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

                return(CreatedAtRoute("GetTransportById", new { transportId = transport.TransportId }, transport));
            }

            return(BadRequest());
        }