Example #1
0
        public void SendMessage(NotificationMessageDto notificationMessage)
        {
            var factory = new ConnectionFactory
            {
                HostName = "localhost",
                Port     = 5672
            };

            using var connection = factory.CreateConnection();
            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "trigger", type: ExchangeType.Fanout);

                var message = JsonSerializer.Serialize(notificationMessage);
                var body    = Encoding.UTF8.GetBytes(message);

                channel.BasicPublish(
                    exchange: "trigger",
                    routingKey: "",
                    basicProperties: null,
                    body: body);

                Console.WriteLine(" --> Message Published on Message Bus");
            };
        }
Example #2
0
        private async Task AddMessageAsync(NotificationMessageDto notificationMessageDto,
                                           RtEntityId?associatedRtId)
        {
            var notificationMessageInputDto = new NotificationMessageInputDto
            {
                SubjectText      = notificationMessageDto.SubjectText,
                BodyText         = notificationMessageDto.BodyText,
                RecipientAddress = notificationMessageDto.RecipientAddress,
                SendStatus       = notificationMessageDto.SendStatus,
                NotificationType = notificationMessageDto.NotificationType,
                LastTryDateTime  = DateTime.MinValue
            };

            if (associatedRtId != null)
            {
                notificationMessageInputDto.RelatesTo = new[]
                {
                    new RtAssociationInputDto
                    {
                        Target = associatedRtId.Value, ModOption = AssociationModOptionsDto.Create
                    }
                };
            }

            var query = new GraphQLRequest
            {
                Query     = GraphQl.CreateNotificationMessage,
                Variables = new { entities = new[] { notificationMessageInputDto } }
            };

            await _tenantClient.SendMutationAsync <IEnumerable <RtServiceHookDto> >(query);
        }
Example #3
0
        private async Task AddMessageAsync(string tenantId, NotificationMessageDto notificationMessageDto, RtEntityId?targetRtId)
        {
            ArgumentValidation.ValidateString(nameof(tenantId), tenantId);
            ArgumentValidation.Validate(nameof(notificationMessageDto), notificationMessageDto);


            var tenantContext = await _systemContext.CreateOrGetTenantContext(tenantId);

            var session = await tenantContext.Repository.StartSessionAsync();

            session.StartTransaction();

            var rtEntity = CreateRtEntity(notificationMessageDto, tenantContext);

            var associationUpdateInfos = new List <AssociationUpdateInfo>();

            if (targetRtId != null)
            {
                associationUpdateInfos.Add(new AssociationUpdateInfo(rtEntity.ToRtEntityId(), targetRtId.Value, Constants.RelatedRoleId, AssociationModOptionsDto.Create));
            }

            await tenantContext.Repository.ApplyChanges(session, new[]
            {
                new EntityUpdateInfo(rtEntity, EntityModOptions.Create)
            }, associationUpdateInfos);

            await session.CommitTransactionAsync();
        }
Example #4
0
        public async Task AddEMailMessageAsync(string tenantId, string emailAddress, string subject,
                                               string htmlMessage, RtEntityId?associatedRtId)
        {
            ArgumentValidation.ValidateString(nameof(tenantId), tenantId);
            ArgumentValidation.ValidateString(nameof(emailAddress), emailAddress);
            ArgumentValidation.ValidateString(nameof(subject), subject);
            ArgumentValidation.ValidateString(nameof(htmlMessage), htmlMessage);

            try
            {
                var notificationMessage = new NotificationMessageDto
                {
                    SendStatus       = SendStatusDto.Pending,
                    SubjectText      = subject,
                    BodyText         = htmlMessage,
                    RecipientAddress = emailAddress,
                    NotificationType = NotificationTypesDto.EMail,
                    LastTryDateTime  = DateTime.MinValue
                };

                await AddMessageAsync(tenantId, notificationMessage, associatedRtId);
            }
            catch (Exception e)
            {
                throw new NotificationSendFailedException("Message send failed.", e);
            }
        }
        public async Task <IActionResult> UpdateFlight(Guid flightId, [FromBody] FlightDetailForUpdateDto flightToUpdate)
        {
            var flight = await _repo.FlightDetailS.Where(x => x.Id.Equals(flightId)).SingleOrDefaultAsync();

            if (flight == null)
            {
                return(NotFound("Flight Id Doesnot Exist"));
            }


            var oldPrice = flight.Price;
            var newPrice = flightToUpdate.Price;

            if (oldPrice == newPrice)
            {
                return(BadRequest("The old price and new price is same"));
            }


            _mapper.Map(flightToUpdate, flight);
            _repo.FlightDetailS.Update(flight);
            await _repo.SaveChangesAsync();


            NotificationMessageDto notificationMessageDto = new NotificationMessageDto()
            {
                FlightCode  = flight.FlightCode,
                WebhookType = "PriceChange",
                OldPrice    = oldPrice,
                NewPrice    = newPrice
            };

            _messageBusClient.SendMessage(notificationMessageDto);
            return(NoContent());
        }
