public void Notify_Creates_Log_On_Failure()
        {
            // Arrange
            var logService = new Mock<ILogService>();
            var emailService = new Mock<IEmailService>();
            emailService.Setup(e => e.Send(It.IsAny<MailMessage>())).Throws(new SmtpException());
            var user = new Mock<User>();
            user.SetupProperty(u => u.Email, "*****@*****.**");
            var template = new Mock<INotificationTemplate>();
            template.Setup(t => t.Read()).Returns(new XElement("Email",
                new XElement("Subject"), new XElement("Body")));
            template.Setup(t => t.ContainingDirectory).Returns("");
            var templateObj = template.Object;

            var templateService = new Mock<ITemplateService>();
            templateService.Setup(t => t.ParseTemplate(It.IsAny<string>(),
                templateObj,
                It.IsAny<object>()))
                .Returns(new Dictionary<string, string>()
                    {
                        {"Subject", ""},
                        {"Body", ""}
                    });

            // Parent email template
            templateService.Setup(t => t.ParseTemplate(It.IsAny<string>(),
                It.Is<INotificationTemplate>(n => n != templateObj),
                It.IsAny<object>()))
                .Returns(new Dictionary<string, string>()
                    {
                        {"Message", ""}
                    });

            var service = new EmailNotificationService(logService.Object, emailService.Object,
                templateService.Object,
                "*****@*****.**", "Support");

            // Act
            service.Notify(user.Object, templateObj, null);

            // Assert
            logService.Verify(l => l.CreateLog(It.IsAny<Domain.Log>()), Times.Once());
        }
        static void Main(string[] args)
        {
            Console.WriteLine(@"
This a very simple demo of how the NonHttpRunTimeRazorSupport library 
might be used to send emails outside of the context of a running
web application.

This app is configured to drop .eml files in the C:\temp folder (see 
app.config). These files can be viewed in an email client, or on a
web site like http://www.encryptomatic.com/viewer/Default.aspx");
            var settings = new NotificationSettings(new Uri("http://www.facepack.com/"));
            var service = new EmailNotificationService(settings);
            do
            {
                var from = new MailAddress("*****@*****.**");
                var to = new MailAddress("*****@*****.**");
                var model = new WelcomeModel
                {
                    Name = "Dave"
                };
                service.Send(from, to, model);
                Console.WriteLine("Message sent. Press a key to resend, or q to exit");
            } while (Console.ReadKey().KeyChar != 'q');
        }
Example #3
0
        public void LoginInvalidCredentials()
        {
            ApplicationConfiguration appApplicationConfiguration = new ApplicationConfiguration();
            PersonRepository         personRepository            = new PersonRepository(_session);
            AuthenticationService    authenticationService       = new AuthenticationService(personRepository);
            ScheduledEmailRepository scheduledEmailRepository    = new ScheduledEmailRepository(_session);
            EmailNotificationService emailNotificationService    = new EmailNotificationService(appApplicationConfiguration);
            ScheduledEmailService    scheduledEmailService       = new ScheduledEmailService(scheduledEmailRepository, emailNotificationService, personRepository);

            DeviceRepository  deviceRepository     = new DeviceRepository(_session);
            SessionRepository apiSessionRepository = new SessionRepository(_session);
            PersonService     personService        = new PersonService(personRepository, deviceRepository, apiSessionRepository, emailNotificationService, scheduledEmailService, appApplicationConfiguration, scheduledEmailRepository);
            SessionService    apiSessionService    = new SessionService(apiSessionRepository);
            DeviceService     deviceService        = new DeviceService(deviceRepository, personRepository);


            AuthController authController = new AuthController(apiSessionService, personService, authenticationService, deviceService)
            {
                Configuration = new HttpConfiguration(),
                Request       = new HttpRequestMessage()
            };

            authController.Request.Headers.Add("XClientId", "00000000000000000000000000000000");

            AuthModelLight authModelLight = new AuthModelLight
            {
                EmailAddress = "empty",
                Password     = "******"
            };

            string jsonString = JsonConvert.SerializeObject(authModelLight);

            AuthModelLight result = authController.VerifyByPost(authModelLight);

            Assert.AreEqual(result.Desc, ApplicationConfiguration.LoginInvalidCredentials);
        }
        public async Task WhenMessageIsValidThenClientIsCalled()
        {
            var source = new Mock <IEmailSender>();

            SendEmailDto saveDto = null;

            source.Setup(c => c.SendAsync(It.IsAny <SendEmailDto>()))
            .Callback <SendEmailDto>((dto) => saveDto = dto)
            .Returns(Task.CompletedTask);

            var emailService = new EmailNotificationService(source.Object);
            var message      = new TestEmailNotification(
                "*****@*****.**",
                "Softeq Unit Test",
                new TestEmailModel("google.com", "Softeq Unit Test"));

            await emailService.SendAsync(message);

            source.Verify(sender => sender.SendAsync(It.IsAny <SendEmailDto>()), Times.Once);
            Assert.NotNull(saveDto);
            Assert.Equal(message.Text, saveDto.Text);
            Assert.Equal(message.Recipients, saveDto.Recipients);
            Assert.Equal(message.Subject, saveDto.Subject);
        }
        public void Init()
        {
            _emailNotificationBuilderMock = new Mock <IEmailNotificationBuilder>();

            IEnumerable <EmailNotificationMessage <CostNotificationObject> > approvedMessages = new List <EmailNotificationMessage <CostNotificationObject> >
            {
                new EmailNotificationMessage <CostNotificationObject>(core.Constants.EmailNotificationActionType.BrandApprovalApproved, "57e5461ed9563f268ef4f19a")
            };

            _emailNotificationBuilderMock.Setup(e => e.BuildCostApprovedNotification(
                                                    It.IsAny <CostNotificationUsers>(),
                                                    It.IsAny <Cost>(), It.IsAny <CostStageRevision>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>()))
            .Returns(Task.FromResult(approvedMessages));

            IEnumerable <EmailNotificationMessage <CostNotificationObject> > pendingBrandMessages = new List <EmailNotificationMessage <CostNotificationObject> >
            {
                new EmailNotificationMessage <CostNotificationObject>(core.Constants.EmailNotificationActionType.BrandApproverAssigned, "57e5461ed9563f268ef4f19a")
            };

            _emailNotificationBuilderMock.Setup(e => e.BuildPendingBrandApprovalNotification(
                                                    It.IsAny <CostNotificationUsers>(),
                                                    It.IsAny <Cost>(), It.IsAny <CostStageRevision>(), It.IsAny <DateTime>()))
            .Returns(Task.FromResult(pendingBrandMessages));

            IEnumerable <EmailNotificationMessage <CostNotificationObject> > pendingTechnicalMessages = new List <EmailNotificationMessage <CostNotificationObject> >
            {
                new EmailNotificationMessage <CostNotificationObject>(core.Constants.EmailNotificationActionType.TechnicalApproverAssigned, "57e5461ed9563f268ef4f19a")
            };

            _emailNotificationBuilderMock.Setup(e => e.BuildPendingTechnicalApprovalNotification(
                                                    It.IsAny <CostNotificationUsers>(),
                                                    It.IsAny <Cost>(), It.IsAny <CostStageRevision>(), It.IsAny <DateTime>()))
            .Returns(Task.FromResult(pendingTechnicalMessages));

            IEnumerable <EmailNotificationMessage <CostNotificationObject> > recalledMessages = new List <EmailNotificationMessage <CostNotificationObject> >
            {
                new EmailNotificationMessage <CostNotificationObject>(core.Constants.EmailNotificationActionType.Recalled, "57e5461ed9563f268ef4f19r")
            };

            _emailNotificationBuilderMock.Setup(e => e.BuildCostRecalledNotification(
                                                    It.IsAny <CostNotificationUsers>(),
                                                    It.IsAny <Cost>(), It.IsAny <CostStageRevision>(), It.IsAny <CostUser>(), It.IsAny <DateTime>()))
            .ReturnsAsync(recalledMessages);

            IEnumerable <EmailNotificationMessage <CostNotificationObject> > rejectedMessages = new List <EmailNotificationMessage <CostNotificationObject> >
            {
                new EmailNotificationMessage <CostNotificationObject>(core.Constants.EmailNotificationActionType.Rejected, "57e5461ed9563f268ef4f19r")
            };

            _emailNotificationBuilderMock.Setup(e => e.BuildCostRejectedNotification(
                                                    It.IsAny <CostNotificationUsers>(),
                                                    It.IsAny <Cost>(), It.IsAny <CostStageRevision>(), It.IsAny <CostUser>(),
                                                    It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>()))
            .Returns(Task.FromResult(rejectedMessages));

            IEnumerable <EmailNotificationMessage <CostNotificationObject> > cancelledMessages = new List <EmailNotificationMessage <CostNotificationObject> >
            {
                new EmailNotificationMessage <CostNotificationObject>(core.Constants.EmailNotificationActionType.Cancelled, "57e5461ed9563f268ef4f19r")
            };

            _emailNotificationBuilderMock.Setup(e => e.BuildCostCancelledNotification(
                                                    It.IsAny <CostNotificationUsers>(),
                                                    It.IsAny <Cost>(), It.IsAny <CostStageRevision>(), It.IsAny <DateTime>()))
            .Returns(Task.FromResult(cancelledMessages));

            IEnumerable <EmailNotificationMessage <CostNotificationObject> > costOwnerChangedMessages = new List <EmailNotificationMessage <CostNotificationObject> >
            {
                new EmailNotificationMessage <CostNotificationObject>(core.Constants.EmailNotificationActionType.CostOwnerChanged, "57e5461ed9563f268ef4f19r")
            };

            _emailNotificationBuilderMock.Setup(e => e.BuildCostOwnerChangedNotification(
                                                    It.IsAny <CostNotificationUsers>(),
                                                    It.IsAny <Cost>(),
                                                    It.IsAny <CostStageRevision>(),
                                                    It.IsAny <DateTime>(),
                                                    It.IsAny <CostUser>(),
                                                    It.IsAny <CostUser>()))
            .Returns(Task.FromResult(costOwnerChangedMessages));

            _paperPusherClientMock = new Mock <IPaperpusherClient>();
            _paperPusherClientMock.Setup(p => p.SendMessage(It.IsAny <EmailNotificationMessage <CostNotificationObject> >()))
            .Returns(Task.FromResult(true));

            _reminderServiceMock = new Mock <IEmailNotificationReminderService>();
            _efContextMock       = new Mock <EFContext>();
            _costUserServiceMock = new Mock <ICostUserService>();
            _approvalServiceMock = new Mock <IApprovalService>();
            SetupDataSharedAcrossTests();

            _emailNotificationService = new EmailNotificationService(_emailNotificationBuilderMock.Object, _paperPusherClientMock.Object,
                                                                     _reminderServiceMock.Object, _efContextMock.Object, _costUserServiceMock.Object, _approvalServiceMock.Object);
        }
Example #6
0
 public ReviewsController(IReviewDao reviewDao, EmailNotificationService emailService, SmsNotificationService smsService)
 {
     _dao = reviewDao;
     _emailNotificationService = emailService;
     _smsNotificationService   = smsService;
 }
Example #7
0
 public AmazonOrdersService()
 {
     _logger          = new LoggerRepository();
     _orderRepository = new OrderRepository();
     _emailService    = new EmailNotificationService();
 }
Example #8
0
 public SRP_Good()
 {
     _emailService = new EmailNotificationService();
 }
Example #9
0
        public async Task <IActionResult> Invoke([FromBody] JToken body)
        {
            var invokeHeaders = ProcessInvokeHeaders();

            if (string.IsNullOrWhiteSpace(invokeHeaders.Path))
            {
                return(BadRequest($"Missing {PathQueryHeader} header"));
            }

            string detectorId = null;

            if (body?.GetType() != typeof(JArray))
            {
                detectorId = body?["id"] != null ? body["id"].ToString() : string.Empty;
            }

            string applensLink = "https://applens.azurewebsites.net/" + invokeHeaders.Path.Replace("resourcegroup", "resourceGroup").Replace("diagnostics/publish", string.Empty) + "detectors/" + detectorId;

            var detectorAuthorEmails = new List <EmailAddress>();

            if (invokeHeaders.DetectorAuthors.Any())
            {
                detectorAuthorEmails = invokeHeaders.DetectorAuthors
                                       .Select(x => x.EndsWith("@microsoft.com") ? x : $"{x}@microsoft.com")
                                       .Distinct(StringComparer.OrdinalIgnoreCase)
                                       .Select(x => new EmailAddress(x)).ToList();
            }

            HttpRequestHeaders headers = new HttpRequestMessage().Headers;

            foreach (var header in Request.Headers)
            {
                if (header.Key.Equals("x-ms-location", StringComparison.CurrentCultureIgnoreCase) && blackListedAscRegions.Any(region => header.Value.FirstOrDefault()?.Contains(region) == true))
                {
                    headers.Add("x-ms-subscription-location-placementid", diagAscHeaderValue);
                }
                else if ((header.Key.StartsWith("x-ms-") || header.Key.StartsWith("diag-")) && !headers.Contains(header.Key))
                {
                    headers.Add(header.Key, header.Value.ToString());
                }
            }

            var response = await DiagnosticClient.Execute(invokeHeaders.Method, invokeHeaders.Path, body?.ToString(), invokeHeaders.InternalClient, invokeHeaders.InternalView, headers);

            if (response == null)
            {
                return(StatusCode(500, "Null response from DiagnosticClient"));
            }

            var responseTask = response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                return(StatusCode((int)response.StatusCode, await responseTask));
            }

            if (response.Headers.Contains(ScriptEtagHeader))
            {
                Request.HttpContext.Response.Headers.Add(ScriptEtagHeader, response.Headers.GetValues(ScriptEtagHeader).First());
            }

            if (invokeHeaders.Path.EndsWith("/diagnostics/publish", StringComparison.OrdinalIgnoreCase) && detectorAuthorEmails.Count > 0 && Env.IsProduction())
            {
                EmailNotificationService.SendPublishingAlert(invokeHeaders.ModifiedBy, detectorId, applensLink, detectorAuthorEmails);
            }

            return(Ok(JsonConvert.DeserializeObject(await responseTask)));
        }
        public async Task <IActionResult> Invoke([FromBody] JToken body)
        {
            if (!Request.Headers.ContainsKey("x-ms-path-query"))
            {
                return(BadRequest("Missing x-ms-path-query header"));
            }

            string path = Request.Headers["x-ms-path-query"];

            string method = HttpMethod.Get.Method;

            if (Request.Headers.ContainsKey("x-ms-method"))
            {
                method = Request.Headers["x-ms-method"];
            }

            bool internalClient = true;

            if (Request.Headers.ContainsKey("x-ms-internal-client"))
            {
                bool.TryParse(Request.Headers["x-ms-internal-client"], out internalClient);
            }

            bool internalView = true;

            if (Request.Headers.ContainsKey("x-ms-internal-view"))
            {
                bool.TryParse(Request.Headers["x-ms-internal-view"], out internalView);
            }

            string alias          = string.Empty;
            string detectorId     = string.Empty;
            string detectorAuthor = string.Empty;

            List <EmailAddress> tos = new List <EmailAddress>();
            List <string>       distinctEmailRecipientsList = new List <string>();

            if (body != null && body["id"] != null)
            {
                detectorId = body["id"].ToString();
            }

            string applensLink = "https://applens.azurewebsites.net/" + path.Replace("resourcegroup", "resourceGroup").Replace("diagnostics/publish", "") + "detectors/" + detectorId;

            if (!string.IsNullOrWhiteSpace(Request.Headers["x-ms-emailRecipients"]))
            {
                detectorAuthor = Request.Headers["x-ms-emailRecipients"];
                char[] separators = { ' ', ',', ';', ':' };

                // Currently there's a bug in sendgrid v3, email will not be sent if there are duplicates in the recipient list
                // Remove duplicates before adding to the recipient list
                string[] authors = detectorAuthor.Split(separators, StringSplitOptions.RemoveEmptyEntries).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
                foreach (var author in authors)
                {
                    if (string.IsNullOrWhiteSpace(alias))
                    {
                        alias = author;
                    }

                    string baseEmailAddressString = author.EndsWith("@microsoft.com", StringComparison.OrdinalIgnoreCase) ? author : author + "@microsoft.com";

                    if (!distinctEmailRecipientsList.Contains(baseEmailAddressString))
                    {
                        EmailAddress emailAddress = new EmailAddress(baseEmailAddressString);
                        tos.Add(emailAddress);
                        distinctEmailRecipientsList.Add(baseEmailAddressString);
                    }
                }
            }

            var scriptETag = string.Empty;

            if (Request.Headers.ContainsKey("diag-script-etag"))
            {
                scriptETag = Request.Headers["diag-script-etag"];
            }

            var assemblyName = string.Empty;

            if (Request.Headers.ContainsKey("diag-assembly-name"))
            {
                assemblyName = Request.Headers["diag-assembly-name"];
            }

            HttpRequestHeaders headers = new HttpRequestMessage().Headers;

            if (!string.IsNullOrWhiteSpace(scriptETag))
            {
                headers.Add("diag-script-etag", scriptETag);
            }

            if (!string.IsNullOrWhiteSpace(assemblyName))
            {
                headers.Add("diag-assembly-name", assemblyName);
            }

            var response = await DiagnosticClient.Execute(method, path, body?.ToString(), internalClient, internalView, headers);

            if (response != null)
            {
                var responseString = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                {
                    var responseObject = JsonConvert.DeserializeObject(responseString);
                    if (response.Headers.Contains("diag-script-etag"))
                    {
                        Request.HttpContext.Response.Headers.Add("diag-script-etag", response.Headers.GetValues("diag-script-etag").First());
                    }

                    if (path.EndsWith("/diagnostics/publish", StringComparison.OrdinalIgnoreCase) && tos.Count > 0 && Env.IsProduction())
                    {
                        EmailNotificationService.SendPublishingAlert(alias, detectorId, applensLink, tos);
                    }

                    return(Ok(responseObject));
                }
                else if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    return(BadRequest(responseString));
                }
            }

            return(StatusCode((int)response.StatusCode));
        }
