Inheritance: IEmailService
示例#1
0
        public ActionResult Contact(ContactMessage form)
        {
            if (!ModelState.IsValid)
            {
                return View(form);
            }

            var emailer = new EmailService();

            var mail = new IdentityMessage()
            {
                Destination = ConfigurationManager.AppSettings["PersonalEmail"],
                Subject = form.Subject,
                Body = "You have received a new contact form submission from" + form.Name + "(" + form.FromEmail + ") with the following contents:<br /><br /><br />" + form.Message
            };

            emailer.SendAsync(mail);

            //TempData["MessageSent"] = "Your message has been delivered successfully.";
            ViewBag.Messagesent = "Your message has been delivered successfully.";
            return View();
            //return RedirectToAction("Contact");

            /* ViewBag.Message = "Contact Shane Overby";

             return View();*/
        }
        public ActionResult Index(ContactMessage contactForm)
        {
            if (!ModelState.IsValid)
            {
                if (contactForm.FromEmail == null || !contactForm.IsValidEmail(contactForm.FromEmail))
                {
                    TempData["Error"] = "Please enter a valid email address.";
                }

                ViewBag.EmailError = TempData["Error"];
                return View(contactForm);
            }

            var emailer = new EmailService();

            var mail = new IdentityMessage
            {
                Subject = contactForm.Subject,
                Destination = ConfigurationManager.AppSettings["ContactMeEmail"],
                Body = "You have recieved a new contact form submission from " + contactForm.contactName +
                "( " + contactForm.FromEmail + " ) with the following contents<br/>" + contactForm.Message
            };

            emailer.SendAsync(mail);

            TempData["MessageSent"] = "Your message has been delivered successfully!";

            return RedirectToAction("Index");
        }
        public async Task<ActionResult> InviteToJoin(Invitation invitationModel)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                //check to make sure that the user has access
                ApplicationUser user = db.Users.FirstOrDefault(x => x.UserName == User.Identity.Name);
                Household household = db.Households.FirstOrDefault(x => x.Id == invitationModel.HouseholdId);

                if (!household.Members.Contains(user))
                {
                    return RedirectToAction("Unauthorized", "Error");
                }

                //ApplicationDbContext db = new ApplicationDbContext();
                Guid invitationCode = Guid.NewGuid();
                //Save invitation model to database to check later
                invitationModel.JoinCode = invitationCode;
                invitationModel.UserId = User.Identity.GetUserId();
                db.Invitations.Add(invitationModel);
                await db.SaveChangesAsync();

                IdentityMessage myMessage = new IdentityMessage();
                myMessage.Destination = invitationModel.ToEmail;
                myMessage.Subject = "Invitation to Join " + household.HouseholdName + " on CashCache";
                var callbackUrl = Url.Action("RegisterAndAdd", "Account", new { invitationId = invitationModel.Id, guid = invitationCode }, protocol: Request.Url.Scheme);
                myMessage.Body = "User " + user.UserName + " has invited you to join their household " + household.HouseholdName +
                    " on CashCache budget tracking application. Please click <a href =\"" + callbackUrl + "\">here</a> to accept their invitation.";

                EmailService emailService = new EmailService();
                await emailService.SendAsync(myMessage);

                return RedirectToAction("Details", "Household", new { id = invitationModel.HouseholdId });
            }
        }
示例#4
0
        private static void SendEmailNotificationsToUsers(UsersRepository usersRepository, EmailService emailService)
        {
            var notTempUsers = usersRepository.Users.Where(u => u.Temp == false);

            foreach (var user in notTempUsers)
            {
                if (user.Email != "Admin")
                {
                    var message = CreateEmailMessageForUser(user);

                    try
                    {
                        emailService.SendEmail(message, "support");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Failed to send email for {0}", user.Email);
                        Console.WriteLine("\tDetails: {0}", e.Message);
                        continue;
                    }


                    Console.WriteLine(String.Format("Sent email for {0}", user.Email));
                }
            }
        }
        public void CoordinatorCompleteWithEmailAndDefaultEmailSendsEmail()
        {
            var mailActioner = MockRepository.GenerateMock<IMailActioner>();
            var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>();
            var session = MockRepository.GenerateMock<IDocumentSession>();
            ravenDocStore.Expect(r => r.GetStore().OpenSession("Configuration"))
                .Return(session);
            var mailgunConfig = new MailgunConfiguration {ApiKey = "key", DomainName = "domain", DefaultFrom = "*****@*****.**"};
            session.Expect(s => s.Load<MailgunConfiguration>("MailgunConfig")).Return(mailgunConfig);
            var emailDefaultNotification = new EmailDefaultNotification { EmailAddresses = new List<string> { "*****@*****.**", "*****@*****.**" } };
            session.Expect(s => s.Load<EmailDefaultNotification>("EmailDefaultConfig")).Return(emailDefaultNotification);

            var message = new MailMessage();
            mailActioner.Expect(m => m.Send(Arg<MailgunConfiguration>.Is.Equal(mailgunConfig), Arg<MailMessage>.Is.NotNull)).WhenCalled(a => message = (MailMessage)(a.Arguments[1]));

            var emailService = new EmailService { MailActioner = mailActioner, RavenDocStore = ravenDocStore };
            var coordinatorComplete = new CoordinatorCompleteEmail
                                          {
                                              CoordinatorId = Guid.NewGuid(),
                                              EmailAddress = "*****@*****.**",
                                              FinishTimeUtc = DateTime.Now,
                                              StartTimeUtc = DateTime.Now.AddMinutes(-10),
                                              SendingData = new SendingData()
                                          };
            emailService.Handle(coordinatorComplete);

            mailActioner.VerifyAllExpectations();
            Assert.That(message.From.ToString(), Is.EqualTo(mailgunConfig.DefaultFrom));
            Assert.That(message.To[0].Address, Is.EqualTo(coordinatorComplete.EmailAddress));
            Assert.That(message.To[1].Address, Is.EqualTo(emailDefaultNotification.EmailAddresses[0]));
            Assert.That(message.To[2].Address, Is.EqualTo(emailDefaultNotification.EmailAddresses[1]));
        }
示例#6
0
        public void CanGetListOfPersonEventsForAGroup()
        {
            var eventRepository = MockRepository.GenerateStub<IEventRepository>();
            var eventList = new List<PersonEventDto> { new PersonEventDto(), new PersonEventDto(), new PersonEventDto() };
            var currentPerson = new Person {Permissions = new List<int> {57}};
            eventRepository
                .Expect(e => e.GetPersonEventsForGroup(1, currentPerson))
                .Return(eventList);

            var permissionRepository = new PermissionRepository();
            var personRepository = new PersonRepository(permissionRepository, new ChurchRepository());
            var usernamePasswordRepository = new UsernamePasswordRepository(permissionRepository);
            var groupRepository = new GroupRepository();
            var messageRepository = new MessageRepository();
            var messageRecepientRepository = new MessageRecepientRepository();
            var messageAttachmentRepository = new MessageAttachmentRepository();
            var emailSender = new EmailSender(messageRepository, messageRecepientRepository, messageAttachmentRepository, personRepository);
            var churchEmailTemplatesRepository = new ChurchEmailTemplatesRepository();
            var emailContentRepository = new EmailContentRepository();
            var emailContentService = new EmailContentService(emailContentRepository);
            var emailService = new EmailService(usernamePasswordRepository, personRepository, groupRepository, emailSender, emailContentService, churchEmailTemplatesRepository, permissionRepository);
            IEventService eventService = new EventService(eventRepository, emailService, new BirthdayAndAniversaryRepository());

            var sut = eventService.GetPersonEventsForGroup(1, currentPerson);

            Assert.That(sut.Count(), Is.EqualTo(3));
        }
        public void CoordinatorCreatedNoEmailWithDefaultEmailForCoordinatorSendEmail()
        {
            var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>();
            var session = MockRepository.GenerateMock<IDocumentSession>();
            var mailActioner = MockRepository.GenerateMock<IMailActioner>();
            var dateTimeMapper = MockRepository.GenerateMock<IDateTimeOlsenFromUtcMapping>();

            ravenDocStore.Expect(r => r.GetStore().OpenSession("Configuration"))
                .Return(session);
            var emailDefaultNotification = new EmailDefaultNotification { EmailAddresses = new List<string> { "*****@*****.**", "*****@*****.**" } };
            session.Expect(s => s.Load<EmailDefaultNotification>("EmailDefaultConfig")).Return(emailDefaultNotification);
            var mailgunConfig = new MailgunConfiguration {ApiKey = "key", DomainName = "domain", DefaultFrom = "*****@*****.**"};
            session.Expect(s => s.Load<MailgunConfiguration>("MailgunConfig")).Return(mailgunConfig);
            var message = new MailMessage();
            mailActioner.Expect(m => m.Send(Arg<MailgunConfiguration>.Is.Equal(mailgunConfig), Arg<MailMessage>.Is.NotNull)).WhenCalled(a => message = (MailMessage)(a.Arguments[1]));
            dateTimeMapper.Expect(d => d.DateTimeUtcToLocalWithOlsenZone(Arg<DateTime>.Is.Anything, Arg<string>.Is.Anything)).Return(DateTime.Now).Repeat.Any();

            var emailService = new EmailService { RavenDocStore = ravenDocStore, MailActioner = mailActioner, DateTimeOlsenFromUtcMapping = dateTimeMapper };
            var coordinatorComplete = new CoordinatorCreated { ScheduledMessages = new List<MessageSchedule> { new MessageSchedule { ScheduledTimeUtc = DateTime.Now }}, MetaData = new SmsMetaData()};
            emailService.Handle(new CoordinatorCreatedEmail(coordinatorComplete));

            Assert.That(message.From.Address, Is.EqualTo(mailgunConfig.DefaultFrom));
            Assert.That(message.To[0].Address, Is.EqualTo(emailDefaultNotification.EmailAddresses[0]));
            Assert.That(message.To[1].Address, Is.EqualTo(emailDefaultNotification.EmailAddresses[1]));
        }
示例#8
0
    public static void SendWelcomeEmail(string toEmail)
    {
        if (string.IsNullOrEmpty(toEmail))
            return;

        EmailService email = new EmailService("*****@*****.**", toEmail, "Welcome to Pow Wow", welcomeEmail);
        email.Send();
    }
 public HttpResponseMessage DailyNotifications()
 {
     EmailService emailService = new EmailService();
     bool result = emailService.DailyMailNotifications();
     if (result)
         return Request.CreateResponse(HttpStatusCode.OK , true);
     else
         return Request.CreateResponse(HttpStatusCode.InternalServerError , false);
 }
 public HttpResponseMessage ExecuteMailQueue()
 {
     EmailService emailService = new EmailService();
     bool result = emailService.ExecuteMailQueue();
     if (result)
         return Request.CreateResponse(HttpStatusCode.OK, true);
     else
         return Request.CreateResponse(HttpStatusCode.InternalServerError, false);
 }
 public HttpResponseMessage SetMailQueue(string body, string subject, List<string> mailTo)
 {
     EmailService emailService = new EmailService();
     bool result = emailService.SetMailQueue(body , subject , mailTo);
     if (result)
         return Request.CreateResponse(HttpStatusCode.OK, true);
     else
         return Request.CreateResponse(HttpStatusCode.InternalServerError, false);
 }
示例#12
0
 static void Main(string[] args)
 {
     var viewEngine = new ViewEngine();
     var bodyProvider = new TemplateProvider(new[] { new EmailTemplate(typeof(TestMail), "<b>{{Value}}</b>") });
     var subjectProvider = new TemplateProvider(new[] { new EmailTemplate(typeof(TestMail), "{{Title}}") });
     var emailService = new EmailService(new EmailRenderer(bodyProvider, viewEngine), new EmailRenderer(subjectProvider, viewEngine), new TestSmtpService());
     emailService.Send(new[] { "tt" }, new TestMail { Value = "777", Title = "555"});
     Console.ReadKey();
 }
示例#13
0
 public static void SendNotification(this ApplicationUser user, string subject, string body) {
     EmailService es = new EmailService();
     IdentityMessage im = new IdentityMessage {
         Destination = user.Email,
         Subject = subject,
         Body = body
     };
     es.SendAsync(im);
 }
 public void ShouldReturnFalseOnError()
 {
     var mock = new Mock<ISmtpClient>();
       mock.Setup(x => x.Send(It.IsAny<MailMessage>())).Throws(new Exception());
       var smtpException = mock.Object;
       var service = new EmailService(smtpException, "*****@*****.**", "Alias");
       var result = service.Send("*****@*****.**", "prova", "body of message", false, new List<Attachment> { new Attachment(new MemoryStream(), "file1") });
       Assert.AreEqual(false, result);
 }