Example #6
0
        private static RtSystemNotificationMessage CreateRtEntity(NotificationMessageDto notificationMessageDto,
                                                                  ITenantContext tenantContext)
        {
            var rtEntity = tenantContext.Repository.CreateTransientRtEntity <RtSystemNotificationMessage>();

            ApplyDtoData(notificationMessageDto, rtEntity);

            return(rtEntity);
        }
Example #7
0
 /// <summary>
 /// Verifies the token and email specified.
 /// </summary>
 private void VerifyNotificationData(NotificationMessageDto notificationMessageDto)
 {
     if (notificationMessageDto == null ||
         string.IsNullOrWhiteSpace(notificationMessageDto.AppToken) ||
         string.IsNullOrWhiteSpace(notificationMessageDto.Message) ||
         string.IsNullOrWhiteSpace(notificationMessageDto.UserId))
     {
         throw new ArgumentNullException();
     }
 }
        public async Task <HttpStatusCode> HandleEvent(NotificationMessageDto message)
        {
            switch (message.EventType)
            {
            case "INVOICING.INVOICE.CREATED":
                return(await InvoiceCreated(message));

            default:
                return(HttpStatusCode.NotFound);
            }
        }
 public async Task <HttpStatusCode> HandleEvent(NotificationMessageDto message)
 {
     if (message.EventType != "")
     {
         return(HttpStatusCode.OK);
     }
     else
     {
         return(HttpStatusCode.BadRequest);
     }
 }
        /// <summary>
        /// Re-sends specified notification message
        /// </summary>
        /// <param name="notificationMessage"></param>
        /// <returns></returns>
        public async Task ResendMessageAsync(NotificationMessageDto notificationMessage)
        {
            if (notificationMessage.SendType == null ||
                notificationMessage.SendType.ItemValue != (int)NotificationType)
            {
                return;
            }

            var message = await NotificationMessageRepository.GetAsync(notificationMessage.Id);

            await SendNotificationInternalAsync(message);
        }
        public string CreateHashMessage(string key, NotificationMessageDto msg)
        {
            //pamtimo notifikaciju koju treba da saljemo korisnicima
            string hashKey = key + ":" + MsgPostfix;

            _redis.SetEntryInHash(hashKey, "message", msg.Message);
            _redis.SetEntryInHash(hashKey, "createdAt", msg.CreatedAt.ToString());
            _redis.SetEntryInHash(hashKey, "creator", msg.Creator);
            TimeSpan timeSpan = new TimeSpan(0, 0, ttl);

            _redis.ExpireEntryIn(hashKey, timeSpan);
            return(hashKey);
        }
