public async Task SendCommand(byte[] payload)
        {
            var command = getCommandFromPayload(payload);

            if (command == null)
            {
                await NotifyError("Command not understood");

                return;
            }
            ICommandResult?commandResult = await GetCommandResult(command);

            switch (commandResult)
            {
            case CommandAccepted commandAccepted:
                //Do nothing, everything went as planned
                break;

            case CommandRejected commandRejected:
                //Oh well, let's throw
                await NotifyError(commandRejected.Reason);

                break;

            case CommandDiscarded commandDiscarded:
                //This command is not acceptable at the state the FSM in in
                await NotifyError("Cannot send this command now");

                break;

            case CommandTimedOut commandTimedOut:
                await NotifyError("The command handler did not respond in a timely fashion");

                break;

            case CommandFailed commandFailed:
                await NotifyError($"An error occurred while handling the command: {commandFailed.Reason}");

                break;

            case ICommandResultWithResponse commandResponse:
                //TODO: should we notify just the sender? Right now we're notifying everybody
                //Should use MQTT5 Request/Response pattern
                //https://www.hivemq.com/blog/mqtt5-essentials-part9-request-response-pattern/
                await notificationSender.SendNotification(commandResponse.Response);

                break;

            default:
                await NotifyError($"Command result not supported: '{commandResult?.GetType().FullName ?? "<null>"}'");

                break;
            }
        }
 /// <summary>
 /// Send notification to Ground Application.
 /// <param name="pRequestId"> Request ID corresponding to the specified request </param>
 /// <param name="pStatus"> Status : Completed/Failed/Processing </param>
 /// </summary>
 private static void SendNotificationToGroundApp(Guid requestId, PIS.Ground.GroundCore.AppGround.NotificationIdEnum status)
 {
     LogManager.WriteLog(TraceType.INFO, String.Format(CultureInfo.CurrentCulture, Logs.INFO_FUNCTION_CALLED, "SendNotificationToGroundApp"), "PIS.Ground.Infotainment.Journaling.JournalingService.SendNotificationToGroundApp", null, EventIdEnum.InfotainmentJournaling);
     try
     {
         _notificationSender.SendNotification(status, null, requestId);
     }
     catch (Exception ex)
     {
         LogManager.WriteLog(TraceType.ERROR, String.Format(CultureInfo.CurrentCulture, Logs.INFO_FUNCTION_EXCEPTION, "SendNotificationToGroundApp"), "PIS.Ground.Infotainment.Journaling.JournalingService.SendNotificationToGroundApp", ex, EventIdEnum.InfotainmentJournaling);
     }
 }
        public void Execute(int productId)
        {
            var product = productRepository.GetById(productId);

            product.Deactivate();
            notificationSender.SendNotification();
        }
        public void PerformTask(InsideModel.Models.Task taskMessage)
        {
            var sendEmailTask = JsonConvert.DeserializeObject <NotificationTaskMessage>(taskMessage.Message);

            var contactId = sendEmailTask.ContactId;
            var contactNotificationToSend = contactRepository.Where(c => c.Id == contactId)
                                            .Include(l => l.Client);

            if (!contactNotificationToSend.Any())
            {
                return;
            }
            var client = contactNotificationToSend.First().Client;

            if (!client.IsActive)
            {
                return;
            }
            if (!client.Labels.Where(l => l.Name == "Helloypaket").Any())
            {
                return;
            }

            var notificationText = notificationPhoneTextBuilder.GetDefinition(contactId);

            phoneNotificationSender.SendNotification(client.Id, notificationText);
        }
