コード例 #1
0
        [Fact]//(Skip = "Test to see if mail is inboxed")]
        public async Task EmailSenderShouldSendWithTemplate()
        {
            var factory = new SendGridMailFactory(new OptionsWrapper <MailOptions>(new MailOptions()
            {
                FromAddress     = "*****@*****.**",
                FromDisplayName = "Test",
                Templates       = new List <TemplateItem>()
                {
                    new TemplateItem()
                    {
                        Id   = "7cc262f1-48eb-4948-a22c-16cb844d4540",
                        Type = NotificationType.ResetPassword
                    }
                }
            }));
            var sender = new SimpleSendGridEmailSender(new OptionsWrapper <MailOptions>(new MailOptions()
            {
                ApiKey          = "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",
                FromAddress     = "*****@*****.**",
                FromDisplayName = "Integration Test"
            }), factory);

            var message = NotificationRequestModel.Email("*****@*****.**", "subject", "message");

            message.AddToken("-name-", "John Doe");
            message.AddToken("-city-", "Denver");
            message.AddToken("subject", "SendGrid Subject");

            await sender.SendEmailAsync(message, NotificationType.ResetPassword);
        }
コード例 #2
0
        /// <summary>
        /// The CreateMessage
        /// </summary>
        /// <param name="type">The <see cref="NotificationType"/></param>
        /// <param name="model">The <see cref="NotificationRequestModel"/></param>
        /// <returns>The <see cref="SendGridMessage"/></returns>
        public SendGridMessage CreateMessage(NotificationType type, NotificationRequestModel model)
        {
            try
            {
                var mailMessage = new SendGridMessage();
                mailMessage.AddTo(model.DefaultDestination);
                mailMessage.SetFrom(new EmailAddress(Options.FromAddress, Options.FromDisplayName));
                mailMessage.SetSubject(model.DefaultSubject);
                mailMessage.AddContent(MimeType.Html, model.DefaultContent);

                var template = Options.Templates?.FirstOrDefault(c => c.Type == type);

                if (template != null)
                {
                    mailMessage.AddSubstitutions(model.Tokens);
                    if (!string.IsNullOrEmpty(template.Id))
                    {
                        mailMessage.SetTemplateId(template.Id);
                    }
                }

                return(mailMessage);
            }
            catch (Exception ex)
            {
                throw new FormatException($"Failed to construct mail message", ex);
            }
        }
コード例 #3
0
        public void EmailSenderShouldFailWithInvalidApiKey()
        {
            var factory = Substitute.For <ISendGridMalFactory>();
            var sender  = new SimpleSendGridEmailSender(new OptionsWrapper <MailOptions>(new MailOptions()
            {
                ApiKey          = "xxx",
                FromAddress     = "*****@*****.**",
                FromDisplayName = "Integration Test"
            }), factory);

            factory.CreateMessage(Arg.Any <NotificationType>(), Arg.Any <NotificationRequestModel>()).Returns(c =>
            {
                var mailMessage = new SendGridMessage();
                mailMessage.AddTo("*****@*****.**");
                mailMessage.From        = new EmailAddress("*****@*****.**", "Integration Test");
                mailMessage.Subject     = "Test Subject";
                mailMessage.HtmlContent = "Test Body";
                return(mailMessage);
            });

            Func <Task> act = async() =>
            {
                await sender.SendEmailAsync(NotificationRequestModel.Email("*****@*****.**", "test subject", "test body"));
            };

            act.Should().Throw <InvalidOperationException>();
        }
コード例 #4
0
 /// <summary>
 /// The SubmitNotificationRequest
 /// </summary>
 /// <param name="model">The <see cref="NotificationRequestModel"/></param>
 /// <returns>The <see cref="Task{RequestResult}"/></returns>
 public async Task <RequestResult> SubmitEmailNotification(NotificationRequestModel model, NotificationType type = NotificationType.None)
 {
     return(await RequestResult.From(async() =>
     {
         Logger.LogDebug($"Sending email to {model.DefaultDestination}");
         await EmailSender.SendEmailAsync(model, type);
     }));
 }
