private async Task <SendNotificationResult> SendNotificationAsync(Notification notification)
        {
            var retVal         = new SendNotificationResult();
            var apiKey         = _settingsManager.GetSettingByName(_sendGridApiKeySettingName).Value;
            var sendGridClient = new SendGridAPIClient(apiKey);

            var from    = new Email(notification.Sender);
            var to      = new Email(notification.Recipient);
            var content = new Content("text/html", notification.Body);
            var mail    = new Mail(from, notification.Subject, to, content);

            mail.ReplyTo = from;

            try
            {
                SendGrid.CSharp.HTTP.Client.Response result = await sendGridClient.client.mail.send.post(requestBody : mail.Get());

                retVal.IsSuccess = result.StatusCode == HttpStatusCode.Accepted;
                if (!retVal.IsSuccess)
                {
                    retVal.ErrorMessage = result.StatusCode.ToString() + ":" + await result.Body.ReadAsStringAsync();
                }
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message;
            }
            return(retVal);
        }
        public SendNotificationResult SendNotification(Core.Notification.Notification notification)
        {
            var retVal = new SendNotificationResult();

            SendGridMessage mail = new SendGridMessage();

            mail.From = new MailAddress(notification.Sender);
            mail.AddTo(notification.Recipient);
            mail.Subject = notification.Subject;
            mail.Html    = notification.Body;

            var credentials  = new NetworkCredential("*****@*****.**", "j8ddaANMU5Whzcu");
            var transportWeb = new Web(credentials);

            try
            {
                Task.Run(() => transportWeb.DeliverAsync(mail));
                retVal.IsSuccess = true;
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message;
            }

            return(retVal);
        }
        private async Task <SendNotificationResult> SendNotificationAsync(Notification notification)
        {
            var retVal         = new SendNotificationResult();
            var apiKey         = _settingsManager.GetSettingByName(_sendGridApiKeySettingName).Value;
            var sendGridClient = new SendGridClient(apiKey);

            var from = new EmailAddress(notification.Sender);
            var to   = new EmailAddress(notification.Recipient);
            var mail = new SendGridMessage()
            {
                From = from, Subject = notification.Subject, ReplyTo = to, HtmlContent = notification.Body
            };

            mail.AddTo(to);

            try
            {
                var result = await sendGridClient.SendEmailAsync(mail);

                retVal.IsSuccess = result.StatusCode == HttpStatusCode.Accepted;
                if (!retVal.IsSuccess)
                {
                    retVal.ErrorMessage = result.StatusCode.ToString() + ":" + await result.Body.ReadAsStringAsync();
                }
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message;
            }
            return(retVal);
        }
        public async Task Handle(SubscribtionChangedEvent notification, CancellationToken cancellationToken)
        {
            var result = new SendNotificationResult();

            if (notification.SubscriptionType == SubscriptionType.Email)
            {
                var link =
                    $"{jobsOptions.Value.ServiceFullUrl}confirm?token={notification.Token}&mail={notification.Contact}";
                var message = MailTemplate.SubscriptionTemplate(link);
                result = await emailService.SendMessage(notification.Contact, "Potwierdzenie zapisu na powiadomienia", message);
            }
            else if (notification.SubscriptionType == SubscriptionType.Sms)
            {
                var notificationText =
                    notification.ActionType == SubscribtionChangedEvent.SubriptionChangedType.Subscribe
                        ? SMSTemplate.SubscribeTemplate(notification.Token)
                        : SMSTemplate.UnsubscribeTemplate(notification.Token);
                result = await smsService.SendAsync(notificationText, new string[] { notification.Contact });

                logger.Log(LogLevel.Information, result.LogMessage);
            }

            if (!result.IsSuccessful)
            {
                logger.Log(LogLevel.Error, result.LogMessage);
            }
        }