Example #11
0
        private bool SendOTPAndEmail(int UserId)
        {
            bool IsSuccess = false;

            #region Prepare OTP Data

            string UniqueString = AppUtil.GetUniqueGuidString();
            string OTPString    = AppUtil.GetUniqueRandomNumber(100000, 999999); // Generate a Six Digit OTP
            OTPBO  objOTP       = new OTPBO()
            {
                GUID = UniqueString, OTP = OTPString, CreatedDate = DateTime.Now, UserID = UserId, Attempts = 0
            };

            #endregion
            try
            {
                if (SecurityBusinessInstance.SaveOTP(objOTP))
                {
                    #region Send Email Servie and OTP
                    //string hostName = AppUtil.GetAppSettings(AspectEnums.ConfigKeys.HostName);
                    string resetUrl         = AppUtil.GetAppSettings(AspectEnums.ConfigKeys.ForgotPasswordURL);
                    string PasswordResetURL = resetUrl + UniqueString;
                    //string PasswordResetURL = Request.Url.AbsoluteUri.Split('/')[0] + Request.Url.AbsoluteUri.Split('/')[1]  + resetUrl + "?id=" + UniqueString;
                    EmailNotificationService eNotification = new EmailNotificationService();
                    var userProfile = UserBusinessInstance.DisplayUserProfile(UserId); // empBusinessInstance.DisplayEmpProfile(EmpId);
                    TemplateMasterBO            objEmailTemplate = EmailBusinessInstance.GetEmailTemplate((int)AspectEnums.EmailTemplateCode.ResetPassword);
                    List <TemplateMergeFieldBO> mergeFields      = EmailBusinessInstance.GetEmailMergeFields(objEmailTemplate.TemplateID);
                    foreach (var field in mergeFields)
                    {
                        if (field.SRC_FIELD == "{{PASSWORDRESETURL}}")
                        {
                            objEmailTemplate.TemplateContent = eNotification.FindReplace(objEmailTemplate.TemplateContent, "{{PASSWORDRESETURL}}", PasswordResetURL);
                        }

                        else if (field.SRC_FIELD == "{{TONAME}}")
                        {
                            objEmailTemplate.TemplateContent = eNotification.FindReplace(objEmailTemplate.TemplateContent, field.SRC_FIELD, userProfile.FirstName + " " + userProfile.LastName);
                        }
                    }
                    objEmailTemplate.TemplateContent = eNotification.FindReplace(objEmailTemplate.TemplateContent, "{{COMPANY}}", AppUtil.GetAppSettings(AspectEnums.ConfigKeys.CompanyName));


                    EmailServiceDTO emailService = new EmailServiceDTO();
                    emailService.Priority     = 1;
                    emailService.CreatedBy    = userProfile.UserID;
                    emailService.IsHtml       = true;
                    emailService.ToName       = userProfile.FirstName + " " + userProfile.LastName;
                    emailService.Body         = objEmailTemplate.TemplateContent;
                    emailService.Status       = (int)AspectEnums.EmailStatus.Pending;
                    emailService.ToEmail      = userProfile.Email;
                    emailService.FromName     = AppUtil.GetAppSettings(AspectEnums.ConfigKeys.FromName);
                    emailService.FromEmail    = AppUtil.GetAppSettings(AspectEnums.ConfigKeys.FromEmail);
                    emailService.Subject      = eNotification.FindReplace(objEmailTemplate.TemplateSubject, "{{COMPANY}}", AppUtil.GetAppSettings(AspectEnums.ConfigKeys.CompanyName));
                    emailService.IsAttachment = false;
                    emailService.TemplateID   = objEmailTemplate.TemplateID;
                    emailBusinessInstance.InsertEmailRecord(emailService);

                    eNotification.SendEmailNotification(emailService, objEmailTemplate);
                    IsSuccess = true;

                    #endregion
                }
            }
            catch (Exception ex)
            {
                IsSuccess = false;
            }


            return(IsSuccess);
        }