コード例 #5
0
        /// <summary>
        /// The SendEmailAsync
        /// </summary>
        /// <param name="model">The <see cref="NotificationRequestModel"/></param>
        /// <returns>The <see cref="Task"/></returns>
        public async Task SendEmailAsync(NotificationRequestModel model, NotificationType type = NotificationType.None)
        {
            var message  = MailFactory.CreateMessage(type, model);
            var response = await SendGridClient.SendEmailAsync(message);

            if (response.StatusCode != System.Net.HttpStatusCode.Accepted)
            {
                throw new InvalidOperationException(await response.Body.ReadAsStringAsync());
            }
        }
コード例 #6
0
        public void EmailSenderShouldThrowWhenOptionsNotConfigured()
        {
            Func <Task> act = async() =>
            {
                var sender = new SimpleSendGridEmailSender(new OptionsWrapper <MailOptions>(new MailOptions()), Substitute.For <ISendGridMalFactory>());
                await sender.SendEmailAsync(NotificationRequestModel.Email("*****@*****.**", "test subject", "test body"));
            };

            act.Should().Throw <ArgumentException>();
        }
コード例 #7
0
        public string SendNotification(NotificationRequestModel ObjNotificationRequestModel)
        {
            var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

            request.KeepAlive   = true;
            request.Method      = "POST";
            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Add("authorization", "Basic YWQzNzVhYzItNDM3YS00OTA3LTk0YmEtYjZjNGNhYTY0M2Rj");
            string MessageSend       = ObjNotificationRequestModel.MessageBody;
            string NotificationTitle = ObjNotificationRequestModel.Subject;
            string deviceId          = ObjNotificationRequestModel.DeviceId;
            string deviceType        = ObjNotificationRequestModel.DeviceType;

            var serializer = new JavaScriptSerializer();
            var obj        = new
            {
                app_id             = "0c5b7cb6-a33d-453e-ada0-2c54d17bd7ba",
                contents           = new { en = MessageSend },
                headings           = new { en = NotificationTitle },
                include_player_ids = new string[] { deviceId }
            };

            var param = serializer.Serialize(obj);

            byte[] byteArray = Encoding.UTF8.GetBytes(param);

            string responseContent = null;

            try
            {
                using (var writer = request.GetRequestStream())
                {
                    writer.Write(byteArray, 0, byteArray.Length);
                }

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseContent = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
            }
            System.Diagnostics.Debug.WriteLine(responseContent);
            return(responseContent);
        }
コード例 #8
0
        public async Task <bool> AddNotificationsAsync(NotificationRequestModel notification)
        {
            if (notification == null)
            {
                Log.Debug($"Param: {notification} was null");

                throw new ArgumentNullException(nameof(notification), "Notification param was null");
            }

            notification.UserID = GenerateUserID();

            var notificationEntity = _mapper.Map <Notification>(notification);

            _dbContext.Add(notificationEntity);

            return(await _dbContext.SaveChangesAsync() > 0);
        }
コード例 #9
0
        public async Task <IActionResult> RegisterNewNotification(NotificationRequestModel model)
        {
            Log.Information($"Processing request from {Request.Headers["Origin"]}");

            if (model == null)
            {
                Log.Debug("Model was null");
                return(BadRequest("Request model was null"));
            }

            if (await _notificationsService.AddNotificationsAsync(model) == true)
            {
                return(Created(_linkGenerator.GetPathByAction("RegisterNewNotification", "Notifications"), model));
            }

            Log.Debug("Something bad has happened while trying to add new notification");

            return(BadRequest("Something bad has happened while trying to add new notification"));
        }
コード例 #10
0
        [Fact]//(Skip = "Test to see if mail is inboxed")]
        public async Task EmailSenderShouldSendNotificationWithSendGrid()
        {
            var factory = Substitute.For <ISendGridMalFactory>();
            var sender  = new SimpleSendGridEmailSender(new OptionsWrapper <MailOptions>(new MailOptions()
            {
                ApiKey          = "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",
                FromAddress     = "*****@*****.**",
                FromDisplayName = "Integration Test"
            }), factory);

            factory.CreateMessage(Arg.Any <NotificationType>(), Arg.Any <NotificationRequestModel>()).Returns(c =>
            {
                var mailMessage = new SendGridMessage();
                mailMessage.AddTo("*****@*****.**");
                mailMessage.From        = new EmailAddress("*****@*****.**", "Integration Test");
                mailMessage.Subject     = "Test Without Template";
                mailMessage.HtmlContent = "Test Body";
                return(mailMessage);
            });
            await sender.SendEmailAsync(NotificationRequestModel.Email("*****@*****.**", "test subject", "test body"));
        }