Exemple #5
0
        public SendNotificationResult SendNotification(Notification notification)
        {
            var retVal         = new SendNotificationResult();
            var apiKey         = _settingsManager.GetSettingByName(_sendGridApiKeySettingName).Value;
            var sendGridClient = new SendGridAPIClient(apiKey);

            var from    = new Email(notification.Sender);
            var to      = new Email(notification.Recipient);
            var content = new Content("text/html", notification.Body);
            var mail    = new Mail(from, notification.Subject, to, content);

            mail.ReplyTo = from;

            try
            {
                Task.Run(async() => await sendGridClient.client.mail.send.post(mail.Get())).Wait();
                retVal.IsSuccess = true;
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message;
            }

            return(retVal);
        }
        private async Task <SendNotificationResult> SendNotificationAsync(Notification notification)
        {
            ValidateParameters(notification);

            var result = new SendNotificationResult();

            TwilioClient.Init(_options.AccountId, _options.AccountPassword);

            try
            {
                var message = await MessageResource.CreateAsync(
                    body : notification.Body,
                    from : new Twilio.Types.PhoneNumber(_options.Sender),
                    to : notification.Recipient
                    );

                result.IsSuccess = message.Status != MessageResource.StatusEnum.Failed;
                if (!result.IsSuccess)
                {
                    result.ErrorMessage = $"Twilio sending failed. Error code: {message.ErrorCode}. Error message: {message.ErrorMessage}.";
                }
            }
            catch (ApiException e)
            {
                result.ErrorMessage = $"Twilio Error {e.Code} - {e.MoreInfo}. Exception: {e.Message}";
            }
            catch (Exception e)
            {
                result.ErrorMessage = $"Twilio sending failed. Exception: {e.Message}";
            }

            return(result);
        }
Exemple #7
0
        public SendNotificationResult SendNotification(Notification notification)
        {
            var retVal = new SendNotificationResult();

            try
            {
                MailMessage mailMsg = new MailMessage();

                var emailNotification = notification as EmailNotification;
                //To email
                var recipients = emailNotification.Recipient.Split(';', ',');
                foreach (var email in recipients)
                {
                    mailMsg.To.Add(new MailAddress(email));
                }

                //From email
                mailMsg.From = new MailAddress(emailNotification.Sender);
                mailMsg.ReplyToList.Add(mailMsg.From);

                mailMsg.Subject    = emailNotification.Subject;
                mailMsg.Body       = emailNotification.Body;
                mailMsg.IsBodyHtml = true;
                if (!emailNotification.CC.IsNullOrEmpty())
                {
                    foreach (var ccEmail in emailNotification.CC)
                    {
                        mailMsg.CC.Add(new MailAddress(ccEmail));
                    }
                }
                if (!emailNotification.Bcc.IsNullOrEmpty())
                {
                    foreach (var bccEmail in emailNotification.Bcc)
                    {
                        mailMsg.Bcc.Add(new MailAddress(bccEmail));
                    }
                }

                var login    = _settingsManager.GetSettingByName(_smtpClientLoginSettingName).Value;
                var password = _settingsManager.GetSettingByName(_smtpClientPWDSettingName).Value;
                var host     = _settingsManager.GetSettingByName(_smtpClientHostSettingName).Value;
                var port     = _settingsManager.GetSettingByName(_smtpClientPortSettingName).Value;
                var useSsl   = _settingsManager.GetValue(_smtpClientUseSslSettingName, false);

                SmtpClient smtpClient = new SmtpClient(host, Convert.ToInt32(port));
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(login, password);
                smtpClient.Credentials = credentials;
                smtpClient.EnableSsl   = useSsl;

                smtpClient.Send(mailMsg);
                retVal.IsSuccess = true;
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message + ex.InnerException;
            }

            return(retVal);
        }
        SendNotificationResult INotificationManager.SendNotification(Notification notification)
        {
            var result = new SendNotificationResult();

            //Do not send unregistered notifications
            if (!_unregisteredNotifications.Any(x => x.IsAssignableFrom(notification.GetType())))
            {
                ResolveTemplate(notification);
                result = notification.SendNotification();
            }
            return(result);
        }