Example #12
0
        public ActionResult Purchase(UserPurchaseViewModel model)
        {
            try
            {
                ViewBag.ShowMessage = true;
                ViewBag.IsTrial     = false;


                if (model.subscriptions.SubscriptionType == (int)AspectEnums.SubscriptionType.Trial)
                {
                    ViewBag.IsTrial        = true;
                    model.template.IsTrial = true;
                }

                #region Create NEW USER - SUBMIT USERMASTER

                bool isUserExist = UserBusinessInstance.GetUserByLoginName(model.user.Email).UserID > 0 ? true : false;

                if (isUserExist)
                {
                    ViewBag.Message   = "This email address already exist.";
                    ViewBag.IsSuccess = false;
                    return(View(model));
                }

                model.user.CreatedBy     = 1;
                model.user.CreatedDate   = DateTime.Now;
                model.user.AccountStatus = (int)AspectEnums.UserAccountStatus.Pending;
                model.user.isActive      = true;
                model.user.isDeleted     = false;
                model.user.IsEmployee    = false;
                model.user.LoginName     = model.user.Email;
                model.user.Password      = "******";
                string sessionID = HttpContext.Session.SessionID.ToString();
                int    newUserID = UserBusinessInstance.SubmitNewEmployee(model.user, sessionID);
                #endregion

                #region CREATE NEW ORDER - SUBMIT ORDERMASTER
                model.order.UserID = newUserID;
                decimal cost     = 0;
                int     Discount = Convert.ToInt32(ConfigurationManager.AppSettings["Discount"]);
                if (model.subscriptions.SubscriptionType == (int)AspectEnums.SubscriptionType.Trial)
                {
                    cost = 0;
                    model.subscriptions.EndDate = DateTime.Now.AddDays(10);
                }
                if (model.subscriptions.SubscriptionTypeList == AspectEnums.SubscriptionType.Annual)
                {
                    cost = Convert.ToDecimal(model.template.COST);
                    model.subscriptions.EndDate = DateTime.Now.AddMonths(12);
                }
                else if (model.subscriptions.SubscriptionTypeList == AspectEnums.SubscriptionType.HalfYearly)
                {
                    cost = Convert.ToDecimal(model.template.COST * .60);
                    model.subscriptions.EndDate = DateTime.Now.AddMonths(06);
                }
                else if (model.subscriptions.SubscriptionTypeList == AspectEnums.SubscriptionType.Quarterly)
                {
                    cost = Convert.ToDecimal(model.template.COST * 0.30);
                    model.subscriptions.EndDate = DateTime.Now.AddMonths(3);
                }

                model.order.Discount = Discount;
                model.order.Amount   = cost - (cost * (Discount / 100));
                model.template.COST  = Convert.ToInt32(model.order.Amount);
                int OrderID = SystemBusinessInstance.SubmitNewOrder(model.order);
                #endregion

                #region CREATE NEW SUBSCRIPTION - SUBMIT USERWEDDINGSUBSCRIPTION
                model.subscriptions.UserId    = newUserID;
                model.subscriptions.InvoiceNo = OrderID;


                int SubscriptionID = SystemBusinessInstance.SubmitUserSubscription(model.subscriptions);
                #endregion

                if (newUserID > 1)
                {
                    EmailServiceDTO  email         = new EmailServiceDTO();
                    TemplateMasterBO emailTemplate = new TemplateMasterBO();
                    int emailTemplateCode          = (int)AspectEnums.EmailTemplateCode.WelcomeEmail;

                    if (DreamWeddsData.DreamWeddsWeb == null)
                    {
                        emailTemplate = SystemBusinessInstance.GetTemplateData(0, emailTemplateCode);
                    }
                    else
                    {
                        emailTemplate = DreamWeddsData.DreamWeddsWeb.templateMasters.Where(x => x.TemplateCode == emailTemplateCode).FirstOrDefault();
                    }

                    model.template.UrlIdentifier = EncryptionEngine.Encrypt(newUserID.ToString() + "," + model.user.FirstName + "," + model.user.LastName + "," + model.user.LoginName + "," + model.template.TemplateName);
                    //string encodedValue = HttpUtility.UrlEncode(model.template.UrlIdentifier);
                    string decrypt = EncryptionEngine.Decrypt(model.template.UrlIdentifier);
                    email.ToName         = model.user.FirstName + " " + model.user.LastName;
                    email.Subject        = emailTemplate.TemplateSubject;
                    email.ToEmail        = model.user.Email;
                    email.Status         = (int)AspectEnums.EmailStatus.Pending;
                    email.Message        = emailTemplate.TemplateName;
                    email.Phone          = model.user.Phone;
                    email.Mobile         = model.user.Mobile;
                    email.IsCustomerCopy = false;
                    email.TemplateID     = emailTemplate.TemplateID;
                    email.Body           = emailTemplate.TemplateContent;
                    email.CreatedDate    = DateTime.Now;
                    email.CreatedBy      = newUserID;
                    email.IsHtml         = true;
                    email.Priority       = 2;
                    email.IsAttachment   = false;
                    email.Body           = PrepareEmailContent(email, emailTemplate);
                    EmailNotificationService eNotification = new EmailNotificationService();
                    eNotification.SendEmailNotification(email, model.template);
                    ViewBag.IsSuccess = true;
                }
            }
            catch (DbEntityValidationException ex)
            {
                ViewBag.IsSuccess = false;
                var newException = new FormattedDbEntityValidationException(ex);
                ViewBag.Message = "Error: " + ex;
            }
            catch (Exception e)
            {
                ViewBag.IsSuccess = false;
                ViewBag.Message   = "Error: " + e;
            }
            return(View(model));
        }