コード例 #11
0
        public NotificationResponseModel SendNotification(NotificationRequestModel notificationRequestModel)
        {
            if (notificationRequestModel.SmsTo == null || notificationRequestModel.SmsTo.Count() == 0)
            {
                throw new ArgumentNullException(nameof(notificationRequestModel.SmsTo));
            }

            TwilioClient.Init(ConfigurationManager.AppSettings["accountSid"], ConfigurationManager.AppSettings["authToken"]);

            foreach (var Sms_to in notificationRequestModel.SmsTo)
            {
                var to      = new PhoneNumber(Sms_to);
                var message = MessageResource.Create(
                    to,
                    from: new PhoneNumber(ConfigurationManager.AppSettings["senderNumber"]),            //"+12563054795"
                    body: Encoding.UTF8.GetString(notificationRequestModel.Message));

                notificationResponseModel.ResponseMessage = message.Status.ToString();
            }

            //notificationResponseModel.ResponseMessage = "Message Successfully sent.";

            return(notificationResponseModel);
        }
コード例 #12
0
        /// <summary>
        /// The ResetPassword
        /// </summary>
        /// <param name="model">The <see cref="ResetPasswordViewModel"/></param>
        /// <returns>The <see cref="Task{RequestResult}"/></returns>
        public async Task <RequestResult> ResetPassword(string email)
        {
            return(await RequestResult.From(async() =>
            {
                if (string.IsNullOrEmpty(email))
                {
                    return RequestResult.Failed($"Email cannot be empty");
                }

                var user = await UserManager.FindByEmailAsync(email);
                if (user != null)
                {
                    var token = await UserManager.GeneratePasswordResetTokenAsync(user);

                    var result = await Session.Notification.SubmitEmailNotification(NotificationRequestModel.Email(email,
                                                                                                                   "Your password has been reset",
                                                                                                                   $"Reset token - [{token}]").AddToken("~token~", token), NotificationType.ResetPassword);

                    return result;
                }

                return RequestResult.Failed($"Failed to find login for account {email}");
            }));
        }
コード例 #13
0
        public void SendGridFactoryShouldSetTokensAndTemplateId()
        {
            var factory = new SendGridMailFactory(new OptionsWrapper <MailOptions>(new MailOptions()
            {
                FromAddress     = "*****@*****.**",
                FromDisplayName = "Test",
                Templates       = new List <TemplateItem>()
                {
                    new TemplateItem()
                    {
                        Id   = "123",
                        Type = NotificationType.ResetPassword
                    }
                }
            }));
            var message = NotificationRequestModel.Email("*****@*****.**", "subject", "message");

            message.AddToken("token", "test");

            var result = factory.CreateMessage(NotificationType.ResetPassword, message);

            result.Personalizations[0].Substitutions.Count.Should().BeGreaterThan(0);
            result.TemplateId.Should().NotBeNullOrEmpty();
        }
コード例 #14
0
 /// <summary>
 /// The SendEmailAsync
 /// </summary>
 /// <param name="model">The <see cref="NotificationRequestModel"/></param>
 /// <param name="type">The <see cref="NotificationType"/></param>
 /// <returns>The <see cref="Task"/></returns>
 public Task SendEmailAsync(NotificationRequestModel model, NotificationType type = NotificationType.None)
 {
     return(Task.CompletedTask);
 }