Example #12
0
 private static void ApplyDtoData(NotificationMessageDto notificationMessageDto, RtSystemNotificationMessage rtEntity)
 {
     rtEntity.SubjectText      = notificationMessageDto.SubjectText;
     rtEntity.BodyText         = notificationMessageDto.BodyText;
     rtEntity.RecipientAddress = notificationMessageDto.RecipientAddress;
     rtEntity.SentDateTime     = notificationMessageDto.SentDateTime;
     rtEntity.LastTryDateTime  = notificationMessageDto.LastTryDateTime;
     rtEntity.ErrorText        = notificationMessageDto.ErrorText;
     rtEntity.SendStatus       = notificationMessageDto.SendStatus == null
         ? SendStatus.Pending
         : (SendStatus)notificationMessageDto.SendStatus;
     rtEntity.NotificationType = notificationMessageDto.NotificationType == null
         ? NotificationTypes.EMail
         : (NotificationTypes)notificationMessageDto.NotificationType;
 }
        public async Task <IHttpActionResult> PostSendMessage([FromBody] NotificationMessageDto notificationMessageDto)
        {
            try
            {
                await _notificationsManager.SendMessageToUser(notificationMessageDto);

                return(Ok());
            }
            catch (AuthenticationException)
            {
                return(BadRequest("Authentication was not approved"));
            }
            catch (Exception)
            {
                return(InternalServerError());
            }
        }
        public async Task <HttpStatusCode> HandleEvent(NotificationMessageDto message)
        {
            switch (message.EventType)
            {
            case "BILLING.SUBSCRIPTION.CANCELLED":
                return(await SubscriptionCancelled(message));

            case "BILLING.SUBSCRIPTION.ACTIVATED":
                return(await SubscriptionCancelled(message));

            case "BILLING.SUBSCRIPTION.SUSPENDED":
                return(await SubscriptionCancelled(message));

            default:
                return(HttpStatusCode.NotFound);
            }
        }
        public IActionResult UpdateFlightDetail(string flightCode, FlightDetailUpdateDto flightToUpdate)
        {
            var flight = _context.FlightDetails.FirstOrDefault(f => f.FlightCode == flightCode);

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

            var oldPrice = flight.PricePerSeat;

            _mapper.Map(flightToUpdate, flight);

            try
            {
                _context.SaveChanges();

                if (oldPrice != flight.PricePerSeat)
                {
                    Console.WriteLine("Price changed - Place message on bus");

                    var message = new NotificationMessageDto
                    {
                        WebhookType     = "pricechange",
                        OldPricePerSeat = oldPrice,
                        NewPricePerSeat = flight.PricePerSeat,
                        FlightCode      = flight.FlightCode
                    };

                    _messageBus.SendMessage(message);
                }
                else
                {
                    Console.WriteLine("No Price change");
                }

                return(NoContent());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }

            return(NoContent());
        }
        public async Task <ActionResult> UpdateFlightDetail(int id, FlightDetailUpdateDto flightDetailUpdateDto)
        {
            var flight = await _context.FlightDetails.FirstOrDefaultAsync(f => f.Id == id);

            if (flight is null)
            {
                return(await Task.FromResult(NotFound()));
            }

            decimal oldPrice = flight.Price;

            _mapper.Map(flightDetailUpdateDto, flight);

            try
            {
                await _context.SaveChangesAsync();

                if (oldPrice != flight.Price)
                {
                    Console.WriteLine("Price changed - Place message on bus");
                    var message = new NotificationMessageDto
                    {
                        WebhookType = "pricechange",
                        OldPrice    = oldPrice,
                        NewPrice    = flight.Price,
                        FlightCode  = flight.FlightCode
                    };
                    _messageBusClient.SendMessage(message);
                }
                else
                {
                    Console.WriteLine("No price change");
                }

                return(await Task.FromResult(NoContent()));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
        }
Example #17
0
        public ActionResult UpdateFlightDetail(int id, FlightDetailUpdateDto flightDetailUpdateDto)
        {
            var flight = _context.FlightDetails.FirstOrDefault(f => f.Id == id);

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

            decimal oldPrice = flight.Price;

            _mapper.Map(flightDetailUpdateDto, flight);

            try
            {
                _context.SaveChanges();

                if (oldPrice != flight.Price)
                {
                    Console.WriteLine("Price changed - Place message on bus");

                    var message = new NotificationMessageDto
                    {
                        WebhookType = "Price Change",
                        OldPrice    = oldPrice,
                        // TODO: TYPO
                        NewPrice   = flight.Price,
                        FlightCode = flight.FlightCode,
                    };
                    _messageBus.SendMessage(message);
                }
                else
                {
                    Console.WriteLine("No price change");
                }
                return(NoContent());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #18
0
        public async void SendNotification(NotificationMessageDto msg)
        {
            var query = _client.Cypher.Match("(p)-[:Follow]-(u:User)")
                        .Where("id(p)=" + msg.PostId)
                        .With("u.Username as name")
                        .Return((name) => new
            {
                Users = name.CollectAsDistinct <String>()
            });
            var users = await query.ResultsAsync;

            if (users.First().Users.Count() == 0)
            {
                return;
            }
            var    key    = _rms.GenerateKeyWithPrefix(msg.PostId.ToString());
            string msgKey = _rms.CreateSetMessage(key, users.First().Users);

            string hashKey = _rms.CreateHashMessage(key, msg);
            await _hubContext.Clients.Group(msg.PostId.ToString()).SendAsync("ReceiveMessage", new { msg, key });
        }
Example #19
0
        public async Task Invoke(HttpContext httpContext)
        {
            if (httpContext.Request.Path.Equals(_config.EndpointPath, StringComparison.Ordinal) &&
                httpContext.Request.Method == HttpMethods.Post)
            {
                if (!httpContext.User.HasClaim(x => x.Type == ClaimTypes.Authentication && x.Value == "true"))
                {
                    await httpContext.ChallengeAsync(EventRequestAuthenticationDefaults.AuthenticationScheme);
                }
                else
                {
                    string body = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
                    try
                    {
                        NotificationMessageDto message = JsonConvert.DeserializeObject<NotificationMessageDto>(body);
                        message.TypedResourceType = GetDtoTypeFromResource(message.ResourceType);

                        if (httpContext.Items.TryAdd("Message", message))
                        {
                            await _next.Invoke(httpContext);
                        }
                        else
                        {
                            httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                            await httpContext.Response.WriteAsync($"Failed to deserialize message! Resource type was: {message.ResourceType}");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError($"{DateTime.Now}: Bad request encountered. Failed to deserialize message with error: {ex.Message}");
                        httpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        await httpContext.Response.WriteAsync($"Bad request!");
                    }
                }
            }
            else
            {
                await _next.Invoke(httpContext);
            }
        }
Example #20
0
        /// <summary>
        /// Sends a message to a user.
        /// </summary>
        /// <param name="notificationMessageDto"></param>
        /// <returns></returns>
        public async Task SendMessageToUser(NotificationMessageDto notificationMessageDto)
        {
            try
            {
                VerifyNotificationData(notificationMessageDto);
                string userId = await _commonOperationsManager.VerifyToken(notificationMessageDto.AppToken);

                await _notificationsHelper.SendMessageToUser(notificationMessageDto.Message, notificationMessageDto.UserId);
            }
            catch (ArgumentNullException)
            {
                throw new ArgumentNullException();
            }
            catch (AuthenticationException)
            {
                throw new AuthenticationException();
            }
            catch (Exception e)
            {
                throw new Exception();
            }
        }
Example #21
0
        /// inheritedDoc
        public async Task ResendMessageAsync(NotificationMessageDto notificationMessage)
        {
            var notifierTypes = _notificationConfiguration.Notifiers
                                .Where(t => typeof(IShaRealTimeNotifier).IsAssignableFrom(t)).ToList();

            foreach (var notifierType in notifierTypes)
            {
                try
                {
                    using (var notifier = _iocResolver.ResolveAsDisposable <IShaRealTimeNotifier>(notifierType))
                    {
                        if ((int)notifier.Object.NotificationType == notificationMessage.SendType?.ItemValue)
                        {
                            await notifier.Object.ResendMessageAsync(notificationMessage);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.ToString(), ex);
                }
            }
        }
Example #22
0
        public async Task AddShortMessageAsync(string tenantId, string toPhoneNumber, string message, RtEntityId?associatedRtId)
        {
            ArgumentValidation.ValidateString(nameof(tenantId), tenantId);
            ArgumentValidation.ValidateString(nameof(toPhoneNumber), toPhoneNumber);
            ArgumentValidation.ValidateString(nameof(message), message);

            try
            {
                var notificationMessage = new NotificationMessageDto
                {
                    SendStatus       = SendStatusDto.Pending,
                    BodyText         = message,
                    RecipientAddress = toPhoneNumber,
                    NotificationType = NotificationTypesDto.Sms,
                    LastTryDateTime  = DateTime.MinValue
                };

                await AddMessageAsync(tenantId, notificationMessage, associatedRtId);
            }
            catch (Exception e)
            {
                throw new NotificationSendFailedException("Message send failed.", e);
            }
        }
        /// <summary>
        /// Sends a notification to a specific user.
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendNotification(string userId, string message, string appToken)
        {
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    var notificationDto = new NotificationMessageDto()
                    {
                        UserId = userId, Message = message, AppToken = appToken
                    };

                    var response = await httpClient.PostAsJsonAsync(_notificationsBaseUrl + "Notifications/SendMessage", notificationDto).ConfigureAwait(false);

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new ApplicationException("Notification was not sent");
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
 private async Task <HttpStatusCode> InvoiceCreated(NotificationMessageDto message)
 {
     return(HttpStatusCode.OK);
 }
 private async Task <HttpStatusCode> SubscriptionSuspended(NotificationMessageDto message)
 {
     return(HttpStatusCode.OK);
 }
Example #26
0
        private static async Task <RtSystemNotificationMessage> PrepareUpdateRtEntityAsync(IOspSession session, NotificationMessageDto notificationMessageDto,
                                                                                           ITenantContext tenantContext)
        {
            var rtEntity = await tenantContext.Repository.GetRtEntityAsync <RtSystemNotificationMessage>(session, notificationMessageDto.ToRtEntityId());

            ApplyDtoData(notificationMessageDto, rtEntity);

            return(rtEntity);
        }