示例#15
0
        public ActionResult Custom(CustomViewModel customViewModel)
        {
            customViewModel.PaymentFormHidden = false;
            var chargeOptions = new StripeChargeCreateOptions()
            {
                //required
                Amount = 3900,
                Currency = "usd",
                Source = new StripeSourceOptions() { TokenId = customViewModel.StripeToken },
                //optional
                Description = string.Format("JavaScript Framework Guide Ebook for {0}", customViewModel.StripeEmail),
                ReceiptEmail = customViewModel.StripeEmail
            };

            var chargeService = new StripeChargeService();

            try
            {
                StripeCharge stripeCharge = chargeService.Create(chargeOptions);

                //Validate charge
                chargeService.Capture(stripeCharge.Id);

                if (stripeCharge.Status == "succeeded")
                {
                    //creating the customer and add it to stripe
                    var newCustomer = new StripeCustomerService().Create(
                        new StripeCustomerCreateOptions
                        {
                            Email = customViewModel.StripeEmail
                        }
                        );
                    // CREATE NEW INVOICE
                    // var invoiceService = new StripeInvoiceService();
                    // StripeInvoice response = invoiceService.Create(newCustomer.Id); // optional StripeInvoiceCreateOptions
                    //var response = invoiceService.Upcoming(newCustomer.Id);
                    // stripeCharge.InvoiceId = response.Id;

                    //SEND THE CONFIRMATION
                    var emailService = new EmailService();
                    emailService.SendPaymentReceivedFromChargeEmail(stripeCharge);

                }
            }
            catch (StripeException stripeException)
            {
                Debug.WriteLine(stripeException.Message);
                ModelState.AddModelError(string.Empty, stripeException.Message);
                return View(customViewModel);
            }

            return RedirectToAction("Confirmation");
        }
        public void CoordinatorCreatedNoEmailNullDefaultEmailForCoordinatorNoAction()
        {
            var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>();
            var session = MockRepository.GenerateMock<IDocumentSession>();
            ravenDocStore.Expect(r => r.GetStore().OpenSession("Configuration"))
                .Return(session);
            session.Expect(s => s.Load<EmailDefaultNotification>("EmailDefaultConfig")).Return(null);

            var emailService = new EmailService { RavenDocStore = ravenDocStore };
            var coordinatorComplete = new CoordinatorCreated();
            emailService.Handle(new CoordinatorCreatedEmail(coordinatorComplete));
        }
示例#17
0
        public ActionResult Contact(ContactMessage contact)
        {
            var es = new EmailService();
            var msg = new IdentityMessage();
            msg.Destination = ConfigurationManager.AppSettings["ContactEmail"];
            msg.Body = "You have been sent a message from " + contact.Name + " (" + contact.Email + ") with the following contents. <br/><br/>\"" + contact.Message + "\"";
            msg.Subject = "Message received through Words from the West";
            es.SendAsync(msg);

            //ViewBag.Message = "Your message was sent successfully. Thank you!";
            return Redirect("http://awest.azurewebsites.net");
        }
示例#18
0
        public ActionResult Contact(string name,string email,string subject,string message)
        {
            IdentityMessage msg = new IdentityMessage();
            EmailService ems = new EmailService();

            msg.Subject = subject;
            msg.Destination = ConfigurationManager.AppSettings["ContactEmail"];
            msg.Body = "From : " + name + "<BR> Email : " + email + "<BR> Message : " + message;
            ems.SendAsync(msg);
            TempData["Message"] = "Your Message Has Been Sent.";
            return RedirectToAction("Contact");
        }
示例#19
0
        public void Should_Not_Email_Outsiders_NonProd(String email)
        {
            
            IEmailService emailer = new EmailService(new System.Net.Mail.SmtpClient());

            using (var msg = new MailMessage { From = new MailAddress("*****@*****.**") })
            {
                msg.To.Add(email);

                emailer.Send(msg);
            }
        }
示例#20
0
        public async Task<ActionResult> Index(string contactName, string contactEmail, string contactSubject, string contactMessage) {
            
            EmailService emailService = new EmailService();
            IdentityMessage identityMessage = new IdentityMessage();
            identityMessage.Subject = contactSubject;
            identityMessage.Body = "From : " + contactName + "<br />Email: " + contactEmail + "<br /><br />Email Message: " + contactMessage;
            identityMessage.Destination = ConfigurationManager.AppSettings["FromEmail"];

            await emailService.SendAsync(identityMessage);
            return RedirectToAction("Index");

        }
        public void CoordinatorCompleteWithEmailDefaultFromNotSentThrowsException()
        {
            var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>();
            var session = MockRepository.GenerateMock<IDocumentSession>();
            ravenDocStore.Expect(r => r.GetStore().OpenSession("Configuration"))
                .Return(session);
            var mailgunConfig = new MailgunConfiguration { ApiKey = "key", DomainName = "domain", DefaultFrom = string.Empty };
            session.Expect(s => s.Load<MailgunConfiguration>("MailgunConfig")).Return(mailgunConfig);

            var emailService = new EmailService { RavenDocStore = ravenDocStore };
            var coordinatorComplete = new CoordinatorCompleteEmail { EmailAddress = "*****@*****.**" };
            Assert.That(() => emailService.Handle(coordinatorComplete), Throws.Exception.With.Message.EqualTo("Could not find the default 'From' sender."));
        }
        public void SendMessage_Success()
        {
            // Arrange
            var email = new EmailService();
            var expected = "Message sent: Test Message";

            // Act
            var actual = email.SendMessage("Test Message",
                "This is a test message", "*****@*****.**");

            // Assert
            Assert.AreEqual(expected, actual);
        }
        public async Task<ActionResult> Index(FeedbackViewModel model)
        {
            if (model == null || !ModelState.IsValid)
            {
                return this.View(model);
            }

            EmailService email = new EmailService();

            await email.SendFeedbackEmailAsync(model);

            return this.RedirectToAction("Index");
        }
        public void MessageNotSentWithEmailDefaultFromNotSentThrowsException()
        {
            var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>();
            var session = MockRepository.GenerateMock<IDocumentSession>();
            ravenDocStore.Expect(r => r.GetStore().OpenSession("Configuration"))
                .Return(session);
            var mailgunConfig = new MailgunConfiguration { ApiKey = "key", DomainName = "domain", DefaultFrom = string.Empty };
            session.Expect(s => s.Load<MailgunConfiguration>("MailgunConfig")).Return(mailgunConfig);

            var emailService = new EmailService { RavenDocStore = ravenDocStore };
            var messageFailedSending = new MessageFailedSending { ConfirmationEmailAddress = "*****@*****.**", SmsData = new SmsData("mobile", "message"), SmsMetaData = new SmsMetaData { Tags = new List<string> { "a" }, Topic = "topic" } };
            Assert.That(() => emailService.Handle(messageFailedSending), Throws.Exception.With.Message.EqualTo("Could not find the default 'From' sender."));
        }
        public void CoordinatorCompleteNoEmailInMessageOrDefaultNoAction()
        {
            var ravenDocStore = MockRepository.GenerateMock<IRavenDocStore>();
            var session = MockRepository.GenerateMock<IDocumentSession>();
            ravenDocStore.Expect(r => r.GetStore().OpenSession("Configuration"))
                .Return(session);
            var emailDefaultNotification = new EmailDefaultNotification();
            session.Expect(s => s.Load<EmailDefaultNotification>("EmailDefaultConfig")).Return(emailDefaultNotification);

            var emailService = new EmailService { RavenDocStore = ravenDocStore };
            var coordinatorComplete = new CoordinatorCompleteEmailWithSummary();
            emailService.Handle(coordinatorComplete);
        }
示例#26
0
        public ActionResult Contact(ContactMessage contact)
        {
            var Emailer = new EmailService();
            var mail = new IdentityMessage
            {
                Subject = "Message",
                Destination = ConfigurationManager.AppSettings["ContactEmail"],
                Body = "You have recieved a new ContactForm Submission from: " + "(" + contact.c_email + ") with the following contents. \n\n" + contact.c_message
            };
            Emailer.SendAsync(mail);

            return RedirectToAction("Index", "BlogPosts");
        }
示例#27
0
        public void Sends_an_Email()
        {
            // Arrange
            var credentials = new NetworkCredential();
            var service = new EmailService(credentials);
            var data = new
            {
                SiteName = "Site Name",
                EmailVerificationUrl = "http://www.sample.com/verify/1234567890"
            };

            // Act
            service.Send("*****@*****.**", "WelcomeNewUser", "Welcome to Site", data);
        }
示例#28
0
        public void Should_Not_Allow_Any_Email_When_Testing_Domains_Enabled(string email)
        {

            EmailService.AllowedTestingDomainsEnabled = false;

            IEmailService emailer = new EmailService(new SmtpClient());

            using (var msg = new MailMessage { From = new MailAddress("*****@*****.**") })
            {
                msg.To.Add(email);

                emailer.Send(msg);
            }

        }
示例#29
0
        public ActionResult Create([Bind(Include = "HouseholdId,HouseholdName,IssuedBy,GuestEmail")] Invitation invitation)
        {
            var INVITATION_CODE_LENGTH = 12;
            var EXPIRATION_DAYS = 7;
            var EXPIRATION_HOURS = 24;

            if (ModelState.IsValid)
            {
                invitation.IssuedOn = System.DateTimeOffset.Now;
                invitation.InvalidAfter = invitation.IssuedOn.AddHours(EXPIRATION_HOURS); //.AddDays(EXPIRATION_DAYS);

                invitation.InvitationCode = GetUniqueKey(INVITATION_CODE_LENGTH);
                db.Invitations.Add(invitation);
                db.SaveChanges();
                // vvvvvvvvv end send Email vvvvvvvvv

                var callbackRegisterUrl = Url.Action("Register", "Account", new { code = invitation.InvitationCode }, protocol: Request.Url.Scheme);
                var manualRegisterUrl = Url.Action("Register", "Account", new { code = "" }, protocol: Request.Url.Scheme);
                var callbackLoginUrl = Url.Action("Login", "Account", new { code = invitation.InvitationCode }, protocol: Request.Url.Scheme);
                var manualLoginUrl = Url.Action("Login", "Account", new { code = "" }, protocol: Request.Url.Scheme);
                //await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                var SendTo = invitation.GuestEmail;
                var es = new EmailService();
                var msg = new IdentityMessage
                {
                    Subject = "Invitation to join TGP-Budget App",
                    Destination = SendTo,
                    Body = "On " + invitation.IssuedOn.DateTime.ToLongDateString() + ", " + invitation.IssuedBy +
                    " sent you an invitation to join the " + invitation.HouseholdName + " house hold.<br />" +
                    "Please register at  within the next " + EXPIRATION_DAYS + " days. <br />" +
                    "To REGISTER with TGP-Budget and JOIN this household  by clicking <a href=\"" + callbackRegisterUrl + "\">here.</a><br /><br />" +
                    "To login manually, navigate to this address: < a href =\"" + manualRegisterUrl + "\">here</a>" +
                    "and enter the following household code: <b>" + invitation.InvitationCode + "</b> <br /><br /><br />" +

                    "(Note: if you have already visited registered, then" +
                    "To LOGIN  by clicking <a href=\"" + callbackLoginUrl + "\">here.</a><br /><br />" +
                    "To login manually, navigate to this address: < a href =\"" + manualLoginUrl + "\">here</a>" +
                    "and enter the following household code: <b>" + invitation.InvitationCode + "</b> )."
                };
                es.SendAsync(msg);

                // ^^^^^^^^^ end send Email ^^^^^^^^^
                return RedirectToAction("Index", "Dashboard", "Home");
            }

            //ViewBag.HouseholdId = new SelectList(db.Households, "Id", "Name", invitation.HouseholdId);
            return View(invitation);
        }
示例#30
0
 public ServiceList(string url, ResponseToken token)
 {
     this.eventService = new EventService(url, token);
     this.categoryService = new CategoryService(url, token);
     this.clubService = new ClubService(url, token);
     this.userService = new UserService(url, token);
     this.ticketService = new TicketService(url, token);
     this.meetingService = new MeetingService(url, token);
     this.invoiceService = new InvoiceService(url, token);
     this.groupService = new GroupService(url, token);
     this.expenseService = new ExpenseService(url, token);
     this.emailService = new EmailService(url, token);
     this.depositService = new DepositService(url, token);
     this.customFieldService = new CustomFieldService(url, token);
     this.taskService = new TaskService(url, token);
     this.contactService = new ContactService(url, token);
 }
示例#31
0
        public async Task <bool> PKCheck()
        {
            List <string> errors = new List <string>();

            try
            {
                // primary Key check is only available by put api , so in this case it must be a putapiModel
                // and need to convert to it to get the primary keys lsit

                PutDataApiModel data = (PutDataApiModel)_data;
                string[]        pks  = null;
                if (data != null)
                {
                    pks = data.PrimaryKeys;
                }

                variableIds = new List <long>();
                if (pks != null && _dataStructure != null)
                {
                    //check if primary keys are exiting in the datastrutcure
                    foreach (var variable in _dataStructure.Variables)
                    {
                        if (pks.Any(p => p.ToLower().Equals(variable.Label.ToLower())))
                        {
                            variableIds.Add(variable.Id);
                        }
                    }

                    if (!variableIds.Count.Equals(pks.Count()))
                    {
                        errors.Add("The list of primary keys is unequal to the existing equal variables in the datatructure.");
                        return(false);
                    }

                    bool IsUniqueInDb   = uploadHelper.IsUnique2(_dataset.Id, variableIds);
                    bool IsUniqueInFile = uploadHelper.IsUnique(_dataset.Id, variableIds, ".tsv", Path.GetFileName(_filepath), _filepath, new AsciiFileReaderInfo(), _dataStructure.Id);

                    if (!IsUniqueInDb || !IsUniqueInFile)
                    {
                        if (!IsUniqueInDb)
                        {
                            errors.Add("The selected key is not unique in the data in the dataset.");
                        }
                        if (!IsUniqueInFile)
                        {
                            errors.Add("The selected key is not unique in the received data.");
                        }
                    }
                }
                else
                {
                    errors.Add("The list of primary keys is empty.");
                }

                if (errors.Count == 0)
                {
                    return(await Validate());
                }
                else
                {
                    return(false);
                }
            }
            finally
            {
                var es = new EmailService();
                es.Send(MessageHelper.GetPushApiPKCheckHeader(_dataset.Id, _title),
                        MessageHelper.GetPushApiPKCheckMessage(_dataset.Id, _user.UserName, errors.ToArray()),
                        new List <string>()
                {
                    _user.Email
                },
                        new List <string>()
                {
                    ConfigurationManager.AppSettings["SystemEmail"]
                }
                        );
            }
        }