Example #13
0
        public async Task <IActionResult> Invoke([FromBody] JToken body)
        {
            var invokeHeaders = ProcessInvokeHeaders();

            if (string.IsNullOrWhiteSpace(invokeHeaders.Path))
            {
                return(BadRequest($"Missing {PathQueryHeader} header"));
            }

            string detectorId = null;

            if (body?.GetType() != typeof(JArray))
            {
                detectorId = body?["id"] != null ? body["id"].ToString() : string.Empty;
            }

            string applensLink = "https://applens.azurewebsites.net/" + invokeHeaders.Path.Replace("resourcegroup", "resourceGroup").Replace("diagnostics/publish", string.Empty) + "detectors/" + detectorId;

            var detectorAuthorEmails = new List <EmailAddress>();

            if (invokeHeaders.DetectorAuthors.Any())
            {
                detectorAuthorEmails = invokeHeaders.DetectorAuthors
                                       .Select(x => x.EndsWith("@microsoft.com") ? x : $"{x}@microsoft.com")
                                       .Distinct(StringComparer.OrdinalIgnoreCase)
                                       .Select(x => new EmailAddress(x)).ToList();
            }

            HttpRequestHeaders headers = new HttpRequestMessage().Headers;

            var locationPlacementId = await GetLocationPlacementId(invokeHeaders);

            if (!string.IsNullOrWhiteSpace(locationPlacementId))
            {
                headers.Add("x-ms-subscription-location-placementid", locationPlacementId);
            }

            foreach (var header in Request.Headers)
            {
                if ((header.Key.StartsWith("x-ms-") || header.Key.StartsWith("diag-")) && !headers.Contains(header.Key))
                {
                    headers.Add(header.Key, header.Value.ToString());
                }
            }

            // For Publishing Detector Calls, validate if user has access to publish the detector
            if (invokeHeaders.Path.EndsWith("/diagnostics/publish", StringComparison.OrdinalIgnoreCase))
            {
                if (!TryFetchPublishAcessParametersFromRequestBody(body, out string resourceType, out string detectorCode, out bool isOriginalCodeMarkedPublic, out string errMsg))
                {
                    return(BadRequest(errMsg));
                }

                string userAlias      = Utilities.GetUserIdFromToken(Request.Headers["Authorization"].ToString());
                var    resourceConfig = await this.resourceConfigService.GetResourceConfig(resourceType);

                bool hasAccess = await Utilities.IsUserAllowedToPublishDetector(userAlias, resourceConfig, detectorCode, isOriginalCodeMarkedPublic);

                if (!hasAccess)
                {
                    return(Unauthorized());
                }
            }

            var response = await DiagnosticClient.Execute(invokeHeaders.Method, invokeHeaders.Path, body?.ToString(), invokeHeaders.InternalClient, invokeHeaders.InternalView, headers);

            if (response == null)
            {
                return(StatusCode(500, "Null response from DiagnosticClient"));
            }

            var responseTask = response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                return(StatusCode((int)response.StatusCode, await responseTask));
            }

            if (response.Headers.Contains(ScriptEtagHeader))
            {
                Request.HttpContext.Response.Headers.Add(ScriptEtagHeader, response.Headers.GetValues(ScriptEtagHeader).First());
            }

            if (invokeHeaders.Path.EndsWith("/diagnostics/publish", StringComparison.OrdinalIgnoreCase) && detectorAuthorEmails.Count > 0 && Env.IsProduction())
            {
                EmailNotificationService.SendPublishingAlert(invokeHeaders.ModifiedBy, detectorId, applensLink, detectorAuthorEmails);
            }

            return(Ok(JsonConvert.DeserializeObject(await responseTask)));
        }
Example #14
0
 public eBayOrdersService()
 {
     _context      = new ApiContext();
     _logger       = new LoggerRepository();
     _emailService = new EmailNotificationService();
 }
        public void SendNotification_MessageNull_ArgumentNullException()
        {
            var sut = new EmailNotificationService(this.mailSettings);

            Assert.ThrowsAsync <ArgumentNullException>(() => sut.SendNotificationAsync(null));
        }
Example #16
0
 public GreeterService(ILogger <GreeterService> logger, EmailNotificationService service)
 {
     _logger  = logger;
     _service = service;
 }