Exemple #9
0
        private async Task <SendNotificationResult> SendNotificationAsync(Notification notification)
        {
            var emailNotification = notification as EmailNotification;

            if (emailNotification == null)
            {
                throw new ArgumentException(nameof(notification));
            }

            var retVal         = new SendNotificationResult();
            var apiKey         = _settingsManager.GetSettingByName(_sendGridApiKeySettingName).Value;
            var sendGridClient = new SendGridClient(apiKey);

            var from    = new EmailAddress(emailNotification.Sender);
            var to      = new EmailAddress(emailNotification.Recipient);
            var content = emailNotification.Body;
            var mail    = MailHelper.CreateSingleEmail(from, to, emailNotification.Subject, content, content);

            if (!emailNotification.CC.IsNullOrEmpty())
            {
                foreach (var ccEmail in emailNotification.CC)
                {
                    mail.AddCc(new EmailAddress(ccEmail));
                }
            }
            if (!emailNotification.Bcc.IsNullOrEmpty())
            {
                foreach (var bccEmail in emailNotification.Bcc)
                {
                    mail.AddBcc(new EmailAddress(bccEmail));
                }
            }
            mail.SetReplyTo(from);

            try
            {
                var result = await sendGridClient.SendEmailAsync(mail);

                retVal.IsSuccess = result.StatusCode == HttpStatusCode.Accepted;
                if (!retVal.IsSuccess)
                {
                    retVal.ErrorMessage = result.StatusCode + ":" + await result.Body.ReadAsStringAsync();
                }
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message;
            }
            return(retVal);
        }
        public void Process()
        {
            var criteria = new SearchNotificationCriteria()
            {
                IsActive = true, Take = _sendingBatchSize
            };

            var result = _notificationManager.SearchNotifications(criteria);

            if (result != null && result.Notifications != null && result.Notifications.Count > 0)
            {
                foreach (var notification in result.Notifications)
                {
                    notification.AttemptCount++;
                    SendNotificationResult sendResult = null;
                    try
                    {
                        sendResult = notification.SendNotification();
                    }
                    catch (Exception ex)
                    {
                        sendResult = new SendNotificationResult
                        {
                            IsSuccess    = false,
                            ErrorMessage = ex.ToString()
                        };
                    }

                    if (sendResult.IsSuccess)
                    {
                        notification.IsActive      = false;
                        notification.IsSuccessSend = true;
                        notification.SentDate      = DateTime.UtcNow;
                    }
                    else
                    {
                        if (notification.AttemptCount >= notification.MaxAttemptCount)
                        {
                            notification.IsActive = false;
                        }

                        notification.LastFailAttemptDate    = DateTime.UtcNow;
                        notification.LastFailAttemptMessage = sendResult.ErrorMessage;
                    }

                    _notificationManager.UpdateNotification(notification);
                }
            }
        }
Exemple #11
0
        private async Task <SendNotificationResult> SendNotificationAsync(NotificationBase notification)
        {
            var result = new SendNotificationResult();

            try
            {
                result = await _platformNotificationApi.SendNotificationAsync(notification.ToNotificationDto());
            }
            catch
            {
                result.IsSuccess    = false;
                result.ErrorMessage = "Error occurred while sending notification";
            }

            return(result);
        }
Exemple #12
0
                public SendNotificationResult DeepCopy()
                {
                    var tmp6 = new SendNotificationResult();

                    if ((Success != null) && __isset.success)
                    {
                        tmp6.Success = (global::APIGateway.Thrift.Generated.NotificationTypes.NotificationQueueResponse) this.Success.DeepCopy();
                    }
                    tmp6.__isset.success = this.__isset.success;
                    if ((Ne != null) && __isset.ne)
                    {
                        tmp6.Ne = (global::APIGateway.Thrift.Generated.BaseTypes.NetworkException) this.Ne.DeepCopy();
                    }
                    tmp6.__isset.ne = this.__isset.ne;
                    return(tmp6);
                }
        protected async Task <SendNotificationResult> SendNotificationAsync(Notification notification)
        {
            ValidateParameters(notification);

            var result = new SendNotificationResult();

            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(_options.JsonApiUri);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method      = "POST";

                using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync()))
                {
                    var json = JsonConvert.SerializeObject(new
                    {
                        UserName     = _options.AccountId,
                        Password     = _options.AccountPassword,
                        Originator   = _options.Sender,
                        Recipients   = new[] { notification.Recipient },
                        MessageText  = notification.Body,
                        ForceGSM7bit = false,
                    });

                    await streamWriter.WriteAsync(json);
                }

                var httpResponse = (HttpWebResponse)await httpWebRequest.GetResponseAsync();

                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    dynamic apiResult = JObject.Parse(await streamReader.ReadToEndAsync());
                    var     status    = (string)apiResult.StatusCode ?? string.Empty;
                    result.IsSuccess = status.EqualsInvariant("1");
                    if (!result.IsSuccess)
                    {
                        result.ErrorMessage = $"ASPSMS service returns an error. Status code: {status}. Status info: {apiResult.StatusInfo}";
                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = $"Exception occured while sending sms using ASPSMS: {ex.Message}.";
            }
            return(result);
        }