示例#32
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Register", model));
            }

            try
            {
                var userStore   = NewUserStore();
                var userManeger = NewUserManager();
                var roleManager = NewRoleManager();
                var user        = await userManeger.FindByNameAsync(model.UserName);

                if (user != null)
                {
                    ModelState.AddModelError("UserName", "Bu kullanıcı adı daha önceden alınmıştır.");
                    return(View("Register", model));
                }

                var newUser = new User()
                {
                    UserName       = model.UserName,
                    Email          = model.Email,
                    Name           = model.Name,
                    Surname        = model.Surname,
                    ActivationCode = new StringHelper().GetCode()
                };
                var result = await userManeger.CreateAsync(newUser, model.Password);

                if (result.Succeeded)
                {
                    if (userStore.Users.Count() == 1)
                    {
                        await userManeger.AddToRoleAsync(newUser.Id, "Admin");
                    }
                    else
                    {
                        await userManeger.AddToRoleAsync(newUser.Id, "User");
                    }

                    string SiteUrl = Request.Url.Scheme + Uri.SchemeDelimiter + Request.Url.Host +
                                     (Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port);
                    var    emailservice = new EmailService();
                    string body         = $"Merhaba <b>{newUser.Name} {newUser.Surname}</b></br>Hesabınızı Aktif etmek için aşağıda ki linke tıklayınız<br> <a href='{SiteUrl}/Account/Activation?code={newUser.ActivationCode}'>Aktivasyon Linki</a>";
                    await emailservice.SendAsync(new IdentityMessage()
                    {
                        Body = body, Subject = "Sitemize Hoş Geldiniz"
                    }, newUser.Email);
                }
                else
                {
                    var err = "";
                    foreach (var resultError in result.Errors)
                    {
                        err += resultError + " ";
                    }
                    ModelState.AddModelError("", err.ToString());
                    return(View("Register", model));
                }

                return(View("Login"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
示例#33
0
        public async Task <ActionResult> Create(Student student)
        {
            try
            {
                ViewBag.Grade = new SelectList(Common.Grades(), "ID", "Description");
                Organization org = Session["Organization"] as Organization;
                if (org != null)
                {
                    student.SchoolID    = org.SchoolID;
                    student.DefaultGoal = org.DefaultGoal.ToString();
                    student.Message     = "";
                    student.image       = "";
                    student.Active      = true;
                }



                //RegisterModel distributor = db.Distributors.Find(org.Distributor);
                //student.image=org.

                db.Students.Add(student);

                db.SaveChanges();
                Session["StudentIDs"] = student.StudentID;

                EmailService    email   = new EmailService();
                IdentityMessage details = new IdentityMessage();
                details.Destination = student.EmailAddress;
                details.Subject     = "Welcome Mail! Fundraisingshop.com";
                Dictionary <string, string> param = new Dictionary <string, string>();
                param.Add("<%ID%>", student.ID.ToString());
                param.Add("<%UserID%>", student.StudentID);
                param.Add("<%password%>", student.Password);
                details.Body = ShrdMaster.Instance.buildEmailBody("WelcomeMessage.txt", param);
                await email.SendAsync(details);

                UserRole userrole = new Models.UserRole();
                userrole.UserId = student.ID;
                userrole.RoleId = 2;
                db.UserRoles.Add(userrole);
                db.SaveChanges();
                //Roles.AddUserToRole("Admin", "Student");
                ViewBag.ID = student.ID;
                return(RedirectToAction("personalization", new { studentID = student.StudentID, option = 1 }));
                //return RedirectToAction("Success", new { ID=student.StudentID });
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                Exception raise = dbEx;
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        string message = string.Format("{0}:{1}",
                                                       validationErrors.Entry.Entity.ToString(),
                                                       validationError.ErrorMessage);
                        // raise a new exception nesting
                        // the current instance as InnerException
                        raise = new InvalidOperationException(message, raise);
                    }
                }
                throw raise;
            }


            // return View(student);
        }
示例#34
0
        public async Task <int> MoveToSecondRole(int projectId, int claimId, int characterId)
        {
            var oldClaim = (await ClaimsRepository.GetClaim(projectId, claimId)).RequestAccess(CurrentUserId); //TODO Specific right

            oldClaim.EnsureStatus(Claim.Status.CheckedIn);

            Debug.Assert(oldClaim.Character != null, "oldClaim.Character != null");
            oldClaim.Character.InGame = false;
            MarkChanged(oldClaim.Character);

            var source = await CharactersRepository.GetCharacterAsync(projectId, characterId);

            MarkChanged(source);

            // TODO improve valitdation here
            //source.EnsureCanMoveClaim(oldClaim);

            var responsibleMaster = source.GetResponsibleMasters().FirstOrDefault();
            var claim             = new Claim()
            {
                CharacterGroupId        = null,
                CharacterId             = characterId,
                ProjectId               = projectId,
                PlayerUserId            = oldClaim.PlayerUserId,
                PlayerAcceptedDate      = Now,
                CreateDate              = Now,
                ClaimStatus             = Claim.Status.Approved,
                CurrentFee              = 0,
                ResponsibleMasterUserId = responsibleMaster?.UserId,
                ResponsibleMasterUser   = responsibleMaster,
                LastUpdateDateTime      = Now,
                MasterAcceptedDate      = Now,
                CommentDiscussion       =
                    new CommentDiscussion()
                {
                    CommentDiscussionId = -1, ProjectId = projectId
                },
            };

            claim.CommentDiscussion.Comments.Add(new Comment
            {
                CommentDiscussionId = -1,
                AuthorUserId        = CurrentUserId,
                CommentText         = new CommentText {
                    Text = new MarkdownString(".")
                },
                CreatedAt         = Now,
                IsCommentByPlayer = false,
                IsVisibleToPlayer = true,
                ProjectId         = projectId,
                LastEditTime      = Now,
                ExtraAction       = CommentExtraAction.SecondRole,
            });

            oldClaim.ClaimStatus = Claim.Status.Approved;
            source.ApprovedClaim = claim;
            AddCommentImpl(oldClaim, null, ".", true, CommentExtraAction.OutOfGame);


            UnitOfWork.GetDbSet <Claim>().Add(claim);

            // ReSharper disable once UnusedVariable TODO decide if we should send email if FieldDefaultValueGenerator changes something
            var updatedFields =
                FieldSaveHelper.SaveCharacterFields(CurrentUserId, claim, new Dictionary <int, string>(),
                                                    FieldDefaultValueGenerator);

            await UnitOfWork.SaveChangesAsync();

            var claimEmail = await CreateClaimEmail <SecondRoleEmail>(claim, "",
                                                                      s => s.ClaimStatusChange,
                                                                      CommentExtraAction.NewClaim);

            await EmailService.Email(claimEmail);

            return(claim.ClaimId);
        }
示例#35
0
        public async Task <bool> Validate()
        {
            Debug.WriteLine("start validate data");

            string error = "";

            //load strutcured data structure

            if (_dataStructure == null)
            {
                // send email to user ("failed to load datatructure");
                return(false);
            }

            // validate file
            Stream = reader.Open(_filepath);
            reader.ValidateFile(Stream, Path.GetFileName(_filepath), _dataset.Id);
            List <Error> errors = reader.ErrorMessages;

            // if errors exist -> send messages back
            if (errors.Count > 0)
            {
                List <string> errorArray = new List <string>();

                foreach (var e in errors)
                {
                    errorArray.Add(e.GetMessage());
                }

                var es = new EmailService();
                es.Send(MessageHelper.GetPushApiValidateHeader(_dataset.Id, _title),
                        MessageHelper.GetPushApiValidateMessage(_dataset.Id, _user.UserName, errorArray.ToArray()),
                        new List <string>()
                {
                    _user.Email
                },
                        new List <string>()
                {
                    ConfigurationManager.AppSettings["SystemEmail"]
                }
                        );

                return(false);
            }
            else
            {
                var es = new EmailService();
                es.Send(MessageHelper.GetPushApiValidateHeader(_dataset.Id, _title),
                        MessageHelper.GetPushApiValidateMessage(_dataset.Id, _user.UserName),
                        new List <string>()
                {
                    _user.Email
                },
                        new List <string>()
                {
                    ConfigurationManager.AppSettings["SystemEmail"]
                }
                        );
            }
            Debug.WriteLine("end validate data");

            return(await Upload());
        }
        public bool Sendmail(string email, int action)
        {
            var checkmember   = db.UngViens.Where(x => x.EmailDN == email).FirstOrDefault();
            var checkemployer = db.CongTies.Where(x => x.Emaildangnhap == email).FirstOrDefault();
            var configmail    = db.ConfigMails.Where(x => x.smtpType == 1).FirstOrDefault();

            if (configmail == null)
            {
                configmail = new ConfigMail();
            }
            if (action == 1)
            {
                Random pass = new Random();
                double pw   = pass.Next(0, 999999);
                checkmember.matkhaureset = LoginMember.MD5Hash(checkmember.EmailDN) + LoginMember.MD5Hash(pw.ToString());
                string smtpUserName = configmail.smtUserName;
                string smtpPassword = configmail.smtpPassword;
                string smtpHost     = configmail.smtpHost;
                int    smtpPort     = int.Parse(configmail.smtpPort.ToString());

                string emailTo = checkmember.EmailDN;
                if (configmail.EnableSSL == null)
                {
                    configmail.EnableSSL = false;
                }
                bool         ssl         = bool.Parse(configmail.EnableSSL.ToString());
                string       subject     = configmail.smtpSubject;
                string       mailcontent = new EmailService().RenderPartialViewToString(this, "_MailForgotPassword", checkmember);
                string       body        = mailcontent;
                EmailService service     = new EmailService();

                bool kq = service.Send(smtpUserName, smtpPassword, smtpHost, smtpPort,
                                       emailTo, subject, body, ssl);
                db.SaveChanges();
                return(kq);
            }
            else
            {
                Random pass = new Random();
                double pw   = pass.Next(0, 999999);
                checkemployer.matkhaureset = LoginMember.MD5Hash(checkemployer.Emaildangnhap) + LoginMember.MD5Hash(pw.ToString());
                string smtpUserName = configmail.smtUserName;
                string smtpPassword = configmail.smtpPassword;
                string smtpHost     = configmail.smtpHost;
                int    smtpPort     = int.Parse(configmail.smtpPort.ToString());
                if (configmail.EnableSSL == null)
                {
                    configmail.EnableSSL = false;
                }
                bool         ssl         = bool.Parse(configmail.EnableSSL.ToString());
                string       emailTo     = checkemployer.Emaildangnhap;
                string       subject     = configmail.smtpSubject;
                string       mailcontent = new EmailService().RenderPartialViewToString(this, "_MailForgotPasswordEmployer", checkemployer);
                string       body        = mailcontent;
                EmailService service     = new EmailService();

                bool kq = service.Send(smtpUserName, smtpPassword, smtpHost, smtpPort,
                                       emailTo, subject, body, ssl);
                db.SaveChanges();
                return(kq);
            }
        }
示例#37
0
        public async Task <AccommodationRequest> SetAccommodationType(int projectId,
                                                                      int claimId,
                                                                      int roomTypeId)
        {
            //todo set first state to Unanswered
            var claim = await ClaimsRepository.GetClaim(projectId, claimId).ConfigureAwait(false);

            claim = claim.RequestAccess(CurrentUserId,
                                        acl => acl.CanSetPlayersAccommodations,
                                        claim?.ClaimStatus == Claim.Status.Approved
                  ? ExtraAccessReason.PlayerOrResponsible
                  : ExtraAccessReason.None);

            // Player cannot change accommodation type if already checked in

            if (claim.AccommodationRequest?.AccommodationTypeId == roomTypeId)
            {
                return(claim.AccommodationRequest);
            }

            var newType = await UnitOfWork.GetDbSet <ProjectAccommodationType>().FindAsync(roomTypeId)
                          .ConfigureAwait(false);

            if (newType == null)
            {
                throw new JoinRpgEntityNotFoundException(roomTypeId,
                                                         nameof(ProjectAccommodationType));
            }

            var email = EmailHelpers.CreateFieldsEmail(claim,
                                                       s => s.AccommodationChange,
                                                       await GetCurrentUser(),
                                                       new FieldWithPreviousAndNewValue[] {},
                                                       new Dictionary <string, PreviousAndNewValue>()
            {
                {
                    "Тип поселения",   //TODO[Localize]
                    new PreviousAndNewValue(newType.Name, claim.AccommodationRequest?.AccommodationType.Name)
                },
            });


            var leaveEmail = await ConsiderLeavingRoom(claim);

            var accommodationRequest = new AccommodationRequest
            {
                ProjectId = projectId,
                Subjects  = new List <Claim> {
                    claim
                },
                AccommodationTypeId = roomTypeId,
                IsAccepted          = AccommodationRequest.InviteState.Accepted,
            };

            UnitOfWork
            .GetDbSet <AccommodationRequest>()
            .Add(accommodationRequest);
            await UnitOfWork.SaveChangesAsync().ConfigureAwait(false);

            await EmailService.Email(email);

            if (leaveEmail != null)
            {
                await EmailService.Email(leaveEmail);
            }

            return(accommodationRequest);
        }
示例#38
0
        public async Task <bool> Upload()
        {
            Debug.WriteLine("start upload data");

            FileStream Stream = null;

            DatasetVersion   workingCopy = new DatasetVersion();
            List <DataTuple> rows        = new List <DataTuple>();

            long   id       = _dataset.Id;
            string userName = _user.UserName;
            var    es       = new EmailService();

            try
            {
                List <long> datatupleFromDatabaseIds = datasetManager.GetDatasetVersionEffectiveTupleIds(datasetManager.GetDatasetLatestVersion(_dataset.Id));

                if (FileHelper.FileExist(_filepath) && (datasetManager.IsDatasetCheckedOutFor(id, userName) || datasetManager.CheckOutDataset(id, userName)))
                {
                    workingCopy = datasetManager.GetDatasetWorkingCopy(id);

                    ////set modification
                    workingCopy.ModificationInfo = new EntityAuditInfo()
                    {
                        Performer  = userName,
                        Comment    = "Data",
                        ActionType = AuditActionType.Edit
                    };

                    //schleife
                    int  counter         = 0;
                    bool inputWasAltered = false;
                    do
                    {
                        counter++;
                        inputWasAltered = false;
                        Stream          = reader.Open(_filepath);
                        rows            = reader.ReadFile(Stream, Path.GetFileName(_filepath), id, packageSize);
                        Stream.Close();

                        // if errors exist, send email to user and stop process
                        if (reader.ErrorMessages.Count > 0)
                        {
                            List <string> errorArray = new List <string>();

                            foreach (var e in reader.ErrorMessages)
                            {
                                errorArray.Add(e.GetMessage());
                            }

                            //send error messages
                            es.Send(MessageHelper.GetPushApiUploadFailHeader(_dataset.Id, _title),
                                    MessageHelper.GetPushApiUploadFailMessage(_dataset.Id, _user.UserName, errorArray.ToArray()),
                                    new List <string>()
                            {
                                _user.Email
                            },
                                    new List <string>()
                            {
                                ConfigurationManager.AppSettings["SystemEmail"]
                            }
                                    );

                            return(false);
                        }

                        //Update Method -- append or update
                        if (_uploadMethod == UploadMethod.Append)
                        {
                            if (rows.Count > 0)
                            {
                                datasetManager.EditDatasetVersion(workingCopy, rows, null, null);
                                inputWasAltered = true;
                            }
                        }
                        else if (_uploadMethod == UploadMethod.Update)
                        {
                            if (rows.Count() > 0)
                            {
                                var splittedDatatuples = uploadHelper.GetSplitDatatuples(rows, variableIds, workingCopy, ref datatupleFromDatabaseIds);
                                datasetManager.EditDatasetVersion(workingCopy, splittedDatatuples["new"], splittedDatatuples["edit"], null);
                                inputWasAltered = true;
                            }
                        }
                    } while (rows.Count() > 0 || inputWasAltered == true);

                    datasetManager.CheckInDataset(id, "via api", userName);

                    string title = workingCopy.Title;

                    //send email
                    es.Send(MessageHelper.GetUpdateDatasetHeader(id),
                            MessageHelper.GetUpdateDatasetMessage(id, title, _user.DisplayName),
                            new List <string>()
                    {
                        _user.Email
                    },
                            new List <string>()
                    {
                        ConfigurationManager.AppSettings["SystemEmail"]
                    }
                            );
                }
                else
                {
                    //ToDo send email to user
                    es.Send(MessageHelper.GetPushApiUploadFailHeader(_dataset.Id, _title),
                            MessageHelper.GetPushApiUploadFailMessage(_dataset.Id, _user.UserName, new string[] { "The temporarily stored data could not be read or the dataset is already in checkout status." }),
                            new List <string>()
                    {
                        _user.Email
                    },
                            new List <string>()
                    {
                        ConfigurationManager.AppSettings["SystemEmail"]
                    }
                            );
                }

                return(true);
            }
            catch (Exception ex)
            {
                if (datasetManager.IsDatasetCheckedOutFor(id, userName))
                {
                    datasetManager.UndoCheckoutDataset(id, userName);
                }

                //ToDo send email to user
                es.Send(MessageHelper.GetPushApiUploadFailHeader(_dataset.Id, _title),
                        MessageHelper.GetPushApiUploadFailMessage(_dataset.Id, _user.UserName, new string[] { ex.Message }),
                        new List <string>()
                {
                    _user.Email
                },
                        new List <string>()
                {
                    ConfigurationManager.AppSettings["SystemEmail"]
                }
                        );

                return(false);
            }
            finally
            {
                Debug.WriteLine("end of upload");
            }
        }
示例#39
0
 public static void init(IServiceCollection services)
 {
     SmsService.setImplementation <HubtelSmsService>();
     EmailService.setImplementation <ElasticEmailService>();
     UssdService.setImplementation <NaloUssdService>();
 }
 public ScheduledHourController(AppointmentSchedulerContext context, EmailService emailService)
 {
     _respository = new ScheduledHourRepository(context, emailService);
 }
示例#41
0
 static void Main(string[] args)
 {
     EmailService
     .EnviarEmail(new Entidades.Pessoa("0000000000", "Ronald", "*****@*****.**"));
     Console.ReadLine();
 }
示例#42
0
 public BlogController(IDBService repo, IConfiguration config, EmailService emailService)
 {
     _repo         = repo;
     _config       = config;
     _emailService = emailService;
 }
示例#43
0
        public ActionResult Summary(object[] data)
        {
            int numberOfRows = 0;

            TaskManager = (TaskManager)Session["TaskManager"];
            _bus        = TaskManager.Bus;

            SummaryModel model = new SummaryModel();

            model.StepInfo = TaskManager.Current();

            long id = Convert.ToInt32(_bus[TaskManager.DATASET_ID]);

            DataASyncUploadHelper asyncUploadHelper = new DataASyncUploadHelper();

            asyncUploadHelper.Bus          = _bus;
            asyncUploadHelper.User         = GetUser();
            asyncUploadHelper.RunningASync = isASyncUpload();

            if (TaskManager.Bus.ContainsKey(TaskManager.DATASET_TITLE) && TaskManager.Bus[TaskManager.DATASET_TITLE] != null)
            {
                model.DatasetTitle = TaskManager.Bus[TaskManager.DATASET_TITLE].ToString();
            }

            if (TaskManager.Bus.ContainsKey(TaskManager.NUMBERSOFROWS))
            {
                numberOfRows = Convert.ToInt32(TaskManager.Bus[TaskManager.NUMBERSOFROWS]);
            }



            if (asyncUploadHelper.RunningASync) //async
            {
                Task.Run(() => asyncUploadHelper.FinishUpload());

                // send email after starting the upload
                var es   = new EmailService();
                var user = GetUser();

                es.Send(MessageHelper.GetASyncStartUploadHeader(id, model.DatasetTitle),
                        MessageHelper.GetASyncStartUploadMessage(id, model.DatasetTitle, numberOfRows),
                        new List <string>()
                {
                    user.Email
                }, null,
                        new List <string>()
                {
                    ConfigurationManager.AppSettings["SystemEmail"]
                }
                        );



                model.AsyncUpload        = true;
                model.AsyncUploadMessage = "All upload information has been entered and the upload will start now. After completion an email will be sent.";
            }
            else
            {
                List <Error> errors = asyncUploadHelper.FinishUpload().Result;
                if (errors.Count == 0)
                {
                    return(null);
                }
                else
                {
                    foreach (var error in errors)
                    {
                        ModelState.AddModelError("", error.ToHtmlString());
                    }
                }
            }

            // set model for the page
            #region set summary

            model = updateModel(model);

            #endregion set summary

            return(PartialView(model));
        }
        private ActionResult Save(int?id, EditCommentViewModel formData)
        {
            var ticket = DbContext.Tickets
                         .FirstOrDefault(p => p.ID == formData.TicketID);

            if (!ModelState.IsValid)
            {
                return(View());
                //return RedirectToAction("FullTicketBySlug", "Ticket", new { slug = ticket.Slug });
            }

            var userId = User.Identity.GetUserId();

            TicketComment comment;

            if (!id.HasValue)
            {
                comment = new TicketComment
                {
                    DateCreated = DateTime.Now,
                    Comment     = formData.Comment,
                    TicketID    = formData.TicketID,
                    UserID      = userId
                };
                DbContext.TicketComments.Add(comment);
            }
            else
            {
                comment = DbContext.TicketComments.FirstOrDefault(
                    p => p.ID == formData.ID);

                if (comment == null)
                {
                    return(RedirectToAction(nameof(ProjectController.Index)));
                }

                if ((User.IsInRole("Admin") || User.IsInRole("Project Manager")) ||
                    (User.IsInRole("Developer") && userId == comment.UserID) ||
                    (User.IsInRole("Submitter") && userId == comment.UserID))
                {
                    // continue
                }
                else
                {
                    return(RedirectToAction("FullTicketBySlug", "Ticket", new { slug = ticket.Slug }));
                }

                comment.Comment = formData.Comment;
            }

            var notifyUsers = DbContext.TicketNotifications.Where(u => u.TicketID == ticket.ID).ToList();

            foreach (var notifyuser in notifyUsers)
            {
                var    user  = DbContext.Users.FirstOrDefault(u => u.Id == notifyuser.UserID);
                string alert = $"new comment on a ticket you are watching: {ticket.Title}";
                if (user == ticket.AssignedToUser)
                {
                    alert = $"new comment on a ticket assigned to you: {ticket.Title}";
                }
                var message = new IdentityMessage
                {
                    Destination = $"{user.Email}",
                    Subject     = $"{alert}",
                    Body        = $"{alert}"
                };
                var emailService = new EmailService();
                emailService.SendAsync(message);
            }

            DbContext.SaveChanges();

            return(RedirectToAction("FullTicketBySlug", "Ticket", new { slug = ticket.Slug }));
        }
示例#45
0
        public async Task <ActionResult> Personalization(HttpPostedFileBase FileUpload, FormCollection fc)
        // public ActionResult Personalization(HttpPostedFileBase FileUpload,FormCollection fc)
        {
            int     studentid;
            string  orgID   = "";
            string  message = "";
            Student student = null;

            if (fc["ID"].ToString() != null)
            {
                int.TryParse(fc["ID"].ToString(), out studentid);
                student = db.Students.Find(studentid);
            }
            PersonalizationData(student.StudentID);


            if (student != null)
            {
                orgID = student.SchoolID;

                //int.TryParse(student.SchoolID, out orgID);
                string mailImagePath = "";
                //Organization org = db.Organizations.Find(orgID);

                Organization                org     = db.Organizations.Where(x => x.SchoolID == orgID && x.IsActive == true).SingleOrDefault();
                EmailService                email   = new EmailService();
                IdentityMessage             details = new IdentityMessage();
                Dictionary <string, string> param   = new Dictionary <string, string>();
                if (fc["message"] != null)
                {
                    message = fc["message"].ToString();
                    string fileName = "";
                    string oldpath  = Server.MapPath("~/SiteImages");
                    string filepath = Server.MapPath("~/SiteImages");
                    string dbpath   = "";

                    if (FileUpload != null)
                    {
                        fileName = Path.GetFileName(FileUpload.FileName);
                        //code to generate different name if the filename exists
                        string ImageName = await ShrdMaster.Instance.SaveImage(filepath, fileName);

                        // string ImageName =ShrdMaster.Instance.SaveImage(path, fileName);
                        //fileName = FileUpload.FileName;
                        filepath = Path.Combine(filepath, ImageName);
                        FileUpload.SaveAs(filepath);
                        string imagename1;
                        using (var srcImage = Image.FromFile(filepath))
                        {
                            var  newWidth  = (int)(150);
                            var  newHeight = (int)(150);
                            int  height    = srcImage.Height;
                            int  width     = srcImage.Width;
                            int  temp;
                            bool isHeightGreater = (height >= width);
                            int  percent         = 0;
                            if (isHeightGreater && height > 300)
                            {
                                newHeight = height - 300;
                                percent   = ((newHeight) / height) * 100;
                                newWidth  = (width - (width * (percent / 100)));
                            }
                            else if (width > 300)
                            {
                                newWidth = width - 300;
                                percent  = ((newWidth) / width) * 100;
                                temp     = (height * (percent / 100));
                                if (temp > 0)
                                {
                                    newHeight = (height - (height * (percent / 100)));
                                }
                            }

                            using (var newImage = new Bitmap(newWidth, newHeight))
                                using (var graphics = Graphics.FromImage(newImage))
                                {
                                    graphics.SmoothingMode     = SmoothingMode.AntiAlias;
                                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                    graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                                    graphics.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
                                    imagename1 = await ShrdMaster.Instance.SaveImage(oldpath, fileName);

                                    oldpath = Path.Combine(oldpath, imagename1);
                                    newImage.Save(oldpath);
                                }
                        }
                        try
                        {
                            System.IO.File.Delete(filepath);
                        }
                        catch
                        {
                        }
                        mailImagePath = oldpath;
                        dbpath        = "/SiteImages/" + imagename1;
                        //if (FileUpload.ContentLength >= 150000)
                        //{
                        //    ViewBag.error = "Image length is too large";
                        //    string opt = fc["option"].ToString();
                        //    if (opt == "1")
                        //    {
                        //        ViewBag.Layout = "~/Views/Student/_Layout.cshtml";
                        //        ViewBag.Option = 1;
                        //        return View();
                        //    }
                        //    else if (opt == "0")
                        //    {
                        //        ViewBag.Layout = "~/Views/Student/_AuthLayout.cshtml";
                        //        ViewBag.Option = 0;
                        //        return View();
                        //    }

                        //}


                        //product.ImageUrl = path;
                    }
                    else
                    {
                        if (student != null)
                        {
                            dbpath = student.image;
                        }
                        else
                        {
                            dbpath = null;
                        }
                    }



                    //param.Add("<%src%>",mailImagePath);


                    student.Message = message;
                    student.image   = dbpath;
                    db.SaveChanges();
                }
                //Email service
                param.Add("<%msg%>", message);
                param.Add("<%Name%>", student.FirstName + " " + student.LastName);
                param.Add("<%link%>", "fundraising.infodatixhosting.com/Customer/index/" + student.StudentID);
                if (!string.IsNullOrEmpty(mailImagePath))
                {
                    details.Subject = "Help " + student.FirstName + " raise money for " + org.Name + "<" + mailImagePath;
                }
                else
                {
                    details.Subject = "Help " + student.FirstName + " raise money for " + org.Name;
                }
                details.Destination = student.EmailAddress;

                details.Body = ShrdMaster.Instance.buildEmailBody("InviteEmailTemplate.txt", param);
                await email.SendAsync(details);

                return(RedirectToAction("Index", new { ID = student.StudentID }));
            }
            else
            {
                return(RedirectToAction("Login", "Account"));
            }


            return(RedirectToAction("Index", new { ID = student.StudentID }));
        }
示例#46
0
        public static async Task SendNotification(this Ticket ticket, Ticket oldTicket)
        {
            //make notification for being assigned to a new ticket

            var newAssignment = (ticket.AssignedToUserId != null && oldTicket.AssignedToUserId == null);
            var unAssignment  = (ticket.AssignedToUserId == null && oldTicket.AssignedToUserId == null);
            var reAssignment  = ((ticket.AssignedToUserId != null && oldTicket.AssignedToUserId != null) &&
                                 (ticket.AssignedToUserId != oldTicket.AssignedToUserId));



            var body = new StringBuilder();

            body.AppendFormat("<p>Email From: <bold>{0}</bold>({1})</p>", "Administrator", WebConfigurationManager.AppSettings["emailfrom"]);
            body.AppendLine("<br/><p><u><b>Message:</b></u></p>");
            body.AppendFormat("<p><b>Project Name:</b> {0}</p>", db.Projects.FirstOrDefault(p => p.Id == ticket.ProjectsId).Name);
            body.AppendFormat("<p><b>Ticket Title:</b> {0} | Id: {1}</p>", ticket.Title, ticket.Id);
            body.AppendFormat("<p><b>Ticket Created:</b> {0}</p>", ticket.Created);
            body.AppendFormat("<p><b>Ticket Type:</b> {0}</p>", db.TicketTypes.Find(ticket.TicketTypeId).Name);
            body.AppendFormat("<p><b>Ticket Status:</b>{0}</p>", db.TicketStatuses.Find(ticket.TicketStatusId).Name);
            body.AppendFormat("<p><b>Ticket Priority:</b> {0}</p>", db.TicketPriorities.Find(ticket.TicketPriorityId).Name);

            //make the email
            IdentityMessage email = null;

            if (newAssignment)
            {
                //create email content
                //Send a email to the new dev letting them know they have a new ticket (for when there was no dev on ticket before)
                email = new IdentityMessage()
                {
                    Subject     = "Bug Tracer: You have been assigned to a ticket!",
                    Body        = body.ToString(),
                    Destination = db.Users.Find(ticket.AssignedToUserId).Email
                };

                var svc = new EmailService();
                await svc.SendAsync(email);
            }
            else if (unAssignment)
            {
                //Send a email to the old dev letting them know they have been taken off the ticket
                email = new IdentityMessage()
                {
                    Subject     = "Bug Tracer: You have been taken off a ticket!",
                    Body        = body.ToString(),
                    Destination = db.Users.Find(oldTicket.AssignedToUserId).Email
                };

                var svc = new EmailService();
                await svc.SendAsync(email);
            }
            else if (reAssignment)
            {
                //Send a email to the new dev letting them know they have a new ticket (for when there was a dev on the ticket before)
                email = new IdentityMessage()
                {
                    Subject     = "Bug Tracer: You have been assigned to a ticket!",
                    Body        = body.ToString(),
                    Destination = db.Users.Find(ticket.AssignedToUserId).Email
                };

                var svc = new EmailService();
                await svc.SendAsync(email);

                //Send a email to the old dev letting them know they have been taken off the ticket
                email = new IdentityMessage()
                {
                    Subject     = "Bug Tracer: You have been taken off of a ticket!",
                    Body        = body.ToString(),
                    Destination = db.Users.Find(oldTicket.AssignedToUserId).Email
                };

                svc = new EmailService();
                await svc.SendAsync(email);
            }

            TicketNotification notification = null;

            if (newAssignment)
            {
                notification = new TicketNotification
                {
                    Body        = "Bug Tracer: A ticket has been assigned to you!",
                    RecipientId = ticket.AssignedToUserId,
                    TicketId    = ticket.Id
                };
                db.TicketNotifications.Add(notification);
            }
            else if (unAssignment)
            {
                notification = new TicketNotification
                {
                    Body        = "Bug Tracer: You have been taken off of a ticket!",
                    RecipientId = oldTicket.AssignedToUserId,
                    TicketId    = ticket.Id
                };
                db.TicketNotifications.Add(notification);
            }
            else if (reAssignment)
            {
                notification = new TicketNotification
                {
                    Body        = "Bug Tracer: A ticket has been assigned to you!",
                    RecipientId = ticket.AssignedToUserId,
                    TicketId    = ticket.Id
                };
                db.TicketNotifications.Add(notification);

                notification = new TicketNotification
                {
                    Body        = "Bug Tracer: You have been taken off of a ticket!",
                    RecipientId = oldTicket.AssignedToUserId,
                    TicketId    = ticket.Id
                };
                db.TicketNotifications.Add(notification);
            }
            db.SaveChanges();
        }
示例#47
0
 public EmailController(EmailService emailService)
 {
     this.emailServices = emailService;
 }
示例#48
0
 /// <summary>
 /// Останавливает все запущенные таймеры
 /// </summary>
 private void StopUpdateTimers()
 {
     EmailService.StopCheckingNewMessages(this.inputMessagesTimerId);
     EmailService.StopCheckingNewMessages(this.outputMessagesTimerId);
     EmailService.StopCheckingNewMessages(this.deletedMessagesTimerId);
 }
示例#49
0
        protected override void onBeforeSaving(Approval entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE)
        {
            var ctx = context as POContext;


            #region Validations
            User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.UserKey == LoggedUser.LocalUser.UserKey);
            if (currentUser == null)
            {
                throw new KnownError("Logged User not found or session expired.");
            }


            var pr = ctx.PurchaseRequests.AsNoTracking().Include(c => c.PRNumber)
                     .Include(e => e.DepartmentManager)
                     .FirstOrDefault(c => c.PurchaseRequestKey == entity.PurchaseRequestKey);


            if (pr == null)
            {
                throw new KnownError("PR document does not exist anymore.");
            }
            #endregion
            entity.UserApprover   = ctx.Users.FirstOrDefault(u => u.UserKey == entity.UserApproverKey);
            entity.UserRequisitor = ctx.Users.FirstOrDefault(u => u.UserKey == entity.UserRequisitorKey);


            if (mode == OPERATION_MODE.UPDATE)
            {
                Email emailEntity = new Email();
                emailEntity.CreatedAt = DateTimeOffset.Now;


                var hyperlink = entity.Hyperlink;


                EmailService emailService = new EmailService("secure.emailsrvr.com", 587)
                {
                    EmailAddress = currentUser.Email,
                    Password     = currentUser.EmailPassword,
                    From         = currentUser.Email,
                    Subject      = "PR - " + pr.PRNumber.GeneratedNumber + " [" + entity.Status + "] " + entity.Title,


                    Body = @"<div style='width: 90%;margin: auto;box-shadow: 1px 1px 8px #c3c3c3;border: 1px solid #d4d4d4;'>
    <div style='background: #006064;text-align: center;color: white;padding: 10px;'>
        <div style='font-size: 20px;font-family: sans-serif;'>PR System notification</div>
    </div>
    <div  style='padding:20px;'>
        <div style='font-size: 16px;margin-bottom: 10px; margin-left: 10px;font-family: sans-serif;'>
            <label>
                <b>User</b>
            </label>
            <br>
            <span>" + currentUser.Value + @"</span>
        </div>
        <div style='font-size: 16px;margin-bottom: 10px; margin-left: 10px;font-family: sans-serif;'>
            <label>
                <b>Status</b>
            </label>
            <br>
            <span>" + entity.Status + @"</span>
        </div>
        
        <div style='font-size: 16px;margin-bottom: 10px; margin-left: 10px;font-family: sans-serif;'>
            <label>
                <b>PR Friendly Identifier</b>
            </label>
            <br>
            <span> " + pr.FriendlyIdentifier + @"</span>
        </div>
    
        <div style='font-size: 16px;margin-bottom: 10px; margin-left: 10px;font-family: sans-serif;'>
            <label>
                <b>Request message</b>
            </label>
            <br>
            <span> " + entity.RequestDescription + @"</span>
        </div>

        <div style='font-size: 16px;margin-bottom: 10px;padding:10px;margin-left: 10px; color:#0075ed;border: none;border-radius: 5px;font-family: sans-serif;'>
            <a href=' " + hyperlink + @" ' style='text-decoration: none;font-size: 22px;'>
                Open document here
            </a>
        </div>
    </div>
</div>"
                };

                switch (entity.Status)
                {
                case "Pending":
                    emailService.To.Add(pr.DepartmentManager.Email);
                    emailService.To.Add(entity.UserApprover.Email);
                    break;

                case "MRO Quote":
                case "DM Quote":
                    emailService.To.Add(entity.UserRequisitor?.Email);
                    var mros = ctx.Users.Where(u => u.Role == "MRO").ToList();
                    foreach (var mro in mros)
                    {
                        emailService.To.Add(mro.Email);
                    }
                    break;

                case "Finance Quote":
                    emailService.To.Add(entity.UserRequisitor?.Email);
                    var finances = ctx.Users.Where(u => u.Role == "Finance").ToList();
                    foreach (var finance in finances)
                    {
                        emailService.To.Add(finance.Email);
                    }
                    break;

                case "DM Rejected":
                    emailService.To.Add(entity.UserRequisitor.Email);
                    break;

                case "GM Rejected":
                    emailService.To.Add(entity.UserRequisitor.Email);
                    break;

                case "MRO Quoted":
                    emailService.To.Add(pr.DepartmentManager.Email);
                    emailService.To.Add(entity.UserApprover.Email);
                    break;

                case "Quote Rejected":
                    var mrosRejected = ctx.Users.Where(u => u.Role == "MRO").ToList();
                    foreach (var mro in mrosRejected)
                    {
                        emailService.To.Add(mro.Email);
                    }
                    break;

                case "Approved":
                    emailService.To.Add(entity.UserRequisitor.Email);
                    var buyers = ctx.Users.Where(u => u.Role == "Buyer").ToList();
                    foreach (var buyer in buyers)
                    {
                        emailService.To.Add(buyer.Email);
                    }
                    break;

                case "Finalized":
                    emailService.To.Add(entity.UserRequisitor.Email);
                    emailService.To.Add(entity.UserApprover.Email);
                    break;

                default:
                    break;
                }

                try
                {
                    if (emailService.To.Count > 0)
                    {
                        emailService.SendMail();
                    }
                }
                catch (Exception ex)
                {
                    throw new KnownError("Could not send email, please verify your Profile settings.\n" + ex.Message);
                }
            }
        }