Ejemplo n.º 5
0
        public void NotifyFailureOf(Fault <OrderIsBackorderedMessage> fault)
        {
            IList <EmailAddress> recipients = new List <EmailAddress>
            {
                new EmailAddress {
                    Address = EmailAddressConstants.InformationtechnologygroupEmailAddress
                }
            };

            if (fault.FailedMessage.BusinessPartnerCode.Contains("WWT"))
            {
                recipients.Add(new EmailAddress {
                    Address = EmailAddressConstants.LogisticsEmailAddress
                });
            }

            if (fault.FailedMessage.BusinessPartnerCode.Contains("FEDE"))
            {
                //TODO: email account manager???
            }

            string body = string.Format(
                @"Failed Message:
                                {0}

                              Caught Execption
                                {1}
                            ", fault.FailedMessage, fault.CaughtException);

            _notificationSender.SendNotification("Failure occured processing this Backordered Order Message", recipients, body);
        }
Ejemplo n.º 6
0
        public IActionResult OnPostSend()
        {
            if (!ModelState.IsValid)
            {
                return(this.Page());
            }

            if (!this.User.Claims.Any())
            {
                return(RedirectToAction("login", "account", new { area = "identity" }));
            }

            var userId = this.User.Claims
                         .Where(c => c.Type == ClaimTypes.NameIdentifier)
                         .FirstOrDefault()
                         .Value;

            if (string.IsNullOrWhiteSpace(this.Feedback))
            {
                return(this.Page());
            }

            var feedback = new Feedback()
            {
                Message  = this.Feedback,
                AuthorId = userId
            };

            notificationSender.SendNotification(Constants.FeedbackSentMessage, MessageType.Success, pageModel: this);

            return(RedirectToAction("index", "home"));
        }
Ejemplo n.º 7
0
        public void OpenAccount()
        {
            Customer customer = new Customer()
            {
                FirstName   = "Dhanik",
                LastName    = "Sahni",
                DateOfBorth = new DateTime(1981, 07, 05),
                Address     = new Address
                {
                    Address1 = "SVF",
                    Address2 = "Lal Kuan",
                    City     = "Ghaziabad",
                    State    = "UP",
                    Zip      = "201002"
                },
                Contact = new Contact
                {
                    Email = "*****@*****.**",
                    Fax   = "3234234242"
                }
            };

            //Concreate Object
            emailSender.SendNotification(customer);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> MakeModerator(string id)
        {
            var user = this.Context.Users.Find(id);

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

            await userManager.AddToRoleAsync(user, Constants.ModeratorRole);

            notificationSender.SendNotification(String.Format(Constants.UserPromotedMessage, user.UserName), MessageType.Success, controller: this);


            return(RedirectToAction("All", new { area = "admin", controller = "users" }));
        }
Ejemplo n.º 9
0
        public IActionResult Add(string message, int postId)
        {
            //Create an attribute for this
            if (this.User.Claims.Count() == 0)
            {
                return(RedirectToAction("login", "account", new { area = "identity" }));
            }

            if (string.IsNullOrWhiteSpace(message))
            {
                return(RedirectToAction("index", "home"));
            }

            var userId = this.User.Claims
                         .Where(c => c.Type == ClaimTypes.NameIdentifier)
                         .FirstOrDefault()
                         .Value;

            var comment = new Comment()
            {
                DatePosted = DateTime.Now,
                Message    = message,
                AuthorId   = userId,
                PostId     = postId
            };

            this.Context.Comments.Add(comment);
            this.Context.SaveChanges();

            notificationSender.SendNotification(Constants.UserAddedComment, MessageType.Success, controller: this);

            return(RedirectToAction("details", "posts", new { id = comment.PostId }));
        }
        public void SendActivationRequest(ActivationRequest activationRequest)
        {
            Template activationTemplate = _templateRepository.Get("ActivationTemplate.html");
            string   notification       = activationTemplate.Apply(activationRequest.ToDictionary());

            _notificationSender.SendNotification(notification, activationRequest.Email.Value);
        }
Ejemplo n.º 11
0
 protected override async Task ExecuteAsync(CancellationToken stoppingToken)
 {
     while (!stoppingToken.IsCancellationRequested)
     {
         await _notificationSender.SendNotification(stoppingToken);
     }
 }
Ejemplo n.º 12
0
        private IEnumerable <IEdiMessage> processPartner(DocumentAssignments assignment)
        {
            var fileParser = assignment.Partner.Parser();
            var documents  = new List <IEdiMessage>();
            var segList    = assignment.Documents;

            foreach (var doc in segList)
            {
                var segments = doc.Segments;
                var file     = doc.File;
                try
                {
                    var docs = fileParser.Parse(segments);
                    if (docs.Count() > 0)
                    {
                        documents.AddRange(docs.Where(d => d != null));
                        moveFileToArchive(file);
                    }
                }
                catch (Exception e)
                {
                    Logger.Error(this, "Error processing file ", e);
                    _notificationSender.SendNotification("Failure processing incoming file", getRecipientList(),
                                                         string.Format("The file {0} could not be processed.  The file is being moved to the Error folder.  Error message: {1}", doc.File, e));
                    moveFileToErrorFolder(file);
                }
            }
            return(documents);
        }
Ejemplo n.º 13
0
        public void Process(ReviewSession session)
        {
            _repository.SaveReviewSession(session);

            MailMessage message = _generator.CreateContentAddedNotification();

            _sender.SendNotification(message);
        }
Ejemplo n.º 14
0
 // GET: /<controller>/
 public IActionResult Index()
 {
     if (loggerFactory != null)
     {
         var logger = loggerFactory.CreateLogger("TEST");
         logger.Log(LogLevel.Critical, "Danger Will Robinson");
     }
     notificationSender.SendNotification("Runing Index Action");
     return(Content("Index"));
 }
Ejemplo n.º 15
0
        public IActionResult OnPostCreate()
        {
            if (!ModelState.IsValid)
            {
                return(this.Page());
            }

            var category = this.Context.Categories.FirstOrDefault(c => c.Name == this.Name);

            if (category != null)
            {
                notificationSender.SendNotification(String.Format(Constants.CategoryAlreadyExistsMessage, category.Name), MessageType.Danger, pageModel: this);
                return(this.Page());
            }
            var bannerExtension = BannerUrl.Substring(BannerUrl.LastIndexOf('.'));

            var bannerFileName = String.Format(Constants.CategoryBannerName, this.Name, bannerExtension);

            var wwwRootPath = this.hostingEnvironment.WebRootPath;

            var bannerPath = wwwRootPath + Constants.CategoriesBannerPathFromWebRoot + bannerFileName;

            ImageUtilities.SaveCategoryBannerFromUrl(bannerPath, this.BannerUrl);

            category = new Category()
            {
                Name   = this.Name,
                Banner = bannerFileName
            };

            this.Context.Categories.Add(category);
            this.Context.SaveChangesAsync();

            notificationSender.SendNotification(String.Format(Constants.CategoryCreatedMessage, category.Name), MessageType.Success, pageModel: this);

            return(this.Redirect("/home/index"));
        }
 /// <summary>Sends a notification to Ground App.</summary>
 /// <param name="requestId">Request ID for the corresponding request.</param>
 /// <param name="status">Processing status.</param>
 /// <param name="parameter">The generic notification parameter.</param>
 private static void SendNotificationToGroundApp(
     Guid requestId,
     PIS.Ground.GroundCore.AppGround.NotificationIdEnum status,
     string parameter)
 {
     LogManager.WriteLog(TraceType.INFO, String.Format(CultureInfo.CurrentCulture, Logs.INFO_FUNCTION_CALLED, "SendNotificationToGroundApp"), "PIS.Ground.LiveVideoControl.LiveVideoControlService.SendNotificationToGroundApp", null, EventIdEnum.Mission);
     try
     {
         //send notification to ground app
         _notificationSender.SendNotification(status, parameter, requestId);
     }
     catch (Exception ex)
     {
         LogManager.WriteLog(TraceType.ERROR, String.Format(CultureInfo.CurrentCulture, Logs.INFO_FUNCTION_EXCEPTION, "SendNotificationToGroundApp"), "PIS.Ground.LiveVideoControl.LiveVideoControlService.SendNotificationToGroundApp", ex, EventIdEnum.Mission);
     }
 }
Ejemplo n.º 17
0
 /// <summary>Sends a notification to Ground App.</summary>
 /// <param name="requestId">Request ID for the corresponding request.</param>
 /// <param name="status">Processing status.</param>
 /// <param name="parameter">The generic notification parameter.</param>
 private static void SendNotificationToGroundApp(
     Guid requestId,
     PIS.Ground.GroundCore.AppGround.NotificationIdEnum status,
     string parameter)
 {
     try
     {
         _notificationSender.SendNotification(status, parameter, requestId);
     }
     catch (Exception ex)
     {
         LogManager.WriteLog(TraceType.ERROR, ex.Message,
                             "PIS.Ground.LiveVideoControl.RequestProcessor.SendNotificationToGroundApp",
                             ex, EventIdEnum.LiveVideoControl);
     }
 }
Ejemplo n.º 18
0
        public void Transfer(IAccount transferor, IAccount tranferee, decimal amount)
        {
            transferor.Withdraw(amount);
            tranferee.Deposit(amount);

            var transactionMessage = $"Transferred £{amount} from {transferor.AccountNumber} to {tranferee.AccountNumber}.";

            transactionLogger.Log(transactionMessage);

            notificationSender.SendNotification(
                "*****@*****.**",
                new List <string> {
                transferor.RetrieveNotificationEmail(),
                tranferee.RetrieveNotificationEmail()
            },
                "Transfer notification",
                transactionMessage);
        }
Ejemplo n.º 19
0
 /// <summary>Sends a notification to Ground App.</summary>
 /// <param name="requestId">Request ID for the corresponding request.</param>
 /// <param name="status">Processing status.</param>
 /// <param name="parameter">The generic notification parameter.</param>
 private void SendNotificationToGroundApp(
     Guid requestId,
     PIS.Ground.GroundCore.AppGround.NotificationIdEnum status,
     string parameter)
 {
     try
     {
         if (_notificationSender != null)
         {
             _notificationSender.SendNotification(status, parameter, requestId);
         }
         else
         {
             DataPackageService.mWriteLog(TraceType.ERROR, System.Reflection.MethodBase.GetCurrentMethod().Name, null, Logs.ERROR_UNDEFINED_NOTIFICATION_SENDER, EventIdEnum.DataPackage);
         }
     }
     catch (Exception ex)
     {
         DataPackageService.mWriteLog(TraceType.ERROR, System.Reflection.MethodBase.GetCurrentMethod().Name, ex, ex.Message, EventIdEnum.DataPackage);
     }
 }
Ejemplo n.º 20
0
        public IActionResult Delete(int id)
        {
            if (id <= 0)
            {
                return(NotFound());
            }

            var comment = this.Context.Comments.Find(id);

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

            this.Context.Comments.Remove(comment);
            this.Context.SaveChanges();

            notificationSender.SendNotification(Constants.ModeratorDeletedCommentMessage, MessageType.Success, controller: this);

            return(RedirectToAction("all", "comments", new { area = "moderator" }));
        }
Ejemplo n.º 21
0
        public void NotifyFailureOf(Fault <InvoicedOrderMessage> fault)
        {
            IList <EmailAddress> recipients = new List <EmailAddress>
            {
                new EmailAddress {
                    Address = EmailAddressConstants.InformationtechnologygroupEmailAddress
                },
                new EmailAddress {
                    Address = EmailAddressConstants.AccountsReceivableEmailAddress
                }
            };

            string body = string.Format(
                @"Failed Message:
                                {0}

                              Caught Execption
                                {1}
                            ", fault.FailedMessage, fault.CaughtException);

            _notificationSender.SendNotification("Failure occured processing this Invoiced Order Message", recipients, body);
        }
Ejemplo n.º 22
0
        public void OnNext(Event value)
        {
            switch (value.EventType)
            {
            case EventType.ReviewerAssigned:
            case EventType.ReviewSessionReleased:
            case EventType.QuestionnaireCompleted:
                try
                {
                    var message = GenerateMessage(value.EntityId, value);
                    _sender.SendNotification(message);
                    value.Recevied = true;
                }
                catch (Exception ex)
                {
                    log.Error("Email Notification Failed", ex);
                }
                break;

            default:
                return;
            }
        }
Ejemplo n.º 23
0
        public void can_send_notification()
        {
            //Arrange
            IEnumerable <EmailAddress> recipients = new List <EmailAddress>();
            var emailServiceEndpoint = new Mock <IEndpoint>();

            _endpointResolver.Setup(x => x.GetEndpoint(new Uri(_emailServiceEndpointUri.ToString()))).Returns(emailServiceEndpoint.Object);

            //Act
            string body    = "test body";
            string subject = "test";

            _sut.SendNotification(subject, recipients, body);

            //Assert
            emailServiceEndpoint.Verify(ep => ep.Send(
                                            It.Is <SendNotificationMessage>(m => m.Body == body &&
                                                                            m.Subject == subject &&
                                                                            m.From.Address ==
                                                                            EmailAddressConstants.
                                                                            InformationtechnologygroupEmailAddress &&
                                                                            m.Recipients == recipients)));
            _endpointResolver.VerifyAll();
        }
Ejemplo n.º 24
0
 public void GenerateTimeEntryReport(IPersonnel personnel)
 {
     // processing here
     _notificationSender.SendNotification($"{ReportName}: Report created.");
 }
Ejemplo n.º 25
0
 private async Task Notify(object domainEvent)
 {
     await notificationSender.SendNotification(new DomainEventResponse(domainEvent));
 }
Ejemplo n.º 26
0
        private void SendNotification(Guid subscriptionId, NotificationBase notification, int attemptsLeft, INotificationSender notificationSender, IMessageScheduler messageScheduler)
        {
            var response = notificationSender.SendNotification(_notificationChannel, notification);

            var toastNotification = notification as ToastNotification;
            var rawNotification = notification as RawNotification;
            var tileNotification = notification as TileNotification;

            if (response.HttpStatusCode == 200)
            {
                if (response.NotificationStatus == "Received")
                {
                    if (toastNotification != null)
                        PublishEvent(new ToastNotificationSucceededEvent(subscriptionId, toastNotification.NotificationId, attemptsLeft, toastNotification.Title, toastNotification.Body));
                    else if (rawNotification != null)
                        PublishEvent(new RawNotificationSucceededEvent(subscriptionId, rawNotification.NotificationId, attemptsLeft, rawNotification.RawContent));
                    else if (tileNotification != null)
                        PublishEvent(new TileNotificationSucceededEvent(subscriptionId, tileNotification.NotificationId, attemptsLeft, tileNotification.Title, tileNotification.BackgroundUri, tileNotification.Counter, tileNotification.BackTitle, tileNotification.BackContent, tileNotification.BackBackgroundUri));
                    return;
                }
            }

            // Something went wrong somehow. First, let's publish an event saing so.
            if (toastNotification != null)
                PublishEvent(new ToastNotificationFailedEvent(subscriptionId, toastNotification.NotificationId, attemptsLeft, DateTime.Now, response.HttpStatusCode, response.NotificationStatus, response.DeviceConnectionStatus, response.SubscriptionStatus, toastNotification.Title, toastNotification.Body));
            else if (rawNotification != null)
                PublishEvent(new RawNotificationFailedEvent(subscriptionId, rawNotification.NotificationId, attemptsLeft, DateTime.Now, response.HttpStatusCode, response.NotificationStatus, response.DeviceConnectionStatus, response.SubscriptionStatus, rawNotification.RawContent));
            else if (tileNotification != null)
                PublishEvent(new TileNotificationFailedEvent(subscriptionId, tileNotification.NotificationId, attemptsLeft, DateTime.Now, response.HttpStatusCode, response.NotificationStatus, response.DeviceConnectionStatus, response.SubscriptionStatus, tileNotification.Title, tileNotification.BackgroundUri, tileNotification.Counter, tileNotification.BackTitle, tileNotification.BackContent, tileNotification.BackBackgroundUri));

            // Next let's figure out what to do next
            var resendTime = DateTime.Now;
            var shouldAttemptAgain = false;

            if (response.NotificationStatus == "QueueFull"  || response.HttpStatusCode == 503)
            {
                // Service currently full or unavailable.
                resendTime = resendTime.AddMinutes(1); // TODO Increase exponentially
                shouldAttemptAgain = true;
            }
            else if (response.NotificationStatus == "Suppressed")
            {
                shouldAttemptAgain = false;
            }
            else if (response.NotificationStatus == "Dropped" && response.SubscriptionStatus == "Expired")
            {
                // Subscription Expired. Don't attempt again and unregister this client.
                shouldAttemptAgain = false;
                Unregister();
            }
            else if (response.NotificationStatus == "Dropped" && response.SubscriptionStatus == "Active")
            {
                // Rate limit reached. Attempt to resend in one hour
                resendTime = resendTime.AddHours(1);
                shouldAttemptAgain = true;
            }
            else if (response.NotificationStatus == "Dropped" && response.DeviceConnectionStatus == "Inactive")
            {
                resendTime = resendTime.AddHours(1);
                shouldAttemptAgain = true;
            }

            // Should we re-try?
            if (shouldAttemptAgain)
            {
                attemptsLeft--;
                if (toastNotification != null)
                    messageScheduler.ScheduleMessage(new SendToastNotificationCommand(this.Id, subscriptionId, toastNotification.NotificationId, toastNotification.Title, toastNotification.Body, attemptsLeft), resendTime);
                else if (rawNotification != null)
                    messageScheduler.ScheduleMessage(new SendRawNotificationCommand(this.Id, subscriptionId, rawNotification.NotificationId, rawNotification.RawContent, attemptsLeft), resendTime);
                else if (tileNotification != null)
                    messageScheduler.ScheduleMessage(new SendTileNotificationCommand(this.Id, subscriptionId, tileNotification.NotificationId, tileNotification.Title, tileNotification.Counter, tileNotification.BackgroundUri, tileNotification.BackTitle, tileNotification.BackContent, tileNotification.BackBackgroundUri, attemptsLeft), resendTime);
            }
        }
Ejemplo n.º 27
0
 private void SendNotification(User user)
 {
     notificationService.SendNotification($"User {user.Name} created");
 }