コード例 #15
0
        public NotificationResponse SendNotification_fcm(NotificationRequestModel ObjNotificationRequestModel)
        {
            NotificationResponse objNotificationResponse = new NotificationResponse();
            var    serverKey           = "AAAAvFQYgYA:APA91bGSoLVXzYCUNptgngQ-UctKIkgvOJ462Vvls7draV1P6OvQ1kHavjZZMAWhUYh_gXfDnH9duNT1QSwqH5KVy1PrL8rQN64xnByPZEonPbhW19pJRbDc-QrQB5wr_RWCjfVmNRFV";
            var    senderId            = "808864743808";
            string deviceId            = ObjNotificationRequestModel.DeviceId;
            string DeviceType          = ObjNotificationRequestModel.DeviceType;
            string MessageSend         = ObjNotificationRequestModel.MessageBody;;
            string Subject             = ObjNotificationRequestModel.Subject;
            string sResponseFromServer = "";

            var objNotification = new
            {
                to                = deviceId,
                priority          = "high",
                content_available = true,
                data              = new
                {
                    title  = Subject,
                    body   = MessageSend,
                    sound  = "Enabled",
                    icon   = "/firebase-logo.png",
                    status = true
                }
            };

            try
            {
                //for Ios
                Guid NotificationId = Guid.NewGuid();
                if (DeviceType.ToUpper() == "IOS")
                {
                    WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");

                    tRequest.Method      = "post";
                    tRequest.ContentType = "application/json";

                    var    serializer = new JavaScriptSerializer();
                    var    json       = serializer.Serialize(objNotification);
                    Byte[] byteArray  = Encoding.UTF8.GetBytes(json);
                    tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
                    tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
                    tRequest.ContentLength = byteArray.Length;
                    using (Stream dataStream = tRequest.GetRequestStream())
                    {
                        dataStream.Write(byteArray, 0, byteArray.Length);
                        using (WebResponse tResponse = tRequest.GetResponse())
                        {
                            using (Stream dataStreamResponse = tResponse.GetResponseStream())
                            {
                                using (StreamReader tReader = new StreamReader(dataStreamResponse))
                                {
                                    sResponseFromServer = tReader.ReadToEnd();
                                    FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(sResponseFromServer);
                                    if (response.success == 1)
                                    {
                                        objNotificationResponse.Responses.Message    = "succeeded";
                                        objNotificationResponse.Responses.StatusCode = 200;
                                    }
                                    else if (response.failure == 1)
                                    {
                                        objNotificationResponse.Responses.Message    = "failed";
                                        objNotificationResponse.Responses.StatusCode = 400;
                                    }
                                }
                            }
                        }
                    }
                }
                //for Android
                else
                {
                    WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");

                    tRequest.Method      = "post";
                    tRequest.ContentType = "application/json";

                    var    serializer = new JavaScriptSerializer();
                    var    json       = serializer.Serialize(objNotification);
                    Byte[] byteArray  = Encoding.UTF8.GetBytes(json);
                    tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
                    tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
                    tRequest.ContentLength = byteArray.Length;
                    using (Stream dataStream = tRequest.GetRequestStream())
                    {
                        dataStream.Write(byteArray, 0, byteArray.Length);
                        using (WebResponse tResponse = tRequest.GetResponse())
                        {
                            using (Stream dataStreamResponse = tResponse.GetResponseStream())
                            {
                                using (StreamReader tReader = new StreamReader(dataStreamResponse))
                                {
                                    sResponseFromServer = tReader.ReadToEnd();

                                    FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(sResponseFromServer);
                                    if (response.success == 1)
                                    {
                                        objNotificationResponse.Responses.Message    = "succeeded";
                                        objNotificationResponse.Responses.StatusCode = 200;
                                    }
                                    else if (response.failure == 1)
                                    {
                                        objNotificationResponse.Responses.Message    = "failed";
                                        objNotificationResponse.Responses.StatusCode = 400;
                                    }
                                }
                            }
                        }
                    }
                }
                // For ios
            }
            catch (Exception ex)
            {
                objNotificationResponse.Responses.Message    = Convert.ToString(ex);
                objNotificationResponse.Responses.StatusCode = 501;
            }
            return(objNotificationResponse);
        }
コード例 #16
0
 /// <summary>
 /// The CreateEmailFromNotification
 /// </summary>
 /// <param name="model">The <see cref="NotificationRequestModel"/></param>
 /// <returns>The <see cref="(string email, string subject, string message)"/></returns>
 public static (string email, string subject, string message) CreateEmailFromNotification(NotificationRequestModel model)
 {
     return(model.DefaultDestination, model.DefaultSubject, model.DefaultContent);
 }