Exemple #14
0
        public SendNotificationResult SendNotification(Notification notification)
        {
            var result = new SendNotificationResult();

            try
            {
                _client.SendMessage(notification.Recipient, notification.Body);

                result.IsSuccess = true;
            }
            catch (Exception e)
            {
                result.IsSuccess    = false;
                result.ErrorMessage = e.ToString();
            }

            return(result);
        }
Exemple #15
0
        /// <summary>
        /// When clicked, sends the notification.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendButton_Click(object sender, EventArgs e)
        {
            // get and validate Notification data from controls
            notification = GetNotification();
            if (!ValidateNotification(notification))
            {
                return;
            }

            // make a confirmation to prevent the accidentally button click
            DialogResult dialogResult = ShowConfirmMessageBox(
                "Send Notification Confirmation",
                "Do you want to send the notification?"
                );

            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            // insert and get subscribers
            SendNotificationResult result = NotificationDB.SendNotification(notification, ref subscribers);

            switch (result)
            {
            case SendNotificationResult.NoSubscribers:
                ShowInfoMessageBox("Sent Notification Terminated", "No any subscriber");
                return;

            case SendNotificationResult.DatabaseError:
                ShowErrorMessageBox(DatabaseError, "Insert notification failed!");
                return;
            }

            // lock controls until finished
            SetControlsEnabledRecursion(this, false);

            sendingNotificationCount         = 1;
            succeededNotificationsLabel.Text = "Succeeded: 0";
            failedNotificationsLabel.Text    = "Failed: 0";
            sendingEmailsLabel.Text          = "Sending notifications... ( 1 / " + subscribers.Count + " )";
            backgroundWorker.RunWorkerAsync();
        }
        public SendNotificationResult SendNotification(Notification notification)
        {
            var retVal = new SendNotificationResult();

            try
            {
                MailMessage mailMsg = new MailMessage();

                //To email
                mailMsg.To.Add(new MailAddress(notification.Recipient));
                //From email
                mailMsg.From = new MailAddress(notification.Sender);
                mailMsg.ReplyToList.Add(mailMsg.From);

                mailMsg.Subject    = notification.Subject;
                mailMsg.Body       = notification.Body;
                mailMsg.IsBodyHtml = true;

                var login    = _settingsManager.GetSettingByName(_smtpClientLoginSettingName).Value;
                var password = _settingsManager.GetSettingByName(_smtpClientPasswordSettingName).Value;
                var host     = _settingsManager.GetSettingByName(_smtpClientHostSettingName).Value;
                var port     = _settingsManager.GetSettingByName(_smtpClientPortSettingName).Value;
                var useSsl   = _settingsManager.GetValue(_smtpClientUseSslSettingName, false);

                SmtpClient smtpClient = new SmtpClient(host, Convert.ToInt32(port));
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(login, password);
                smtpClient.Credentials = credentials;
                smtpClient.EnableSsl   = useSsl;

                smtpClient.Send(mailMsg);
                retVal.IsSuccess = true;
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message + ex.InnerException;
            }

            return(retVal);
        }
Exemple #17
0
        public SendNotificationResult SendNotification(Notification notification)
        {
            var retVal = new SendNotificationResult();

            var mail = new SendGridMessage();

            mail.From    = new MailAddress(notification.Sender);
            mail.ReplyTo = new[] { mail.From };
            mail.AddTo(notification.Recipient);
            mail.Subject = notification.Subject;
            mail.Html    = notification.Body;

            var userName = _settingsManager.GetSettingByName(_sendGridUserNameSettingName).Value;
            var password = _settingsManager.GetSettingByName(_sendGridPasswordSettingName).Value;

            var credentials  = new NetworkCredential(userName, password);
            var transportWeb = new Web(credentials);

            try
            {
                Task.Run(async() => await transportWeb.DeliverAsync(mail)).Wait();
                retVal.IsSuccess = true;
            }
            catch (Exception ex)
            {
                retVal.ErrorMessage = ex.Message;

                var invalidApiRequestException = ex.InnerException as InvalidApiRequestException;
                if (invalidApiRequestException != null)
                {
                    if (invalidApiRequestException.Errors != null && invalidApiRequestException.Errors.Length > 0)
                    {
                        retVal.ErrorMessage = string.Join(" ", invalidApiRequestException.Errors);
                    }
                }
            }

            return(retVal);
        }