示例#50
0
 public ForgotPasswordModel(StorageService storage, EmailService email, EncryptionService encryption)
 {
     this.storage    = storage;
     this.email      = email;
     this.encryption = encryption;
 }
        public async Task Handle(EformCompleted message)
        {
            try
            {
                // Get settings
                var settings = await _dbContext.PluginConfigurationValues.ToListAsync();

                var sendGridKey = settings.FirstOrDefault(x =>
                                                          x.Name == nameof(MonitoringBaseSettings) + ":" + nameof(MonitoringBaseSettings.SendGridApiKey));
                if (sendGridKey == null)
                {
                    throw new Exception($"{nameof(MonitoringBaseSettings.SendGridApiKey)} not found in settings");
                }

                Log.LogEvent($"EFormCompletedHandler.Handle: sendGridKey is {sendGridKey.Value}");
                var fromEmailAddress = settings.FirstOrDefault(x =>
                                                               x.Name == nameof(MonitoringBaseSettings) + ":" + nameof(MonitoringBaseSettings.FromEmailAddress));
                if (fromEmailAddress == null)
                {
                    throw new Exception($"{nameof(MonitoringBaseSettings.FromEmailAddress)} not found in settings");
                }

                Log.LogEvent($"EFormCompletedHandler.Handle: fromEmailAddress is {fromEmailAddress.Value}");
                var fromEmailName = settings.FirstOrDefault(x =>
                                                            x.Name == nameof(MonitoringBaseSettings) + ":" + nameof(MonitoringBaseSettings.FromEmailName));
                if (fromEmailName == null)
                {
                    throw new Exception($"{nameof(MonitoringBaseSettings.FromEmailName)} not found in settings");
                }
                Log.LogEvent($"EFormCompletedHandler.Handle: fromEmailName is {fromEmailName.Value}");

                var emailService = new EmailService(sendGridKey.Value, fromEmailAddress.Value, fromEmailName.Value);

                // Get rules
                var caseId = await _sdkCore.CaseIdLookup(message.microtingUId, message.checkUId) ?? 0;

                var replyElement = await _sdkCore.CaseRead(message.microtingUId, message.checkUId);

                var checkListValue = (CheckListValue)replyElement.ElementList[0];
                var fields         = checkListValue.DataItemList
                                     .SelectMany(f => (f is FieldContainer fc) ? fc.DataItemList : new List <DataItem>()
                {
                    f
                })
                                     .ToList();

                var rules = await _dbContext.Rules
                            .Include(x => x.Recipients)
                            .Where(x => x.WorkflowState != Constants.WorkflowStates.Removed)
                            .Where(x => x.CheckListId == message.checkListId)
                            .ToListAsync();

                // Find trigger
                foreach (var rule in rules)
                {
                    var dataItemId = rule.DataItemId;
                    var field      = (Field)fields.FirstOrDefault(x => x.Id == dataItemId);

                    if (field != null)
                    {
                        // Check
                        var jsonSettings = new JsonSerializerSettings
                        {
                            NullValueHandling = NullValueHandling.Include
                        };
                        var sendEmail    = false;
                        var matchedValue = "";
                        switch (field.FieldType)
                        {
                        case "Number":
                            var numberBlock = JsonConvert.DeserializeObject <NumberBlock>(rule.Data, jsonSettings);

                            matchedValue = field.FieldValues[0].Value;
                            sendEmail    = false;
                            if (float.TryParse(field.FieldValues[0].Value, NumberStyles.Any,
                                               CultureInfo.InvariantCulture, out var numberVal))
                            {
                                if (numberBlock.GreaterThanValue != null &&
                                    numberVal > numberBlock.GreaterThanValue)
                                {
                                    Log.LogEvent(
                                        $"EFormCompletedHandler.Handle: numberVal is {fromEmailName.Value} and is greater than {numberBlock.GreaterThanValue}");
                                    sendEmail = true;
                                }

                                if (numberBlock.LessThanValue != null && numberVal < numberBlock.LessThanValue)
                                {
                                    Log.LogEvent(
                                        $"EFormCompletedHandler.Handle: numberVal is {fromEmailName.Value} and is less than {numberBlock.GreaterThanValue}");
                                    sendEmail = true;
                                }

                                if (numberBlock.EqualValue != null && numberVal.Equals((float)numberBlock.EqualValue))
                                {
                                    Log.LogEvent(
                                        $"EFormCompletedHandler.Handle: numberVal is {fromEmailName.Value} and is equal to {numberBlock.GreaterThanValue}");
                                    sendEmail = true;
                                }
                            }
                            break;

                        case "CheckBox":
                            var checkboxBlock = JsonConvert.DeserializeObject <CheckBoxBlock>(rule.Data, jsonSettings);
                            var isChecked     = field.FieldValues[0].Value == "1" || field.FieldValues[0].Value == "checked";
                            matchedValue = checkboxBlock.Selected ? "Checked" : "Not checked";
                            sendEmail    = isChecked == checkboxBlock.Selected;
                            break;

                        case "MultiSelect":
                        case "SingleSelect":
                            var selectBlock = JsonConvert.DeserializeObject <SelectBlock>(rule.Data, jsonSettings);
                            var selectKeys  = field.FieldValues[0].Value.Split('|');

                            matchedValue = field.FieldValues[0].ValueReadable;
                            sendEmail    = selectBlock.KeyValuePairList.Any(i => i.Selected && selectKeys.Contains(i.Key));
                            break;

                        case "EntitySearch":
                        case "EntitySelect":
                            var entityBlock = JsonConvert.DeserializeObject <SelectBlock>(rule.Data, jsonSettings);
                            var selectedId  = field.FieldValues[0].Value;

                            matchedValue = field.FieldValues[0].ValueReadable;
                            sendEmail    = entityBlock.KeyValuePairList.Any(i => i.Selected && selectedId == i.Key);
                            break;
                        }

                        // Send email
                        if (sendEmail)
                        {
                            Log.LogEvent($"EFormCompletedHandler.Handle: sendmail is true, so let's send an email");
                            var    assembly     = Assembly.GetExecutingAssembly();
                            var    assemblyName = assembly.GetName().Name;
                            var    stream       = assembly.GetManifestResourceStream($"{assemblyName}.Resources.Email.html");
                            string html;

                            using (var reader = new StreamReader(stream, Encoding.UTF8))
                            {
                                html = await reader.ReadToEndAsync();
                            }

                            html = html.Replace("{{label}}", field.Label)
                                   .Replace("{{description}}", field.Description.InderValue)
                                   .Replace("{{value}}", matchedValue)
                                   .Replace("{{link}}", $"{await _sdkCore.GetSdkSetting(Settings.httpServerAddress)}/cases/edit/{caseId}/{message.checkListId}")
                                   .Replace("{{text}}", rule.Text);

                            if (rule.AttachReport)
                            {
                                foreach (var recipient in rule.Recipients.Where(r => r.WorkflowState != Constants.WorkflowStates.Removed))
                                {
                                    try
                                    {
                                        // Fix for broken SDK not handling empty customXmlContent well
                                        string customXmlContent = new XElement("FillerElement",
                                                                               new XElement("InnerElement", "SomeValue")).ToString();

                                        // get report file
                                        var filePath = await _sdkCore.CaseToPdf(
                                            caseId,
                                            replyElement.Id.ToString(),
                                            DateTime.Now.ToString("yyyyMMddHHmmssffff"),
                                            $"{await _sdkCore.GetSdkSetting(Settings.httpServerAddress)}/" + "api/template-files/get-image/",
                                            "pdf",
                                            customXmlContent);

                                        if (!File.Exists(filePath))
                                        {
                                            throw new Exception("Error while creating report file");
                                        }

                                        await emailService.SendFileAsync(
                                            rule.Subject.IsNullOrEmpty()? "-" : rule.Subject,
                                            recipient.Email,
                                            filePath,
                                            html : html);
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine(e);
                                        await emailService.SendAsync(
                                            rule.Subject.IsNullOrEmpty()? "-" : rule.Subject,
                                            recipient.Email,
                                            html : html);
                                    }
                                }
                            }
                            else
                            {
                                foreach (var recipient in rule.Recipients)
                                {
                                    await emailService.SendAsync(
                                        rule.Subject.IsNullOrEmpty()? "-" : rule.Subject,
                                        recipient.Email,
                                        html : html);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
示例#52
0
        public FriendInvitationDTO InviteFriendOperation(InviteFriendOperationData data)
        {
            Log.WriteWarning("InviteFriendOperation:Username={0},Operation:{1},User:{2}", SecurityInfo.SessionData.Profile.UserName, data.Operation, data.User.UserName);

            if (SecurityInfo.SessionData.Profile.GlobalId == data.User.GlobalId)
            {
                throw new InvalidOperationException("You cannot add yourself as a friend");
            }
            var session = Session;

            FriendInvitation returnValue = null;

            using (var tx = session.BeginSaveTransaction())
            {
                var friendProfile = session.Get <Profile>(data.User.GlobalId);
                var inviter       = session.Get <Profile>(SecurityInfo.SessionData.Profile.GlobalId);

                if (friendProfile.IsDeleted)
                {
                    throw new UserDeletedException("Cannot invite a deleted profile");
                }
                if (data.Operation == Model.InviteFriendOperation.Invite)
                {
                    if (inviter.Friends.Contains(friendProfile))
                    {
                        throw new ProfileAlreadyFriendException("Specified profile is already a friend");
                    }
                    //check if user add invitation second time
                    var existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                    {
                        Inviter = inviter,
                        Invited = friendProfile
                    });
                    if (existingInvitation == null)
                    {
                        Log.WriteVerbose("1: existingInvitation == null");
                        existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                        {
                            Inviter = friendProfile,
                            Invited = inviter
                        });
                        if (existingInvitation == null)
                        {
                            Log.WriteVerbose("2: existingInvitation == null. Perform invite operation");
                            FriendInvitation invitation = new FriendInvitation();
                            invitation.Inviter        = inviter;
                            invitation.Invited        = friendProfile;
                            invitation.Message        = data.Message;
                            invitation.CreateDate     = Configuration.TimerService.UtcNow;
                            invitation.InvitationType = FriendInvitationType.Invite;
                            session.Save(invitation);
                            returnValue = invitation;

                            if ((friendProfile.Settings.NotificationSocial & ProfileNotification.Email) == ProfileNotification.Email)
                            {
                                EmailService.SendEMail(friendProfile, "InviteFriendEMailSubject", "InviteFriendEMailMessage", inviter.UserName, DateTime.Now, data.Message);
                            }
                        }
                        else
                        {
                            acceptInvitation(session, friendProfile, inviter, existingInvitation, data);
                        }
                    }
                }
                else if (data.Operation == Model.InviteFriendOperation.Accept)
                {
                    var existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                    {
                        Inviter = friendProfile,
                        Invited = inviter
                    });
                    if (existingInvitation != null)
                    {
                        acceptInvitation(session, friendProfile, inviter, existingInvitation, data);
                    }
                    else
                    {
                        throw new CannotAcceptRejectInvitationDoesntExistException("You are not invited to be a friend for specified user");
                    }
                }
                else
                {//reject
                    var existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                    {
                        Inviter = friendProfile,
                        Invited = inviter
                    });

                    if (existingInvitation != null)
                    {
                        Log.WriteVerbose("3: existingInvitation != null.");
                        if (existingInvitation.InvitationType == FriendInvitationType.Invite)
                        {
                            session.Delete(existingInvitation);

                            //messageService.SendSystemMessage(data.Message, inviter, friendProfile, MessageType.InvitationRejected);
                            //SendMessage(friendProfile.Settings.NotificationSocial, inviter, friendProfile, data.Message, MessageType.InvitationRejected
                            //, "RejectInvitationEmailSubject", "RejectInvitationEmailMessage", inviter.UserName, DateTime.Now, data.Message);
                            NewSendMessageEx(inviter.Settings.NotificationSocial, inviter, friendProfile, "RejectInvitationEmailSubject", "RejectInvitationEmailMessage", inviter.UserName, DateTime.Now, data.Message);
                        }
                        else
                        {
                            Log.WriteError("4:This should not be invoked.");
                        }
                    }
                    else if (inviter.Friends.Contains(friendProfile))
                    {
                        Log.WriteVerbose("Reject friendship");
                        inviter.Friends.Remove(friendProfile);
                        friendProfile.Friends.Remove(inviter);
                        ProfileStatisticsUpdater.UpdateFriends(session, inviter, friendProfile);
                        //SendMessage(friendProfile.Settings.NotificationSocial, inviter, friendProfile, data.Message, MessageType.FriendshipRejected
                        //    , "RejectFriendshipEmailSubject", "RejectFriendshipEmailMessage", inviter.UserName, DateTime.Now, data.Message);
                        NewSendMessageEx(inviter.Settings.NotificationSocial, inviter, friendProfile, "RejectFriendshipEmailSubject", "RejectFriendshipEmailMessage", inviter.UserName, DateTime.Now, data.Message);
                        //messageService.SendSystemMessage(data.Message, inviter, friendProfile, MessageType.FriendshipRejected);
                    }
                    else
                    {
                        existingInvitation = session.Get <FriendInvitation>(new FriendInvitation()
                        {
                            Inviter = inviter,
                            Invited = friendProfile
                        });
                        //user whats to cancel invitation
                        if (existingInvitation != null)
                        {
                            Log.WriteVerbose("Reject invitation");
                            session.Delete(existingInvitation);
                        }
                        else
                        {
                            throw new CannotAcceptRejectInvitationDoesntExistException("There is no invitation to reject");
                        }
                    }
                }


                tx.Commit();
                Log.WriteVerbose("Operation completed");
                if (returnValue != null)
                {
                    return(ObjectsConverter.ConvertFriendInvitation(inviter, returnValue));
                }
                return(null);
            }
        }
示例#53
0
        public async Task AddClaimFromUser(int projectId,
                                           int?characterGroupId,
                                           int?characterId,
                                           string claimText,
                                           IReadOnlyDictionary <int, string> fields)
        {
            var source = await ProjectRepository.GetClaimSource(projectId, characterGroupId, characterId);

            source.EnsureCanAddClaim(CurrentUserId);

            var responsibleMaster = source.GetResponsibleMasters().FirstOrDefault();
            var claim             = new Claim()
            {
                CharacterGroupId        = characterGroupId,
                CharacterId             = characterId,
                ProjectId               = projectId,
                PlayerUserId            = CurrentUserId,
                PlayerAcceptedDate      = Now,
                CreateDate              = Now,
                ClaimStatus             = Claim.Status.AddedByUser,
                ResponsibleMasterUserId = responsibleMaster?.UserId,
                ResponsibleMasterUser   = responsibleMaster,
                LastUpdateDateTime      = Now,
                CommentDiscussion       = new CommentDiscussion()
                {
                    CommentDiscussionId = -1, ProjectId = projectId
                },
            };

            if (!string.IsNullOrWhiteSpace(claimText))
            {
                claim.CommentDiscussion.Comments.Add(new Comment
                {
                    CommentDiscussionId = -1,
                    AuthorUserId        = CurrentUserId,
                    CommentText         = new CommentText {
                        Text = new MarkdownString(claimText)
                    },
                    CreatedAt         = Now,
                    IsCommentByPlayer = true,
                    IsVisibleToPlayer = true,
                    ProjectId         = projectId,
                    LastEditTime      = Now,
                    ExtraAction       = CommentExtraAction.NewClaim,
                });
            }

            UnitOfWork.GetDbSet <Claim>().Add(claim);

            var updatedFields = FieldSaveHelper.SaveCharacterFields(CurrentUserId, claim, fields, FieldDefaultValueGenerator);

            var claimEmail = await CreateClaimEmail <NewClaimEmail>(claim, claimText ?? "", s => s.ClaimStatusChange,
                                                                    CommentExtraAction.NewClaim);

            claimEmail.UpdatedFields = updatedFields;

            await UnitOfWork.SaveChangesAsync();

            await EmailService.Email(claimEmail);

            if (claim.Project.Details.AutoAcceptClaims)
            {
                var userId = claim.ResponsibleMasterUserId ?? claim.Project.ProjectAcls.First().UserId;
                StartImpersonate(userId);
                //TODO[Localize]
                await ApproveByMaster(projectId,
                                      claim.ClaimId,
                                      "Ваша заявка была принята автоматически");

                ResetImpersonation();
            }
        }
示例#54
0
    protected void Submit(object sender, EventArgs e)
    {
        CloudFuns obj    = new CloudFuns();
        int       docid  = obj.FetchMax("uploads", "uploadid");
        string    userid = Convert.ToString(Session["userid"]);

        string newname = "NA", encfilename = "", filePath = "", metaxml = "";
        string input = "", output = "", seckey = "", ext = "";

        long sizebytes = 0;

        int    dd    = DateTime.Now.Day;
        int    mm    = DateTime.Now.Month;
        int    yy    = DateTime.Now.Year;
        string today = dd + "-" + mm + "-" + yy;

        int    hr  = DateTime.Now.Hour;
        string now = hr + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second;

        try
        {
            if (filedocument.HasFile)
            {
                string filename = filedocument.FileName;
                ext      = System.IO.Path.GetExtension(filename);
                filePath = Server.MapPath("UserDocs/") + userid + "/";

                metaxml = docid + "_xml.xml";

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                newname = "doc" + docid + ext;

                //---------------------------------
                input       = filePath + "/" + newname;
                encfilename = "doc" + docid + "_enc" + ext;
                output      = filePath + "/" + encfilename;

                if (File.Exists(input))
                {
                    File.Delete(input);
                }
                // save file for encryption
                filedocument.SaveAs(input);

                // Calculate SHA Hash of the original document
                SHATracker track    = new SHATracker();
                string     shavalue = track.GetSHA1Hash(input);

                FileInfo f = new FileInfo(input);
                sizebytes = f.Length;

                // Generate Keys

                Random r = new Random();
                seckey = "SEC" + docid + "@" + r.Next(111, 999);

                string dockey = docid + newname + "|D@C_" + now.Replace(":", "");

                // read all bytes from uploaded file
                byte[] file = System.IO.File.ReadAllBytes(input);

                // reverse and store file bytes into another byte array
                int filelength = file.Length;

                int    index    = filelength - 1;
                byte[] rev_file = new byte[filelength];
                foreach (byte b in file)
                {
                    rev_file[index] = b;
                    index--;
                }

                // create a file from reversed bytes and store on local server
                string rev_file_path = filePath + "/rev_file" + docid + ext;

                try
                {
                    if (File.Exists(rev_file_path))
                    {
                        FileStream fs = new FileStream(rev_file_path, FileMode.Open, FileAccess.Read, FileShare.None);
                        fs.Close();
                        File.Delete(rev_file_path);
                    }
                }
                catch (Exception ex) { }

                File.WriteAllBytes(rev_file_path, rev_file);

                // encrypt the file

                if (File.Exists(output))
                {
                    File.Delete(output);
                }

                Cryptography cobj = new Cryptography();
                cobj.EncryptAES(rev_file_path, output, dockey);

                // Store data in DB
                ArrayList data = new ArrayList();
                data.Clear();
                data.Add(docid);
                data.Add(txttitle.Text);
                data.Add(sizebytes);
                data.Add(txtdesc.Text);
                data.Add(userid);
                data.Add(metaxml);
                data.Add(dockey);
                data.Add(seckey);
                data.Add(today);
                data.Add(now);
                data.Add(encfilename);


                ManageDocuments dobj = new ManageDocuments();

                if (dobj.NewDoc(data))
                {
                    // create metadata XML file and store on local server
                    DataSet dsxml = new DataSet();
                    dsxml.Tables.Add();

                    dsxml.Tables[0].Columns.Add();
                    dsxml.Tables[0].Columns[0].ColumnName = "dochash";
                    dsxml.Tables[0].Columns.Add();
                    dsxml.Tables[0].Columns[1].ColumnName = "uploaddt";
                    dsxml.Tables[0].Columns.Add();
                    dsxml.Tables[0].Columns[2].ColumnName = "uploadtime";
                    dsxml.Tables[0].Columns.Add();
                    dsxml.Tables[0].Columns[3].ColumnName = "docid";

                    dsxml.Tables[0].Rows.Add();
                    dsxml.Tables[0].Rows[0][0] = shavalue;
                    dsxml.Tables[0].Rows[0][1] = today;
                    dsxml.Tables[0].Rows[0][2] = now;
                    dsxml.Tables[0].Rows[0][3] = docid;

                    if (File.Exists(filePath + metaxml))
                    {
                        File.Delete(filePath + metaxml);
                    }

                    dsxml.WriteXml(filePath + metaxml);

                    // store file on storage and backup server
                    BackupHost info           = new BackupHost();
                    WebClient  oclient        = new WebClient();
                    byte[]     responseArray  = oclient.UploadFile("http://" + info.StorageHostName + ":" + info.StorageHostPort + "/Receiver.aspx?path=" + userid, "POST", output);
                    byte[]     responseArray1 = oclient.UploadFile("http://" + info.BackupHostName + ":" + info.BackupHostPort + "/Receiver.aspx?path=" + userid, "POST", output);



                    value = 1;

                    if (File.Exists(input))
                    {
                        File.Delete(input);
                    }

                    if (File.Exists(output))
                    {
                        File.Delete(output);
                    }

                    try
                    {
                        if (File.Exists(rev_file_path))
                        {
                            FileStream fs = null;
                            try
                            {
                                fs = new FileStream(rev_file_path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
                                fs.Close();
                            }
                            catch (Exception ex) { }
                            File.Delete(rev_file_path);
                        }
                    }
                    catch (Exception ex) { }


                    GetClientDetails dtl   = new GetClientDetails(userid);
                    string           name  = dtl.ClientName;
                    string           email = dtl.ClientEmailId;

                    EmailService mail = new EmailService();
                    mail.sendSecKey(email, seckey, name, txttitle.Text);

                    RecordUsage rec = new RecordUsage();
                    rec.record(userid, "upload");
                    rec.record(userid, "encryption");
                }
                else
                {
                    value = 0;
                }
            }
        }
        catch (Exception ex) { value = 0; }

        if (value == 1)
        {
            message = "File uploaded successfully..";
            title   = "Success Report";
        }
        else if (value == 0)
        {
            message = "Sorry.!! File upload failed.. Try again..";
            title   = "Failure Report";
        }

        string script = "window.onload = function(){ alert('";

        script += message;
        script += "')};";
        ClientScript.RegisterStartupScript(this.GetType(), title, script, true);
        ClearInputs(Page.Controls);
    }
示例#55
0
        public NewPatientRes AddNewPatient(int doctorId, NewPatientReq req)
        {
            var          result = new NewPatientRes();
            string       emeci  = GetLastEmeci(doctorId);
            MemoryStream draw   = null;

            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    var r = new Registro
                    {
                        Nombre          = req.Name,
                        Apellido        = req.LastName,
                        Telefono        = req.Phone,
                        Tipo            = "P",
                        Status          = "V",
                        FechaRegistro   = DateTime.Now.Date,
                        FechaExpiracion = DateTime.Now.AddMonths(1).Date,
                        Emails          = req.Emails,
                        clave           = req.Password,
                        Emeci           = emeci
                    };

                    Context.Registro.Add(r);
                    Context.SaveChanges();

                    var p = new Paciente
                    {
                        IdRegistro      = r.idRegistro,
                        Sexo            = req.Sex,
                        FechaNacimiento = DateTime.Parse(req.BirthDate),
                        NombreMadre     = req.MothersName,
                        NombrePadre     = req.FathersName,
                        AlergiaMedicina = req.Allergy
                    };

                    Context.Paciente.Add(p);
                    Context.SaveChanges();

                    draw = DrawDataInCard(emeci);

                    scope.Complete();
                    result.PatientId = p.idPaciente;
                }
            }
            catch (Exception ex)
            {
                Log.Write($"WebAPI.Services._Patient - AddNewPatient => ${ex.Message}");
            }

            if (result.PatientId.HasValue && draw != null)
            {
                var emailService = new EmailService(req.Emails);
                Task.Run(async() =>
                {
                    await emailService.SendPatientRegister(req, draw);
                });
            }

            return(result);
        }
        public ActionResult MemberRegisterLogic(RegisterViewModel userModel)
        {
            var forumReturnUrl = Settings.ForumRootUrl;
            var newMemberGroup = Settings.Group;

            if (userModel.ForumId != null && userModel.ForumId != Settings.ForumId)
            {
                var correctForum = Dialogue.Settings((int)userModel.ForumId);
                forumReturnUrl = correctForum.ForumRootUrl;
                newMemberGroup = correctForum.Group;
            }

            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Secondly see if the email is banned
                if (BannedEmailService.EmailIsBanned(userModel.Email))
                {
                    ModelState.AddModelError(string.Empty, Lang("Error.EmailIsBanned"));

                    if (userModel.LoginType != LoginType.Standard)
                    {
                        ShowMessage();
                        return(Redirect(Settings.RegisterUrl));
                    }
                    return(CurrentUmbracoPage());
                }

                var userToSave = AppHelpers.UmbMemberHelper().CreateRegistrationModel(DialogueConfiguration.Instance.MemberTypeAlias);
                userToSave.Username        = BannedWordService.SanitiseBannedWords(userModel.UserName);
                userToSave.Name            = userToSave.Username;
                userToSave.UsernameIsEmail = false;
                userToSave.Email           = userModel.Email;
                userToSave.Password        = userModel.Password;

                var homeRedirect = false;

                MembershipCreateStatus createStatus;
                AppHelpers.UmbMemberHelper().RegisterMember(userToSave, out createStatus, false);

                if (createStatus != MembershipCreateStatus.Success)
                {
                    ModelState.AddModelError(string.Empty, MemberService.ErrorCodeToString(createStatus));
                }
                else
                {
                    // Get the umbraco member
                    var umbracoMember = AppHelpers.UmbServices().MemberService.GetByUsername(userToSave.Username);

                    // Set the role/group they should be in
                    AppHelpers.UmbServices().MemberService.AssignRole(umbracoMember.Id, newMemberGroup.Name);

                    // See if this is a social login and we have their profile pic
                    if (!string.IsNullOrEmpty(userModel.SocialProfileImageUrl))
                    {
                        // We have an image url - Need to save it to their profile
                        var image = AppHelpers.GetImageFromExternalUrl(userModel.SocialProfileImageUrl);

                        // Upload folder path for member
                        var uploadFolderPath = MemberService.GetMemberUploadPath(umbracoMember.Id);

                        // Upload the file
                        var uploadResult = UploadedFileService.UploadFile(image, uploadFolderPath);

                        // Don't throw error if problem saving avatar, just don't save it.
                        if (uploadResult.UploadSuccessful)
                        {
                            umbracoMember.Properties[AppConstants.PropMemberAvatar].Value = string.Concat(VirtualPathUtility.ToAbsolute(AppConstants.UploadFolderPath), umbracoMember.Id, "/", uploadResult.UploadedFileName);
                        }
                    }

                    // Now check settings, see if users need to be manually authorised
                    // OR Does the user need to confirm their email
                    var manuallyAuthoriseMembers       = Settings.ManuallyAuthoriseNewMembers;
                    var memberEmailAuthorisationNeeded = Settings.NewMembersMustConfirmAccountsViaEmail;
                    if (manuallyAuthoriseMembers || memberEmailAuthorisationNeeded)
                    {
                        umbracoMember.IsApproved = false;
                    }

                    // Store access token for social media account in case we want to do anything with it
                    if (userModel.LoginType == LoginType.Facebook)
                    {
                        umbracoMember.Properties[AppConstants.PropMemberFacebookAccessToken].Value = userModel.UserAccessToken;
                    }
                    if (userModel.LoginType == LoginType.Google)
                    {
                        umbracoMember.Properties[AppConstants.PropMemberGoogleAccessToken].Value = userModel.UserAccessToken;
                    }

                    // Do a save on the member
                    AppHelpers.UmbServices().MemberService.Save(umbracoMember);

                    if (Settings.EmailAdminOnNewMemberSignup)
                    {
                        var sb = new StringBuilder();
                        sb.AppendFormat("<p>{0}</p>", string.Format(Lang("Members.NewMemberRegistered"), Settings.ForumName, Settings.ForumRootUrl));
                        sb.AppendFormat("<p>{0} - {1}</p>", userToSave.Username, userToSave.Email);
                        var email = new Email
                        {
                            EmailTo   = Settings.AdminEmailAddress,
                            EmailFrom = Settings.NotificationReplyEmailAddress,
                            NameTo    = Lang("Members.Admin"),
                            Subject   = Lang("Members.NewMemberSubject")
                        };
                        email.Body = EmailService.EmailTemplate(email.NameTo, sb.ToString());
                        EmailService.SendMail(email);
                    }

                    // Fire the activity Service
                    ActivityService.MemberJoined(MemberMapper.MapMember(umbracoMember));

                    var userMessage = new GenericMessageViewModel();

                    // Set the view bag message here
                    if (manuallyAuthoriseMembers)
                    {
                        userMessage.Message     = Lang("Members.NowRegisteredNeedApproval");
                        userMessage.MessageType = GenericMessages.Success;
                    }
                    else if (memberEmailAuthorisationNeeded)
                    {
                        userMessage.Message     = Lang("Members.MemberEmailAuthorisationNeeded");
                        userMessage.MessageType = GenericMessages.Success;
                    }
                    else
                    {
                        // If not manually authorise then log the user in
                        FormsAuthentication.SetAuthCookie(userToSave.Username, true);
                        userMessage.Message     = Lang("Members.NowRegistered");
                        userMessage.MessageType = GenericMessages.Success;
                    }

                    //Show the message
                    ShowMessage(userMessage);

                    if (!manuallyAuthoriseMembers && !memberEmailAuthorisationNeeded)
                    {
                        homeRedirect = true;
                    }

                    try
                    {
                        unitOfWork.Commit();

                        // Only send the email if the admin is not manually authorising emails or it's pointless
                        EmailService.SendEmailConfirmationEmail(umbracoMember, Settings);

                        if (homeRedirect && !string.IsNullOrEmpty(forumReturnUrl))
                        {
                            if (Url.IsLocalUrl(userModel.ReturnUrl) && userModel.ReturnUrl.Length >= 1 && userModel.ReturnUrl.StartsWith("/") &&
                                !userModel.ReturnUrl.StartsWith("//") && !userModel.ReturnUrl.StartsWith("/\\"))
                            {
                                return(Redirect(userModel.ReturnUrl));
                            }
                            return(Redirect(forumReturnUrl));
                        }
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        AppHelpers.LogError("Eror during member registering", ex);
                        FormsAuthentication.SignOut();
                        ModelState.AddModelError(string.Empty, ex.Message);
                    }
                }
                if (userModel.LoginType != LoginType.Standard)
                {
                    return(Redirect(Settings.RegisterUrl));
                }
                return(CurrentUmbracoPage());
            }
        }
示例#57
0
 public void SetUp()
 {
     service = new EmailService();
 }
        public void Post()
        {
            string body = "";

            try
            {
                using (StreamReader sr = new StreamReader(Request.Body))
                    body = sr.ReadToEnd();

                Message msg = Message.ParseMessage(body);
                if (String.IsNullOrWhiteSpace(msg?.Signature))
                {
                    dynamic m = JsonConvert.DeserializeObject(body);
                    if (m.notificationType != null && m.notificationType == "AmazonSnsSubscriptionSucceeded")
                    {
                        return;
                    }
                }
                if (msg.IsMessageSignatureValid())
                {
                    if (msg.IsSubscriptionType)
                    {
                        HttpClient client = new HttpClient();
                        _ = client.GetAsync(msg.SubscribeURL).Result;
                        return;
                    }
                    if (msg.IsNotificationType)
                    {
                        dynamic m    = JsonConvert.DeserializeObject(msg.MessageText);
                        dynamic mail = m.mail;
                        if (m.notificationType == "Bounce")
                        {
                            dynamic b = m.bounce;
                            //if (b.bounceSubType != "General" && b.bounceSubType != "Suppressed" && b.bounceSubType != "MailboxFull")
                            //{
                            //    EmailService.SendEmail(new[] { Settings.BounceReporting, Settings.ErrorReporting }, Settings.DefaultFrom, "SES Non-General Bounce", body, false);
                            //    goto END;
                            //}
                            foreach (dynamic recipient in b.bouncedRecipients)
                            {
                                string bounceBody    = "<p>Following are the details of the email bounce. Ensure this email exists or remove it from the system that sent the email.</p>";
                                string bouncedEmails = "";
                                foreach (dynamic em in b.bouncedRecipients)
                                {
                                    if (bouncedEmails.Length > 0)
                                    {
                                        bouncedEmails += "," + (string)em.emailAddress;
                                    }
                                    else
                                    {
                                        bouncedEmails = (string)em.emailAddress;
                                    }
                                }
                                bounceBody += $"<p><strong>Email(s):</strong> {bouncedEmails}</p>";
                                bounceBody += $"<p><strong>Bounce Type:</strong> {b.bounceType}*</p>";
                                bounceBody += $"<p><strong>Bounce Sub Type:</strong> {b.bounceSubType}*</p>";
                                bounceBody += $"<p><strong>Original Subject:</strong> {(string)mail.commonHeaders.subject}</p>";
                                bounceBody += $"<p><strong>Date Sent:</strong> {(string)mail.commonHeaders.date}</p>";
                                bounceBody += "<p>* <strong>Transient</strong> means temporary issue. This email address should be verified. This could indicate a full inbox or vacation mode.<br />";
                                bounceBody += "* <strong>Permanent</strong> means this email address does not exist. Remove this address from the system that sent it. Contact [email protected] if you need assistance.</p>";
                                bounceBody += "<h2 style='margin-top:30px;'>Headers</h2><ul>";

                                foreach (dynamic h in mail.headers)
                                {
                                    bounceBody += $"<li><strong>{h.name}:</strong> {h.value}</li>";
                                }

                                bounceBody += "</ul>";

                                EmailService.SendEmail(new[] { Settings.BounceReporting }, Settings.DefaultFrom, "Bounce From example.com", bounceBody);
                                EmailService.SendEmail(new[] { Settings.ErrorReporting }, Settings.DefaultFrom, "SES example.com Bounce", bounceBody);
                                return;
                            }
                        }
                        else if (m.notificationType == "Complaint")
                        {
                            try
                            {
                                dynamic c = m.complaint;

                                string complaintBody    = "<p>Following are the details of the email complaint. <span style='font-weight:bold;color:#f00;'>Automatic action is not available at this time.</span> Please take the appropriate action (eg - disable email, reach out to customer, etc).</p>";
                                string complainedEmails = "";
                                foreach (dynamic em in c.complainedRecipients)
                                {
                                    if (complainedEmails.Length > 0)
                                    {
                                        complainedEmails += "," + (string)em.emailAddress;
                                    }
                                    else
                                    {
                                        complainedEmails = (string)em.emailAddress;
                                    }
                                }
                                complaintBody += $"<p><strong>Complaint Type:</strong> {c.complaintFeedbackType}</p>";
                                complaintBody += $"<p><strong>Email(s):</strong> {complainedEmails}</p>";
                                complaintBody += $"<p><strong>Original Subject:</strong> {(string)mail.commonHeaders.subject}</p>";
                                complaintBody += $"<p><strong>Date Sent:</strong> {(string)mail.commonHeaders.date}</p>";

                                complaintBody += "<h2 style='margin-top:30px;'>Headers</h2><ul>";

                                foreach (dynamic h in mail.headers)
                                {
                                    complaintBody += $"<li><strong>{h.name}:</strong> {h.value}</li>";
                                }

                                complaintBody += "</ul>";


                                EmailService.SendEmail(new[] { Settings.BounceReporting }, Settings.DefaultFrom, "Email Complaint Notification", complaintBody);
                                EmailService.SendEmail(new[] { Settings.ErrorReporting }, Settings.DefaultFrom, "Complaint Notification", complaintBody);
                            }
                            catch (Exception ex)
                            {
                                EmailService.SendEmail(new[] { Settings.ErrorReporting }, Settings.DefaultFrom, "SES Complaint Processing Error", ExcDetails.Get(ex), false);
                                EmailService.SendEmail(new[] { Settings.ErrorReporting }, Settings.DefaultFrom, "SES Complaint Body for Error", body, false);
                            }
                        }
                        else
                        {
                            EmailService.SendEmail(new[] { Settings.ErrorReporting }, Settings.DefaultFrom, "SES Non-Bounce Notification", body, false);
                        }
                    }
                    else
                    {
                        EmailService.SendEmail(new[] { Settings.ErrorReporting }, Settings.DefaultFrom, "SES Non-NotificationType", body, false);
                    }
                }
            }
            catch (Exception ex)
            {
                EmailService.SendEmail(new[] { Settings.ErrorReporting }, Settings.DefaultFrom, "SES Bounce Processing Error", ExcDetails.Get(ex), false);
                if (!String.IsNullOrWhiteSpace(body))
                {
                    EmailService.SendEmail(new[] { Settings.ErrorReporting }, Settings.DefaultFrom, "SES Bounce Body for Error", body, false);
                }
            }
        }
示例#59
0
        public async Task <IActionResult> AskLocation([FromBody] LocationViewModel model)
        {
            var token = GetToken();

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (!TokenService.ValidateToken(token) || !TokenService.VerifDateExpiration(token))
            {
                return(Unauthorized());
            }


            AuthService service = new AuthService(_context);
            User        user    = service.GetUserConnected(token);

            if (UserAlreadyHaveALocation(model, user))
            {
                ModelState.AddModelError("Error", "Il existe déjà une location enregistrée à votre nom durant cette période.");
                return(BadRequest(ModelState));
            }
            Location location = new Location();

            // information commentaire
            Comments comment = new Comments();

            comment.CommentDate   = DateTime.Now;
            comment.CommentText   = model.Comments;
            comment.CommentUserId = user.UserId;

            // information location
            location.LocDatestartlocation = Convert.ToDateTime(model.DateDebutResa.ToString("yyyy-MM-dd"));
            location.LocDateendlocation   = Convert.ToDateTime(model.DateFinResa.ToString("yyyy-MM-dd"));
            location.LocPoleIdstart       = model.PoleIdDepart;
            location.LocPoleIdend         = model.PoleIdDestination;
            location.LocUserId            = user.UserId;
            location.LocState             = Convert.ToSByte(Enums.LocationState.Asked);

            try
            {
                // un commentaire a besoin d'être d'abord rattacher a une location
                _context.Location.Add(location);
                await _context.SaveChangesAsync();

                comment.CommentLocId = location.LocId;
                _context.Comments.Add(comment);
                await _context.SaveChangesAsync();

                PoleService servicePole = new PoleService(_context);
                var         poleDepart  = servicePole.GetPole(location.LocPoleIdstart).PoleName;
                var         poleArrive  = servicePole.GetPole(location.LocPoleIdend).PoleName;
                string      myFiles     = System.IO.File.ReadAllText(ConstantsEmail.LocationAsk);

                myFiles = myFiles.Replace("%%USERNAME%%", user.UserFirstname);
                myFiles = myFiles.Replace("%%DEBUTLOCATION%%", location.LocDatestartlocation.ToString("dd/MM/yyyy"));
                myFiles = myFiles.Replace("%%FINLOCATION%%", location.LocDateendlocation.ToString("dd/MM/yyyy"));
                myFiles = myFiles.Replace("%%DEPARTPOLE%%", poleDepart);
                myFiles = myFiles.Replace("%%FINPOLE%%", poleArrive);
                var response = await EmailService.SendEmailAsync("Vous venez de demander une Location - BookYourCar", myFiles, user.UserEmail);

                if (response.IsSuccessStatusCode)
                {
                    return(Ok());
                }
                else
                {
                    ModelState.AddModelError("Error",
                                             "Une erreur s'est produite sur l'envoi de mail de confirmation mais la validation de la réservation a bien été prise en compte.");
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                ModelState.AddModelError("Error", "Une erreur est survenue lors de votre demande de location.");
                return(BadRequest(ModelState));
            }
        }
示例#60
0
        public async Task <ActionResult> PlaceOrder(Cart cart, OrderDTO order, string paymentMethod)
        {
            if (cart.LineCollection.Count == 0)
            {
                TempData["EmptyMessage"] = "true";
                return(RedirectToAction("index", "cart"));
            }

            // Add paymentMethod
            var addMethodResult = _orderRepo.AddPaymentMethod(order, paymentMethod);

            // Add orderStatus
            var addOrderStatusResult = _orderRepo.UpdateStatus(order, OrderStatusNames.Pending);

            // Check model valid
            if (!ModelState.IsValid || addMethodResult == null || addOrderStatusResult == null)
            {
                var model = new CheckoutViewModel()
                {
                    Order        = order,
                    OrderDetails = GetOrderDetails(cart)
                };
                return(View("index", model));
            }

            // Add userId if authenticated
            if (User.Identity.IsAuthenticated)
            {
                order.UserId = User.Identity.GetUserId();
            }

            // Get order details and calulate summary
            var orderDetails = GetOrderDetails(cart, false);

            order.SubTotal = cart.Summary;



            // Save order to repository
            var result = _orderRepo.Save(order, orderDetails);

            if (result == null)
            {
                TempData["OrderSuccess"] = "false";
                return(RedirectToAction("index", "cart"));
            }

            // Send mail
            var callbackUrl = Url.Action("index", "tracking", new { id = result.Id }, protocol: Request.Url.Scheme);
            var body        = MailHelper.CreateSuccessPlacingOrderEmailBody(ControllerContext, callbackUrl, result.Id);
            var message     = new IdentityMessage
            {
                Subject     = $"Order {result.Id}",
                Destination = result.Email,
                Body        = body
            };
            var emailService = new EmailService();
            await emailService.SendAsync(message);

            TempData["OrderSuccess"] = "true";
            cart.LineCollection.Clear();

            return(RedirectToAction("index", "tracking", new { id = result.Id }));
        }