コード例 #1
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    string confirmationToken =
                        WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email }, true);
                    Roles.AddUserToRole(model.UserName, "User");
                    dynamic email = new Postal.Email("RegEmail");
                    email.To                = model.Email;
                    email.UserName          = model.UserName;
                    email.ConfirmationToken = confirmationToken;
                    email.Send();

                    return(RedirectToAction("RegisterStepTwo", "Account"));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #2
0
ファイル: EmailModel.cs プロジェクト: pavithra91/JWConvention
        public void SendInquiry(EmailModel _email, string TemplateName)
        {
            dynamic email = new Postal.Email(TemplateName);

            email.To   = _email.EmailTo;
            email.From = "*****@*****.**";// _email.From;

            if (_email.EmailCC != null)
            {
                email.Cc = _email.EmailCC;
            }

            if (_email.EmailBCC != null)
            {
                email.Bcc = _email.EmailBCC;
            }

            email.FullName  = _email.FullName;
            email.ContactNo = _email.ContactNo;
            email.Message   = _email.Message;
            email.TourName  = _email.TourName;
            email.Email     = _email.ClientEmail;

            email.Send();
        }
コード例 #3
0
        /// <summary>
        /// CareManager verifies here.
        /// </summary>
        /// <param name="verificationCode"></param>
        /// <returns></returns>
        public async Task <ActionResult> Verify(string verificationCode)
        {
            var row = db.EmailVerifications.FirstOrDefault(v => v.VerificationCode == verificationCode);

            if (row == null)
            {
                Flash("無効なURLです。");
                return(RedirectToAction("Index", "Home"));
            }
            if (row.CareManager.User != null)
            {
                Flash("そのケアマネは既に認証されています。");
                return(RedirectToAction("Index", "Home"));
            }

            // Generates username and password.
            var username = string.Format("CM{0:D6}", row.CareManagerId);
            var password = Helper.PasswordHelper.GeneratePassword(12);

            // Registers CareHomeUser.
            var user = new User()
            {
                UserName = username, Email = row.Email, Name = row.CareManager.Name
            };
            var result = await UserManager.CreateAsync(user, password);

            if (!result.Succeeded)
            {
                throw new Exception("会員を登録できませんでした。");
            }

            var registeredUser = db.Users.FirstOrDefault(u => u.UserName == username);

            if (registeredUser == null)
            {
                throw new Exception("登録されたはずの会員が見つかりませんでした。");
            }

            // Notifies Sender.
            Flash("ケアマネ会員として認証されました。IDとパスワードを電子メールアドレスにお送りいたしましたのでご確認ください。");
            //SendEmail(registeredUser.Email, "[ケアマネ情報局] ケアマネ会員として認証されました", string.Format("ID:{0} password:{1}", username, password));
            dynamic email = new Postal.Email("EmailVerified");

            email.To              = registeredUser.Email;
            email.CareHomeName    = row.CareManager.CareHome.Name;
            email.CareManagerName = row.CareManager.Name;
            email.UserId          = username;
            email.Password        = password;
            email.SiteUrl         = string.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority);
            email.Send();

            // Adds CareManager and deletes EmailVerification.
            registeredUser.CareManager.Add(row.CareManager);
            db.EmailVerifications.Remove(row);
            db.SaveChanges();
            Log(LogType.CareManager, "ケアマネ会員としてメール認証しました。", new { row.Email, row.CareManagerId });

            return(RedirectToAction("Index", "Home"));
        }
コード例 #4
0
        public async Task <ActionResult> ApproveConfirmed(int id, string noteForSender)
        {
            var application = db.Applications.Find(id);

            if (application == null)
            {
                return(HttpNotFound());
            }

            if (application.CareHome.User != null)
            {
                throw new InvalidOperationException("該当する事業所会員は既に登録されています。");
            }

            // Generates username and password.
            var username = "******" + application.CareHome.CareHomeCode;
            var password = Helper.PasswordHelper.GeneratePassword(12);

            // Registers CareHomeUser.
            var user = new User()
            {
                UserName = username, Email = application.Email, Name = application.Name
            };
            var result = await UserManager.CreateAsync(user, password);

            if (!result.Succeeded)
            {
                throw new Exception("会員を登録できませんでした。");
            }

            var registeredUser = db.Users.FirstOrDefault(u => u.UserName == username);

            if (registeredUser == null)
            {
                throw new Exception("登録されたはずの会員が見つかりませんでした。");
            }

            // Notifies Sender.
            //SendEmail(registeredUser.Email, "[ケアマネ情報局] 事業所会員として承認されました", string.Format("ID:{0} password:{1} 備考:{2}", username, password, noteForSender));
            dynamic email = new Postal.Email("ApplicationApproved");

            email.To               = registeredUser.Email;
            email.CareHomeName     = application.CareHome.Name;
            email.CareHomeUserName = application.Name;
            email.UserId           = username;
            email.Password         = password;
            email.SiteUrl          = string.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority);
            email.Note             = noteForSender;
            email.Send();

            // Adds CareHome and deletes Application.
            registeredUser.CareHomes.Add(application.CareHome);
            db.Applications.Remove(application);
            db.SaveChanges();

            Flash(string.Format("承認されました。ID:{0}", username));
            Log(LogType.Admin, "事業所会員登録申請を承認しました。");
            return(RedirectToAction("Index"));
        }
コード例 #5
0
        public SendEmailResponse SendEmail(Postal.Email email, ILogger log)
        {
            var output = new SendEmailResponse();

#if !DEBUG
            try
            {
#endif
            // Process email with Postal
            var emailService = ServiceLocator.Current.GetInstance <Postal.IEmailService>();
            using (var message = emailService.CreateMailMessage(email))
            {
                var htmlView = message.AlternateViews.FirstOrDefault(x => x.ContentType.MediaType.ToLower() == "text/html");
                if (htmlView != null)
                {
                    string body = new StreamReader(htmlView.ContentStream).ReadToEnd();

                    // move ink styles inline with PreMailer.Net
                    var result = PreMailer.Net.PreMailer.MoveCssInline(body, false, "#ignore");

                    htmlView.ContentStream.SetLength(0);
                    var streamWriter = new StreamWriter(htmlView.ContentStream);

                    streamWriter.Write(result.Html);
                    streamWriter.Flush();

                    htmlView.ContentStream.Position = 0;
                }

                // send email with default smtp client. (the same way as Postal)
                using (var smtpClient = new SmtpClient())
                {
                    try
                    {
                        smtpClient.Send(message);
                        output.Success = true;
                    }
                    catch (SmtpException exception)
                    {
                        _logger.Error("Exception: {0}, inner message {1}", exception.Message, (exception.InnerException != null) ? exception.InnerException.Message : string.Empty);
                        output.Success   = false;
                        output.Exception = exception;
                    }
                }
            }

#if !DEBUG
        }

        catch (Exception ex)
        {
            _logger.Error("Error sending email", ex);
            output.Exception = ex;
        }
#endif
            return(output);
        }
コード例 #6
0
        public ActionResult SendTestEmail()
        {
            dynamic email = new Postal.Email("Test");

            email.To      = "*****@*****.**";
            email.Message = "How do you feel to day. Sent at " + DateTime.Now.ToString();
            email.Send();
            return(RedirectToAction("Index"));
        }
コード例 #7
0
        private bool Send(Postal.Email emailMessage)
        {
            var result = _emailDispatcher.SendEmail(emailMessage, Log);

            if (result.Success)
            {
                return(true);
            }
            Log.Error(result.Exception.Message, result.Exception);
            return(false);
        }
コード例 #8
0
        public ActionResult EmailTest()
        {
            //SendEmailToAdmin("Hi", "Hello");
            dynamic email = new Postal.Email("Example");

            email.To        = "*****@*****.**";
            email.FunnyLink = "http://example.com/";
            email.Send();

            return(null);
        }
コード例 #9
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName       = model.Email,
                    Email          = model.Email,
                    RegisterDate   = DateTime.Now,
                    RegisterIP     = Request.GetVisitorIP(),
                    LastAccessDate = DateTime.Now,
                    LastAccessIP   = Request.GetVisitorIP()
                };

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    // Send an email with this link
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                    var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "signup").SelectAsync();

                    var emailTemplate = emailTemplateQuery.FirstOrDefault();

                    if (emailTemplate != null)
                    {
                        dynamic email = new Postal.Email("Email");
                        email.To          = CacheHelper.Settings.EmailContact;
                        email.From        = CacheHelper.Settings.EmailContact;
                        email.Subject     = emailTemplate.Subject;
                        email.Body        = emailTemplate.Body;
                        email.CallbackUrl = callbackUrl;
                        EmailHelper.SendEmail(email);
                    }

                    return(RedirectToAction("Index", "Manage"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #10
0
 private bool AttemptSendOf(Postal.Email emailMessage)
 {
     try
     {
         return(Send(emailMessage));
     }
     catch (Exception ex)
     {
         Log.Error("Error occured when sending ResetPassword emailMessage.", ex);
         return(false);
     }
 }
コード例 #11
0
        public dynamic ComposeForwardToFriendEmail(string friendname, string friendemailaddress, string message, int id)
        {
            dynamic email = new Postal.Email("SendtoFriend/Multipart");
            var unitposter = UserHelper.GetPoster(id, HttpContext.Request.Url) ?? UserHelper.PosterHelper.DefaultPoster;
            var currentunit = UnitofWork.UnitRepository.FirstOrDefault(x => x.UnitId == id);
            const string previewPathWithHost = @"/Unit/Preview";
            var unitPicture = currentunit.PrimaryPhoto;
            unitPicture = unitPicture.Replace("../../", "");
            //../../Photo/Owner/Property/carrie/2/img_walle - Copy.jpg

            // Assign any view data to pass to the view.
            // It's dynamic, so you can put whatever you want here.

            email.To = friendemailaddress;
            email.FriendName = friendname;
            email.From = "*****@*****.**";
            email.SenderFirstName = unitposter.FirstName;
            email.Title = string.Format("Request From {0}", unitposter.FirstName);
            email.Message = message;
            var uri = Request.Url;
            if (uri != null)
            {
                var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
                var unitUrl = host + previewPathWithHost + id;
                email.UnitUrl = unitUrl;

                string title;
                if (String.IsNullOrEmpty(currentunit.Title))
                {
                    title = (currentunit.Address + " , " + currentunit.State + " , " + currentunit.City);
                    if (title.Length >= 50)
                    {
                        title = title.Substring(0, 50);
                    }
                }
                else
                {
                    title = currentunit.Title;
                    if (currentunit.Title.Length >= 50)
                    {
                        title = currentunit.Title.Substring(0, 50);
                    }
                }

                email.UnitTitle = title;
                // email.UnitPath = "http://www.haithem-araissia.com/images/property/home12.jpg";
                email.UnitPath = host + "/" + unitPicture;
            }
            return email;
        }
コード例 #12
0
        public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(View("ForgotPasswordConfirmation"));
                }

                // Check if email confirm required
                if (CacheHelper.Settings.EmailConfirmedRequired && !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    return(View("ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");

                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "forgotpassword").SelectAsync();

                var emailTemplate = emailTemplateQuery.Single();

                dynamic email = new Postal.Email("Email");
                email.To          = CacheHelper.Settings.EmailContact;
                email.From        = CacheHelper.Settings.EmailContact;
                email.Subject     = emailTemplate.Subject;
                email.Body        = emailTemplate.Body;
                email.CallbackUrl = callbackUrl;
                EmailHelper.SendEmail(email);

                return(RedirectToAction("ForgotPasswordConfirmation", "Account"));
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #13
0
        public async Task <ActionResult> ContactUser(ContactUserModel model)
        {
            var listing = await _listingService.FindAsync(model.ListingID);

            var userIdCurrent = User.Identity.GetUserId();
            var user          = userIdCurrent.User();

            // Check if user send message to itself, which is not allowed
            if (listing.UserID == userIdCurrent)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[You cannot send message to yourself!]]]";
                return(RedirectToAction("Listing", "Listing", new { id = model.ListingID }));
            }

            // Send message to user
            var message = new MessageSendModel()
            {
                UserFrom  = userIdCurrent,
                UserTo    = listing.UserID,
                Subject   = listing.Title,
                Body      = model.Message,
                ListingID = listing.ID
            };

            await MessageHelper.SendMessage(message);

            // Send email with notification
            var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "privatemessage").SelectAsync();

            var emailTemplate = emailTemplateQuery.Single();

            dynamic email = new Postal.Email("Email");

            email.To      = user.Email;
            email.From    = CacheHelper.Settings.EmailAddress;
            email.Subject = emailTemplate.Subject;
            email.Body    = emailTemplate.Body;
            email.Message = model.Message;
            EmailHelper.SendEmail(email);

            TempData[TempDataKeys.UserMessage] = "[[[Message sent succesfully!]]]";

            return(RedirectToAction("Listing", "Listing", new { id = model.ListingID }));
        }
コード例 #14
0
        public async Task <ActionResult> ContactUser(ContactUserModel model)
        {
            var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "privatemessage").SelectAsync();

            var emailTemplate = emailTemplateQuery.Single();

            dynamic email = new Postal.Email("Email");

            email.To      = CacheHelper.Settings.EmailContact;
            email.From    = CacheHelper.Settings.EmailContact;
            email.Subject = emailTemplate.Subject;
            email.Body    = emailTemplate.Body;
            email.Message = model.Message;
            EmailHelper.SendEmail(email);

            TempData[TempDataKeys.UserMessage] = "[[[Message sent succesfully!]]]";

            return(RedirectToAction("Listing", "Listing", new { id = model.ListingID }));
        }
コード例 #15
0
        public async Task <IActionResult> SendEmail2()
        {
            var requestPath = new Postal.RequestPath();

            requestPath.PathBase = Request.PathBase.ToString();
            requestPath.Host     = Request.Host.ToString();
            requestPath.IsHttps  = Request.IsHttps;
            requestPath.Scheme   = Request.Scheme;
            requestPath.Method   = Request.Method;

            var emailData = new Postal.Email("~/Views/AnotherFolder/Testing2.cshtml");

            emailData.RequestPath      = requestPath;
            emailData.ViewData["to"]   = "*****@*****.**";
            emailData.ViewData["Name"] = "Sam";

            await _emailSender.SendEmailAsync(emailData);

            return(View());
        }
コード例 #16
0
ファイル: MailingService.cs プロジェクト: Horndev/zapread.com
        private static string renderEmail(Postal.Email email, string baseUriString = "https://www.zapread.com/")
        {
            var    emailViewRenderer = getRenderer();
            string HTMLString        = emailViewRenderer.Render(email);

            // premailer cleanup
            PreMailer.Net.InlineResult result;
            var baseUri = new Uri(baseUriString);

            result = PreMailer.Net.PreMailer.MoveCssInline(
                baseUri: baseUri,
                html: HTMLString,
                removeComments: true,
                removeStyleElements: true,
                stripIdAndClassAttributes: true
                );

            var cleanHTMLString = result.Html;

            return(cleanHTMLString);
        }
コード例 #17
0
ファイル: EmailModel.cs プロジェクト: pavithra91/JWConvention
        public void SendError(EmailModel _email, string TemplateName)
        {
            dynamic email = new Postal.Email(TemplateName);

            email.To   = _email.EmailTo;
            email.From = "*****@*****.**";// _email.From;

            if (_email.EmailCC != null)
            {
                email.Cc = _email.EmailCC;
            }

            if (_email.EmailBCC != null)
            {
                email.Bcc = _email.EmailBCC;
            }

            email.ErrorMessage = _email.ErrorMessage;

            email.Send();
        }
コード例 #18
0
        public async Task <ActionResult> EmailTemplateTest(int id)
        {
            var emailTemplate = await _emailTemplateService.FindAsync(id);

            if (emailTemplate == null)
            {
                return(new HttpNotFoundResult());
            }

            dynamic email = new Postal.Email("Email");

            email.To      = CacheHelper.Settings.EmailContact;
            email.From    = CacheHelper.Settings.EmailAddress;
            email.Subject = "[[[Testing]]] - " + emailTemplate.Subject;
            email.Body    = emailTemplate.Body;

            EmailHelper.SendEmail(email);

            TempData[TempDataKeys.UserMessage] = string.Format("[[[Message sent to {0} succesfully!]]]", CacheHelper.Settings.EmailContact);

            return(RedirectToAction("EmailTemplateUpdate", new { id = id }));
        }
コード例 #19
0
ファイル: EmailModel.cs プロジェクト: pavithra91/JWConvention
        public void SendEmail(EmailModel _email, string TemplateName)
        {
            dynamic email = new Postal.Email(TemplateName);

            email.To   = _email.ClientEmail;
            email.From = _email.From;

            if (_email.EmailBCC != null)
            {
                email.Cc = _email.EmailCC;
            }
            if (_email.EmailCC != null)
            {
                email.Bcc = _email.EmailBCC;
            }

            email.HotelName    = _email.HotelName;
            email.RoomCategory = _email.RoomCategory;
            email.CheckIn      = _email.CheckIn;
            email.CheckOut     = _email.CheckOut;

            if (_email.PackageType != null)
            {
                email.Package = _email.PackageType;
            }

            email.InvoiceNo     = _email.BookingRef;
            email.InvoiceAmount = _email.InvoiceAmount;
            email.BookingRef    = _email.BookingRef;
            email.Amount        = _email.Amount;
            email.ClientEmail   = _email.ClientEmail;
            email.ClientName    = _email.ClientName;
            email.DateofPayment = _email.DateofPayment.ToShortDateString();

            email.Send();
        }
コード例 #20
0
 /// <summary>
 /// Send email in new thread
 /// </summary>
 /// <param name="to">to</param>
 /// <param name="username">username</param>
 /// <param name="subject">subject</param>
 /// <param name="body">body</param>
 /// <param name="confirmationToken">confirmationToken</param>
 /// <param name="template">template</param>
 /// <param name="hostUrl">hostUrl</param>
 private static void SendEmailInBackground(string to, string username, string subject, string body, string confirmationToken, EmailTemplate template, string hostUrl)
 {
     try
     {
         dynamic email = new Postal.Email(template.ToString());
         email.To   = to;
         email.From = new System.Net.Mail.MailAddress("*****@*****.**", "צוות תמיכה של TeachMe");
         if (!string.IsNullOrEmpty(subject))
         {
             email.Subject = subject;
         }
         if (!string.IsNullOrEmpty(body))
         {
             email.Body = body;
         }
         email.UserName          = username;
         email.ConfirmationToken = confirmationToken;
         email.HostUrl           = hostUrl;
         email.Send();
     }
     catch (System.Exception)
     {
     }
 }
コード例 #21
0
        public async Task <ActionResult> PropertyOrder(Model.Models.Order order)
        {
            var listing = await _listingService.FindAsync(order.ListingID);

            var ordersListing = await _orderService.Query(x => x.ListingID == order.ListingID).SelectAsync();

            if (order.FromDate == order.ToDate)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[You cant book just to one day, minimun two day.]]]";

                return(RedirectToAction("Listing", "Manage", new { id = order.ListingID }));
            }

            if (listing == null)
            {
                return(new HttpNotFoundResult());
            }

            // Redirect if not authenticated
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Login", "Account", new { ReturnUrl = Url.Action("Listing", "Manage", new { id = order.ListingID }) }));
            }

            var userCurrent = User.Identity.User();

            //validar que los dias no esten reservados
            List <DateTime> FechasCocinadas = new List <DateTime>();

            for (DateTime date = order.FromDate.Value; date <= order.ToDate.Value; date = date.Date.AddDays(1))
            {
                FechasCocinadas.Add(date);
            }
            foreach (Model.Models.Order ordenesArrendadas in ordersListing.Where(x => x.Status != (int)Enum_OrderStatus.Cancelled))
            {
                for (DateTime date = ordenesArrendadas.FromDate.Value; date < ordenesArrendadas.ToDate.Value; date = date.Date.AddDays(1))
                {
                    if (FechasCocinadas.Contains(date))
                    {
                        TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                        TempData[TempDataKeys.UserMessage]           = "[[[You can not book with these selected dates!]]]";
                        return(RedirectToAction("Listing", "Manage", new { id = listing.ID }));
                    }
                }
            }

            // Check if payment method is setup on user or the platform
            var descriptors = _pluginFinder.GetPluginDescriptors <IHookPlugin>(LoadPluginsMode.InstalledOnly, "Payment").Where(x => x.Enabled);

            if (descriptors.Count() == 0)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[The provider has not setup the payment option yet, please contact the provider.]]]";

                return(RedirectToAction("Listing", "Manage", new { id = order.ListingID }));
            }



            if (order.ID == 0)
            {
                order.ObjectState   = Repository.Pattern.Infrastructure.ObjectState.Added;
                order.Created       = DateTime.Now;
                order.Modified      = DateTime.Now;
                order.Status        = (int)Enum_OrderStatus.Pending;
                order.UserProvider  = listing.UserID;
                order.UserReceiver  = userCurrent.Id;
                order.ListingTypeID = order.ListingTypeID;
                order.Currency      = listing.Currency;
                order.OrderType     = 2;
                if (order.ToDate.HasValue && order.FromDate.HasValue)
                {
                    order.Description = HttpContext.ParseAndTranslate(
                        string.Format("{0} #{1} ([[[From]]] {2} [[[To]]] {3})",
                                      listing.Title,
                                      listing.ID,
                                      order.FromDate.Value.ToShortDateString(),
                                      order.ToDate.Value.ToShortDateString()));

                    order.Quantity = order.ToDate.Value.Date.AddDays(1).Subtract(order.FromDate.Value.Date).Days;
                    order.Price    = 0;
                }
                else if (order.Quantity.HasValue)
                {
                    order.Description = string.Format("{0} #{1}", listing.Title, listing.ID);
                    order.Quantity    = order.Quantity.Value;
                    order.Price       = 0;
                }
                else
                {
                    // Default
                    order.Description = string.Format("{0} #{1}", listing.Title, listing.ID);
                    order.Quantity    = 1;
                    order.Price       = 0;
                }
                _orderService.Insert(order);
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            //Envio de correo a propietario
            var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "bloqueopropietario").SelectAsync();

            var emailTemplate = emailTemplateQuery.Single();

            dynamic email = new Postal.Email("Email");

            email.To       = userCurrent.Email;
            email.From     = CacheHelper.Settings.EmailAddress;
            email.Subject  = emailTemplate.Subject;
            email.Body     = emailTemplate.Body;
            email.Id       = order.ListingID;
            email.Name     = userCurrent.FullName;
            email.FromDate = order.FromDate.Value.ToShortDateString();
            email.ToDate   = order.ToDate.Value.ToShortDateString();
            EmailHelper.SendEmail(email);

            ClearCache();
            TempData[TempDataKeys.UserMessage] = string.Format("[[[Has bloqueado correctamenter tu propiedad entre las fechas {0} y {1}]]]", order.FromDate.Value.ToString("dd-MM-yyyy"), order.ToDate.Value.ToString("dd-MM-yyyy"));
            return(RedirectToAction("Listing", "Manage", new { id = listing.ID }));
        }
コード例 #22
0
        public void SendRequestToRequester(string requestername, string requesteremailaddress,string datepicker, int id)
        {
            dynamic email = new Postal.Email("RequestShowing/Sender/Multipart");
            var currentunit = UnitofWork.UnitRepository.FirstOrDefault(x=>x.UnitId == id);
            const string previewPathWithHost = @"/Unit/Preview";
            var unitPicture = currentunit.PrimaryPhoto;
            unitPicture = unitPicture.Replace("../../", "");

            email.To = requesteremailaddress;
            email.RequesterName = requestername;
            email.From = "*****@*****.**";

            email.Title = string.Format("Confirmation of Request From {0}", requestername);

            email.ScheduleDate = datepicker;
            email.LinkConfirmation = "Confirmation to Poster Schedule Pending";
            UnitProperty(id, previewPathWithHost, email, currentunit, unitPicture);

            try
            {
                email.SendAsync();

            }
            catch (Exception)
            {
                //Write To Database Error
                //Output Message
                Response.Write("Fail");
                throw;
            }
        }
コード例 #23
0
ファイル: HomeController.cs プロジェクト: gastono/LaCommerce
        public ActionResult Contact(ContactModel model)
        {
            ViewBag.Message = "Your contact page.";

             

            if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Message))
            {               

                dynamic email = new Postal.Email("Email");
                email.To = "*****@*****.**";
                email.From = model.Email;
                email.Subject = "Consulta-"+ model.Email;
                email.Body = model.Message;

                EmailHelper.SendEmail(email);

                TempData[TempDataKeys.UserMessage] = string.Format("[[[Mensaje enviado a {0} exitosamente!]]]", "Administrador");

                return RedirectToAction("Contact");
            }

          

            return View(model);



        }
コード例 #24
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email = model.Email,
                    RegisterDate = DateTime.Now,
                    RegisterIP = Request.GetVisitorIP(),
                    LastAccessDate = DateTime.Now,
                    LastAccessIP = Request.GetVisitorIP()
                };

                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    // Send an email with this link
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                    var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "signup").SelectAsync();
                    var emailTemplate = emailTemplateQuery.FirstOrDefault();

                    if (emailTemplate != null)
                    {
                        dynamic email = new Postal.Email("Email");
                        email.To = CacheHelper.Settings.EmailContact;
                        email.From = CacheHelper.Settings.EmailContact;
                        email.Subject = emailTemplate.Subject;
                        email.Body = emailTemplate.Body;
                        email.CallbackUrl = callbackUrl;
                        EmailHelper.SendEmail(email);
                    }

                    return RedirectToAction("Index", "Manage");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
コード例 #25
0
 public SendEmailResponse SendEmail(Postal.Email email)
 {
     return(SendEmail(email, _logger));
 }
コード例 #26
0
        public async Task<ActionResult> ContactUser(ContactUserModel model)
        {
            var listing = await _listingService.FindAsync(model.ListingID);

            var userIdCurrent = User.Identity.GetUserId();
            var user = userIdCurrent.User();
            
            // Check if user send message to itself, which is not allowed
            if (listing.UserID == userIdCurrent)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage] = "[[[You cannot send message to yourself!]]]";
                return RedirectToAction("Listing", "Listing", new { id = model.ListingID });
            }

            // Send message to user
            var message = new MessageSendModel()
            {
                UserFrom = userIdCurrent,
                UserTo = listing.UserID,
                Subject = listing.Title,
                Body = model.Message,
                ListingID = listing.ID
            };

            await MessageHelper.SendMessage(message);

            // Send email with notification
            var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "privatemessage").SelectAsync();
            var emailTemplate = emailTemplateQuery.Single();

            dynamic email = new Postal.Email("Email");
            email.To = user.Email;
            email.From = CacheHelper.Settings.EmailAddress;
            email.Subject = emailTemplate.Subject;
            email.Body = emailTemplate.Body;
            email.Message = model.Message;
            EmailHelper.SendEmail(email);

            TempData[TempDataKeys.UserMessage] = "[[[Message sent succesfully!]]]";

            return RedirectToAction("Listing", "Listing", new { id = model.ListingID });
        }
コード例 #27
0
        //[HttpPost]
        //[AllowAnonymous]
        //public async Task<ActionResult> ConfirmarPago(Order order)
        //{
        //    var listing = await _listingService.FindAsync(order.ListingID);
        //    var ordersListing = await _orderService.Query(x => x.ListingID == order.ListingID).SelectAsync();
        //    var userCurrent = User.Identity.User();

        //    order.OrderType = 3;


        //    _orderService.Insert(order);

        //    await _unitOfWorkAsync.SaveChangesAsync();

        //    ClearCache();

        //    ClearCache();
        //    TempData[TempDataKeys.UserMessage] = "[[[You booked your stay correctly!]]]";
        //    return RedirectToAction("Listing", "Listing", new { id = listing.ID });

        //}

        public async Task <ActionResult> EnviarCorreo(ConfirmOrder model, string correoPropietario)
        {
            var user = await UserManager.FindByNameAsync(model.Email);

            //Aqui enviamos el correo al pasajero
            #region Correo Pasajero
            var administrator      = _aspNetUserService.Query(x => x.AspNetRoles.Any(y => y.Name.Equals("Administrator"))).Select().FirstOrDefault();
            var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "confirmorder").SelectAsync();

            var emailTemplate = emailTemplateQuery.Single();

            if (emailTemplate != null)
            {
                dynamic email = new Postal.Email("Email");
                email.To               = user.Email;
                email.From             = CacheHelper.Settings.EmailAddress;
                email.Subject          = emailTemplate.Subject;
                email.Body             = emailTemplate.Body;
                email.Id               = model.Id;
                email.Name             = model.Name;
                email.FromDate         = model.FromDate;
                email.ToDate           = model.ToDate;
                email.Adults           = model.Adults;
                email.Children         = model.Children;
                email.Rent             = model.Rent;
                email.Service          = model.Service;
                email.CleanlinessPrice = model.CleanlinessPrice;
                email.Total            = model.Rent + model.CleanlinessPrice + model.Service;
                email.ShortDescription = model.ShortDescription;
                email.Description      = model.Description;
                email.Condominium      = model.Condominium;
                email.TypeOfProperty   = model.TypeOfProperty;
                email.Capacity         = model.Capacity;
                email.Rooms            = model.Rooms;
                email.Beds             = model.Beds;
                email.SuiteRooms       = model.SuiteRooms;
                email.Bathrooms        = model.Bathrooms;
                email.Dishwasher       = model.Dishwasher;
                email.Washer           = model.Washer;
                email.Grill            = model.Grill;
                email.TvCable          = model.TvCable;
                email.Wifi             = model.Wifi;
                email.Elevator         = model.Elevator;
                email.FloorNumber      = model.FloorNumber;
                email.Stay             = model.Stay;
                email.ConditionHouse   = model.ConditionHouse;
                EmailHelper.SendEmail(email);
            }
            #endregion

            //Con esto se envia el correo a la administracion y a PM
            #region Correo PM y Admin
            var emailorderquery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "blockedproperty").SelectAsync();

            var templateorder = emailorderquery.Single();
            var admin         = await _aspNetUserService.Query(x => x.AspNetRoles.Any(z => z.Name == "Administrator")).SelectAsync();

            dynamic emailorder = new Postal.Email("Email");
            foreach (var administradores in admin)
            {
                emailorder.To       = administradores.Email;
                emailorder.From     = CacheHelper.Settings.EmailAddress;
                emailorder.Subject  = templateorder.Subject;
                emailorder.Body     = templateorder.Body;
                emailorder.Name     = administradores.FullName;
                emailorder.FromDate = model.FromDate;
                emailorder.ToDate   = model.ToDate;
                emailorder.Id       = model.Id;
                EmailHelper.SendEmail(emailorder);
            }
            #endregion

            //Aqui enviamos el correo y sms al propietario
            #region Correo Propietario
            var emailOwnerQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "emailowner").SelectAsync();

            var emailOwner  = emailOwnerQuery.Single();
            var propietario = _aspNetUserService.Query(x => x.Email.Equals(correoPropietario)).Select().FirstOrDefault();
            var order       = _orderService.Query(x => x.ID == model.OrderId).Select().FirstOrDefault();
            var propiedad   = await _listingService.FindAsync(order.ListingID);

            dynamic ownermail = new Postal.Email("Email");
            ownermail.To         = propietario.Email;
            ownermail.From       = CacheHelper.Settings.EmailAddress;
            ownermail.Subject    = emailOwner.Subject;
            ownermail.Body       = emailOwner.Body;
            ownermail.Name       = propietario.FullName;
            ownermail.FromDate   = model.FromDate;
            ownermail.ToDate     = model.ToDate;
            ownermail.Tarifa     = propiedad.Price;
            ownermail.Total      = order.Price;
            ownermail.Passengers = order.Adults + order.Children;
            ownermail.Id         = model.Id;
            EmailHelper.SendEmail(ownermail);
            //if(prop.PhoneNumberConfirmed)
            SMSHelper.SendSMS(propietario.PhoneNumber, string.Format("Estimado {0} hemos recibido una reserva por su propiedad desde {1} hasta {2} Mayores detalles en su correo", propietario.FullName, model.FromDate, model.ToDate));
            #endregion
            return(RedirectToAction("Payment", "Payment", new { id = model.Id }));
        }
コード例 #28
0
        public async Task <ActionResult> OrderActionNew(int id, int status)
        {
            var order = await _orderService.FindAsync(id);

            order.Status   = status;
            order.Modified = DateTime.Now;
            _orderService.Update(order);

            await _unitOfWorkAsync.SaveChangesAsync();

            var pasajero    = _aspNetUserService.Query(x => x.Id == order.UserReceiver).Select().FirstOrDefault();
            var propietario = _aspNetUserService.Query(x => x.Id == order.UserProvider).Select().FirstOrDefault();
            var propiedad   = await _listingService.FindAsync(order.ListingID);

            var camas = _detailBedService.Query(x => x.ListingID == order.ListingID)
                        .Include(x => x.TypeOfBed).Select().ToList();

            string htmlcamas = "<br><table>";

            htmlcamas += "<tr><th>Cantidad</th><th>Plaza</th><tr>";
            foreach (var cama in camas)
            {
                htmlcamas += "<tr>";
                htmlcamas += " <th>" + cama.Quantity + "</th>";
                htmlcamas += " <th>" + cama.TypeOfBed.Name + "</th>";
                htmlcamas += "</tr>";
            }
            htmlcamas = htmlcamas + " </table> <br>";

            if (status == 4)
            {
                //Email a Pasajero
                var finishorderquery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "finishorder").SelectAsync();

                var     templatefinishorder = finishorderquery.Single();
                dynamic emailordenpagada    = new Postal.Email("Email");
                emailordenpagada.To      = pasajero.Email;
                emailordenpagada.From    = CacheHelper.Settings.EmailAddress;
                emailordenpagada.Subject = templatefinishorder.Subject;
                emailordenpagada.Body    = templatefinishorder.Body;
                emailordenpagada.Name    = pasajero.FullName;
                emailordenpagada.OT      = order.OT;
                emailordenpagada.Camas   = htmlcamas;
                EmailHelper.SendEmail(emailordenpagada);

                //Email y telefono a Propietario
                var emailorderquery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "payorder").SelectAsync();

                var templateorder = emailorderquery.Single();

                var servicio = order.Price * 0.04;

                dynamic emailorderpropietario = new Postal.Email("Email");
                emailorderpropietario.To       = propietario.Email;
                emailorderpropietario.From     = CacheHelper.Settings.EmailAddress;
                emailorderpropietario.Subject  = templateorder.Subject;
                emailorderpropietario.Body     = templateorder.Body;
                emailorderpropietario.FromDate = order.FromDate.Value.ToShortDateString();
                emailorderpropietario.ToDate   = order.ToDate.Value.ToShortDateString();
                emailorderpropietario.Id       = order.ListingID;
                emailorderpropietario.Tarifa   = propiedad.Price;
                emailorderpropietario.Total    = order.Price;
                emailorderpropietario.OT       = order.OT;
                emailorderpropietario.Abono    = order.Percent;
                EmailHelper.SendEmail(emailorderpropietario);

                //if (propietario.PhoneNumberConfirmed)
                SMSHelper.SendSMS(propietario.PhoneNumber, string.Format("La reserva ha sido confirmada exitosamente. La OT Asociada es la numero {0} Mayores detalles en su correo.", order.OT));
            }

            var result = new
            {
                Success = true,
                Message = "Hola"
            };

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
コード例 #29
0
        public SendEmailResponse SendEmail(Postal.Email email, ILogger log)
        {
            var output = new SendEmailResponse();
            // We need the full host to fix links in the email
            Uri host = GetHostUrl();

            _logger.Log(Level.Debug, "Sending email with using base uri: {0}", host.ToString());

#if !DEBUG
            try
            {
#endif
            // Process email with Postal
            var emailService = ServiceLocator.Current.GetInstance <Postal.IEmailService>();
            using (var message = emailService.CreateMailMessage(email))
            {
                var htmlView = message.AlternateViews.FirstOrDefault(x => x.ContentType.MediaType.ToLower() == "text/html");
                if (htmlView != null)
                {
                    string body = new StreamReader(htmlView.ContentStream).ReadToEnd();

                    // move ink styles inline and fix urls with PreMailer.Net
                    var result = PreMailer.Net.PreMailer.MoveCssInline(host, body, false, "#ignore");

                    // Fix image resources and links in html content
                    string html = AddHostToUrls(result.Html, host);

                    htmlView.BaseUri = host;
                    // Explicit encoding, or we might get utf-16 and mail clients that interpret it as Chinese
                    htmlView.ContentType.CharSet = Encoding.UTF8.WebName;
                    htmlView.ContentStream.SetLength(0);

                    var streamWriter = new StreamWriter(htmlView.ContentStream);

                    streamWriter.Write(html);
                    streamWriter.Flush();

                    htmlView.ContentStream.Position = 0;
                }

                message.IsBodyHtml   = true;
                message.BodyEncoding = Encoding.UTF8;

                // send email with default smtp client. (the same way as Postal)
                using (var smtpClient = new SmtpClient())
                {
                    try
                    {
                        smtpClient.Send(message);
                        output.Success = true;
                    }
                    catch (SmtpException exception)
                    {
                        _logger.Error("Exception: {0}, inner message {1}", exception.Message, (exception.InnerException != null) ? exception.InnerException.Message : string.Empty);
                        output.Success   = false;
                        output.Exception = exception;
                    }
                }
            }

#if !DEBUG
        }

        catch (Exception ex)
        {
            _logger.Error("Error sending email", ex);
            output.Exception = ex;
        }
#endif
            return(output);
        }
コード例 #30
0
 public dynamic ProviderPublicComposeForwardToFriendEmail(string friendname, string friendemailaddress, string message, int id)
 {
     dynamic email = new Postal.Email("ForwardtoFriend/Multipart");
     var poster = UserHelper.GetSendtoFriendPoster(HttpContext.Request.Url) ?? UserHelper.PosterHelper.DefaultPoster;
     email.To = friendemailaddress;
     email.FriendName = friendname;
     email.From = "*****@*****.**";
     email.SenderFirstName = poster.FirstName;
     email.Title = string.Format("Request From {0}", poster.FirstName);
     email.SubTitle = "Request from ";
     email.Message = message;
     email.InvitationNote = " invite you to see this skilled provider.";
     email.FooterNote = "Check out this Provider";
     var uri = Request.Url;
     if (uri != null)
     {
         var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
         email.ProfileUrl = host + uri.AbsolutePath.Replace("ForwardtoFriend", "");
         var currentProvider = UserHelper.GetPublicProfileProviderByProviderId(id);
         if (currentProvider != null)
         {
             var specialistTitle = currentProvider.FirstName + " , " + currentProvider.LastName;
             if (specialistTitle.Length >= 50)
             {
                 specialistTitle = specialistTitle.Substring(0, 50);
             }
             email.CustomTitle = specialistTitle;
         }
         if (currentProvider != null)
         {
             email.PhotoPath = host + "/" + GetProviderPrimaryWorkPhoto(id).Replace("../../", "");
         }
     }
     return email;
 }
コード例 #31
0
        public static SendEmailResponse SendEmail(Postal.Email email)
        {
            var log = LogManager.GetLogger();

            return(SendEmail(email, log));
        }
コード例 #32
0
        public async Task <ActionResult> ListingUpdate(Listing listing, FormCollection form, IEnumerable <HttpPostedFileBase> files, int[] idcama, int[] cantidad)
        {
            if (CacheHelper.Categories.Count == 0)
            {
                TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                TempData[TempDataKeys.UserMessage]           = "[[[There are not categories available yet.]]]";

                return(RedirectToAction("Listing", new { id = listing.ID }));
            }
            var userIdCurrent = User.Identity.GetUserId();

            // Register account if not login
            if (!User.Identity.IsAuthenticated)
            {
                var accountController = BeYourMarket.Core.ContainerManager.GetConfiguredContainer().Resolve <AccountController>();

                var modelRegister = new RegisterViewModel()
                {
                    Email           = listing.ContactEmail,
                    Password        = form["Password"],
                    ConfirmPassword = form["ConfirmPassword"],
                };

                // Parse first and last name
                var names = listing.ContactName.Split(' ');
                if (names.Length == 1)
                {
                    modelRegister.FirstName = names[0];
                }
                else if (names.Length == 2)
                {
                    modelRegister.FirstName = names[0];
                    modelRegister.LastName  = names[1];
                }
                else if (names.Length > 2)
                {
                    modelRegister.FirstName = names[0];
                    modelRegister.LastName  = listing.ContactName.Substring(listing.ContactName.IndexOf(" ") + 1);
                }

                // Register account
                var resultRegister = await accountController.RegisterAccount(modelRegister);

                // Add errors
                AddErrors(resultRegister);

                // Show errors if not succeed
                if (!resultRegister.Succeeded)
                {
                    var model = new ListingUpdateModel()
                    {
                        ListingItem = listing
                    };
                    // Populate model with listing
                    await PopulateListingUpdateModel(listing, model);

                    return(View("ListingUpdate", model));
                }

                // update current user id
                var user = await UserManager.FindByNameAsync(listing.ContactEmail);

                userIdCurrent = user.Id;
            }

            bool updateCount = false;

            int nextPictureOrderId = 0;

            // Set default listing type ID
            if (listing.ListingTypeID == 0)
            {
                var listingTypes = CacheHelper.ListingTypes.Where(x => x.CategoryListingTypes.Any(y => y.CategoryID == listing.CategoryID));

                if (listingTypes == null)
                {
                    TempData[TempDataKeys.UserMessageAlertState] = "bg-danger";
                    TempData[TempDataKeys.UserMessage]           = "[[[There are not listing types available yet.]]]";

                    return(RedirectToAction("Listing", new { id = listing.ID }));
                }

                listing.ListingTypeID = listingTypes.FirstOrDefault().ID;
            }

            if (listing.ID == 0)
            {
                listing.Title       = listing.ID.ToString();
                listing.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added;
                listing.IP          = Request.GetVisitorIP();
                listing.Expiration  = DateTime.MaxValue.AddDays(-1);
                listing.UserID      = userIdCurrent;
                listing.Enabled     = true;
                listing.Active      = false;
                listing.Currency    = CacheHelper.Settings.Currency;
                listing.Children    = !listing.Children;
                updateCount         = true;
                _listingService.Insert(listing);
            }
            else
            {
                if (await NotMeListing(listing.ID))
                {
                    return(new HttpUnauthorizedResult());
                }

                var listingExisting = await _listingService.FindAsync(listing.ID);

                listingExisting.Title       = listing.ID.ToString();
                listingExisting.Description = listing.Description;
                listingExisting.Price       = listing.Price;

                listingExisting.ContactEmail = listing.ContactEmail;
                listingExisting.ContactName  = listing.ContactName;
                listingExisting.ContactPhone = listing.ContactPhone;

                listingExisting.Latitude  = listing.Latitude;
                listingExisting.Longitude = listing.Longitude;
                listingExisting.Location  = listing.Location;

                listingExisting.ShowPhone = listing.ShowPhone;
                listingExisting.ShowEmail = listing.ShowEmail;

                listingExisting.CategoryID    = listing.CategoryID;
                listingExisting.ListingTypeID = listing.ListingTypeID;



                //nuevos campos
                listingExisting.Bathrooms = listing.Bathrooms;
                listingExisting.Beds      = listing.Beds;
                listingExisting.Cellar    = listing.Cellar;
                listingExisting.Children  = !listing.Children;
                //listingExisting.CleanlinessPrice = listing.CleanlinessPrice;
                listingExisting.ConditionCheckOut = listing.ConditionCheckOut;
                listingExisting.ConditionHouse    = listing.ConditionHouse;
                //listingExisting.DescribeCondominium = listing.DescribeCondominium;
                listingExisting.Description      = listing.Description;
                listingExisting.Dishwasher       = listing.Dishwasher;
                listingExisting.Elevator         = listing.Elevator;
                listingExisting.FirstLine        = listing.FirstLine;
                listingExisting.FloorNumber      = listing.FloorNumber;
                listingExisting.Grill            = listing.Grill;
                listingExisting.M2               = listing.M2;
                listingExisting.Max_Capacity     = listing.Max_Capacity;
                listingExisting.NroOfParking     = listing.NroOfParking;
                listingExisting.ParkingLot       = listing.ParkingLot;
                listingExisting.Pets             = listing.Pets;
                listingExisting.Rooms            = listing.Rooms;
                listingExisting.SafetyMesh       = listing.SafetyMesh;
                listingExisting.ShortDescription = listing.ShortDescription;
                listingExisting.Smoker           = listing.Smoker;
                listingExisting.Stay             = listing.Stay;
                listingExisting.Suite            = listing.Suite;
                listingExisting.Terrace          = listing.Terrace;
                listingExisting.Tv               = listing.Tv;
                listingExisting.TV_cable         = listing.TV_cable;
                listingExisting.TypeOfProperty   = listing.TypeOfProperty;
                //listingExisting.Warranty = listing.Warranty;
                listingExisting.Washer = listing.Washer;
                listingExisting.Wifi   = listing.Wifi;

                listingExisting.ObjectState = Repository.Pattern.Infrastructure.ObjectState.Modified;
                _listingService.Update(listingExisting);
            }


            // Elimina las fotos
            var customFieldItemQuery = await _customFieldListingService.Query(x => x.ListingID == listing.ID).SelectAsync();

            var customFieldIds = customFieldItemQuery.Select(x => x.ID).ToList();

            foreach (var customFieldId in customFieldIds)
            {
                await _customFieldListingService.DeleteAsync(customFieldId);
            }

            // Elimina las camas

            var listacama = await _detailBedService.Query(x => x.ListingID == listing.ID).SelectAsync();

            var lista = listacama.Select(x => x.ID).ToList();

            foreach (var id in lista)
            {
                await _detailBedService.DeleteAsync(id);
            }

            // Get custom fields
            var customFieldCategoryQuery = await _customFieldCategoryService.Query(x => x.CategoryID == listing.CategoryID).Include(x => x.MetaField.ListingMetas).SelectAsync();

            var customFieldCategories = customFieldCategoryQuery.ToList();

            foreach (var metaCategory in customFieldCategories)
            {
                var field       = metaCategory.MetaField;
                var controlType = (BeYourMarket.Model.Enum.Enum_MetaFieldControlType)field.ControlTypeID;

                string controlId = string.Format("customfield_{0}_{1}_{2}", metaCategory.ID, metaCategory.CategoryID, metaCategory.FieldID);

                var formValue = form[controlId];

                if (string.IsNullOrEmpty(formValue))
                {
                    continue;
                }

                formValue = formValue.ToString();

                var itemMeta = new ListingMeta()
                {
                    ListingID   = listing.ID,
                    Value       = formValue,
                    FieldID     = field.ID,
                    ObjectState = Repository.Pattern.Infrastructure.ObjectState.Added
                };

                _customFieldListingService.Insert(itemMeta);
            }

            //ACA PONGO EL TITULO COMO ID
            await _unitOfWorkAsync.SaveChangesAsync();

            if (updateCount)
            {
                listing.Title = listing.ID.ToString();
                _listingService.Update(listing);
                await _unitOfWorkAsync.SaveChangesAsync();
            }


            if (Request.Files.Count > 0)
            {
                var itemPictureQuery = _listingPictureservice.Queryable().Where(x => x.ListingID == listing.ID);
                if (itemPictureQuery.Count() > 0)
                {
                    nextPictureOrderId = itemPictureQuery.Max(x => x.Ordering);
                }
            }

            if (files != null && files.Count() > 0)
            {
                foreach (HttpPostedFileBase file in files)
                {
                    if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
                    {
                        // Picture picture and get id
                        var picture = new Picture();
                        picture.MimeType = "image/jpeg";
                        _pictureService.Insert(picture);
                        await _unitOfWorkAsync.SaveChangesAsync();

                        // Format is automatically detected though can be changed.
                        ISupportedImageFormat format = new JpegFormat {
                            Quality = 90
                        };
                        Size size = new Size(500, 0);

                        //https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
                        // Initialize the ImageFactory using the overload to preserve EXIF metadata.
                        using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
                        {
                            var path = Path.Combine(Server.MapPath("~/images/listing"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg"));

                            // Load, resize, set the format and quality and save an image.
                            imageFactory.Load(file.InputStream)
                            .Resize(size)
                            .Format(format)
                            .Save(path);
                        }

                        var itemPicture = new ListingPicture();
                        itemPicture.ListingID = listing.ID;
                        itemPicture.PictureID = picture.ID;
                        itemPicture.Ordering  = nextPictureOrderId;

                        _listingPictureservice.Insert(itemPicture);

                        nextPictureOrderId++;
                    }
                }
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            //INSERTANDO CAMAS
            if (idcama != null)
            {
                List <int> listaid = new List <int>();
                for (int i = 0; i < idcama.Length; i++)
                {
                    if (listaid.Count != 0)                     //entra aca cuando no es la primera recorrida
                    {
                        if (!listaid.Contains(idcama[i]))
                        {
                            DetailBed detallecama = new DetailBed();
                            detallecama.TypeOfBedID = idcama[i];
                            detallecama.Quantity    = cantidad[i];
                            detallecama.ListingID   = listing.ID;
                            _detailBedService.Insert(detallecama);
                            listaid.Add(idcama[i]);
                        }
                    }
                    else                     //entra primero por no tener ninguna cama en la listaid
                    {
                        DetailBed detallecama = new DetailBed();
                        detallecama.TypeOfBedID = idcama[i];
                        detallecama.Quantity    = cantidad[i];
                        detallecama.ListingID   = listing.ID;
                        listaid.Add(idcama[i]);
                        _detailBedService.Insert(detallecama);
                    }
                }
            }               //fin insertando cama

            //Enviar correo de aviso a administrador
            var emailorderquery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "listingupdate").SelectAsync();

            var templateorder = emailorderquery.Single();
            var admin         = await _aspNetUserService.Query(x => x.AspNetRoles.Any(z => z.Name == "Administrator")).SelectAsync();

            dynamic emailorder = new Postal.Email("Email");

            foreach (var administradores in admin)
            {
                emailorder.To      = administradores.Email;
                emailorder.From    = CacheHelper.Settings.EmailAddress;
                emailorder.Subject = templateorder.Subject;
                emailorder.Body    = templateorder.Body;
                emailorder.Name    = administradores.FullName;
                emailorder.Id      = listing.ID;
                EmailHelper.SendEmail(emailorder);
            }

            await _unitOfWorkAsync.SaveChangesAsync();

            // Update statistics count
            if (updateCount)
            {
                _sqlDbService.UpdateCategoryItemCount(listing.CategoryID);
                _dataCacheService.RemoveCachedItem(CacheKeys.Statistics);
            }
            if (listing.Created.Day.Equals(DateTime.Now.Day))
            {
                TempData[TempDataKeys.UserMessage] = "[[[Listing is updated, contact the provider to activate the service]]]";
                Session.Add("focus", "Si");
                return(RedirectToAction("listingcalendar", "Manage", new { id = listing.ID }));
            }
            else
            {
                TempData[TempDataKeys.UserMessage] = "[[[Listing is updated!]]]";
                return(RedirectToAction("Listing", new { id = listing.ID }));
            }
        }
コード例 #33
0
        public async Task<IdentityResult> RegisterAccount(RegisterViewModel model)
        {                        
            var user = new ApplicationUser
            {
                UserName = model.Email,
                Email = model.Email,
                FirstName = model.FirstName,
                LastName = model.LastName,
                RegisterDate = DateTime.Now,
                RegisterIP = System.Web.HttpContext.Current.Request.GetVisitorIP(),
                LastAccessDate = DateTime.Now,
                LastAccessIP = System.Web.HttpContext.Current.Request.GetVisitorIP()
            };

            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                // Send Message
                var roleAdministrator = await RoleManager.FindByNameAsync(BeYourMarket.Model.Enum.Enum_UserType.Administrator.ToString());
                var administrator = roleAdministrator.Users.FirstOrDefault();

                var message = new MessageSendModel()
                {
                    UserFrom = administrator.UserId,
                    UserTo = user.Id,
                    Subject = HttpContext.ParseAndTranslate(string.Format("[[[Welcome to {0}!]]]", CacheHelper.Settings.Name)),
                    Body = HttpContext.ParseAndTranslate(string.Format("[[[Hi, Welcome to {0}! I am happy to assist you if you has any questions.]]]", CacheHelper.Settings.Name))

                };

                await MessageHelper.SendMessage(message);

                // Send an email with this link
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var urlHelper = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
                var callbackUrl = urlHelper.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: System.Web.HttpContext.Current.Request.Url.Scheme);

                var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "signup").SelectAsync();
                var emailTemplate = emailTemplateQuery.FirstOrDefault();

                if (emailTemplate != null)
                {
                    dynamic email = new Postal.Email("Email");
                    email.To = CacheHelper.Settings.EmailContact;
                    email.From = CacheHelper.Settings.EmailContact;
                    email.Subject = emailTemplate.Subject;
                    email.Body = emailTemplate.Body;
                    email.CallbackUrl = callbackUrl;
                    EmailHelper.SendEmail(email);
                }
            }            

            return result;
        }
コード例 #34
0
 public dynamic ComposeForwardUnitToFriendEmail(string friendname, string friendemailaddress, string message, int id)
 {
     dynamic email = new Postal.Email("ForwardtoFriend/Multipart");
     var poster = UserHelper.GetSendtoFriendPoster(HttpContext.Request.Url) ?? UserHelper.PosterHelper.DefaultPoster;
     email.To = friendemailaddress;
     email.FriendName = friendname;
     email.From = "*****@*****.**";
     email.SenderFirstName = poster.FirstName;
     email.Title = string.Format("Request From {0}", poster.FirstName);
     email.SubTitle = "Request from ";
     email.Message = message;
     email.InvitationNote = " invite you to see this potential unit.";
     email.FooterNote = "Check out this Property";
     var uri = Request.Url;
     if (uri != null)
     {
         var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
         var unitUrl = host + PreviewPathWithHost + id;
         email.UnitUrl = unitUrl;
         var currentunit = UnitofWork.UnitRepository.FindBy(x => x.UnitId == id).FirstOrDefault();
         if (currentunit != null)
         {
             var unitPicture = currentunit.PrimaryPhoto;
             unitPicture = unitPicture.Replace("../../", "");
             string unitTitle;
             if (String.IsNullOrEmpty(currentunit.Title))
             {
                 unitTitle = (currentunit.Address + " , " + currentunit.State + " , " + currentunit.City);
                 if (unitTitle.Length >= 50)
                 {
                     unitTitle = unitTitle.Substring(0, 50);
                 }
             }
             else
             {
                 unitTitle = currentunit.Title;
                 if (currentunit.Title.Length >= 50)
                 {
                     unitTitle = currentunit.Title.Substring(0, 50);
                 }
             }
             email.UnitTitle = unitTitle;
             // email.UnitPath = "http://www.haithem-araissia.com/images/property/home12.jpg";
             email.UnitPath = host + "/" + unitPicture;
         }
     }
     return email;
 }
コード例 #35
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    string confirmationToken =
                        WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email }, true);
                    Roles.AddUserToRole(model.UserName, "User");
                    dynamic email = new Postal.Email("RegEmail");
                    email.To = model.Email;
                    email.UserName = model.UserName;
                    email.ConfirmationToken = confirmationToken;
                    email.Send();

                    return RedirectToAction("RegisterStepTwo", "Account");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
コード例 #36
0
        public async Task <ActionResult> OrderActionNewReserva(int id, int status, int ot, int percent)
        {
            var order = await _orderService.FindAsync(id);

            order.Status   = status;
            order.OT       = ot;
            order.Modified = DateTime.Now;
            if (status == 2)
            {
                order.Percent = percent;
                int valor = Convert.ToInt32(order.Total.Value);
                int abono = (percent * valor) / 100;
                order.Abono = abono;
            }

            _orderService.Update(order);

            await _unitOfWorkAsync.SaveChangesAsync();

            var pasajero  = _aspNetUserService.Query(x => x.Id == order.UserReceiver).Select().FirstOrDefault();
            var propiedad = await _listingService.FindAsync(order.ListingID);

            var condominio = await _categoryService.FindAsync(propiedad.CategoryID);

            if (status == 2)
            {
                var emailorderquery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "pagoabono").SelectAsync();

                var     templateorder = emailorderquery.Single();
                dynamic emailorder    = new Postal.Email("Email");
                emailorder.To               = pasajero.Email;
                emailorder.From             = CacheHelper.Settings.EmailAddress;
                emailorder.Subject          = templateorder.Subject;
                emailorder.Body             = templateorder.Body;
                emailorder.Name             = pasajero.FirstName + pasajero.LastName;
                emailorder.Adults           = order.Adults;
                emailorder.Children         = order.Children;
                emailorder.Rent             = order.Price;
                emailorder.CleanlinessPrice = propiedad.CleanlinessPrice;
                emailorder.Service          = order.Price * 0.04;
                emailorder.Total            = order.Total;
                emailorder.Address          = propiedad.Address;
                emailorder.Condominium      = condominio.Name;
                emailorder.Period           = string.Format("Desde el {0} hasta el {1}", order.FromDate.Value.ToShortDateString(), order.ToDate.Value.ToShortDateString());
                emailorder.Tarifa           = propiedad.Price;
                emailorder.Abono            = order.Abono;
                emailorder.Garantia         = propiedad.Warranty;
                emailorder.FromDate         = order.FromDate.Value.ToShortDateString();
                emailorder.ToDate           = order.ToDate.Value.ToShortDateString();
                emailorder.Id               = order.ListingID;
                emailorder.OT               = order.OT;
                emailorder.Percent          = order.Percent;
                //Falta agregar la Orden de trabajo
                EmailHelper.SendEmail(emailorder);
            }

            //Generar SpreadSheet
            SpreadsheetHelper.WriteOtOAuth(order, propiedad, pasajero);

            var result = new
            {
                Success = true,
                Message = "Hola"
            };

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
コード例 #37
0
        public ActionResult Edit(string code, [Bind(Include = "CareManagerId,CareHomeId,Email,MediaFileDataId,Name,Gender,Age,Licensed,Licenses,CurrentPatients,AllowNewPatient,Career,Messages,BlogUrls,TotalRating,ReviewsCount,Rating,Birthday")] CareManager caremanager, HttpPostedFileBase file, int year, int month, int day)
        {
            // Checks file size.
            if (file != null && file.ContentLength > 200000)
            {
                ModelState.AddModelError("", "アップロードできる画像のサイズは200kBまでです。");
            }

            // Sets Dec. 31th.
            caremanager.Birthday = new DateTime(year, month, day);
            caremanager.Licensed = new DateTime(caremanager.Licensed.Year, 12, 31);

            if (ModelState.IsValid)
            {
                // Uploads Image
                if (file != null)
                {
                    BlobHelper.DeleteIfExists("mediafile", caremanager.MediaFileDataId);
                    caremanager.MediaFileDataId = BlobHelper.Upload("mediafile", file, file.FileName);
                }

                // Adds / Edits record
                if (caremanager.CareManagerId == 0)
                {
                    // Add
                    db.CareManagers.Add(caremanager);
                    var verification = new EmailVerification()
                    {
                        CareManager = caremanager, Email = caremanager.Email
                    };
                    db.EmailVerifications.Add(verification);
                    db.SaveChanges();

                    // Notifies CareManager to verify.
                    //SendEmail(caremanager.Email, "[ケアマネ情報局] ケアマネ会員認証", "URL: " + Url.Action("Verify", "EmailVerification", new { verificationCode = verification.VerificationCode}, Request.Url.Scheme));
                    var     added = db.CareManagers.Include(m => m.CareHome).FirstOrDefault(m => m.CareManagerId == caremanager.CareManagerId);
                    dynamic email = new Postal.Email("CareManagerAdded");
                    email.To = added.Email;
                    email.CareManagerName  = added.Name;
                    email.CareHomeName     = added.CareHome.Name;
                    email.CareHomeUserName = "";
                    if (added.CareHome.User != null)
                    {
                        email.CareHomeUserName = added.CareHome.User.Name;
                    }
                    email.VerificationUrl = Url.Action("Verify", "EmailVerification", new { verificationCode = verification.VerificationCode }, Request.Url.Scheme);
                    email.SiteUrl         = string.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority);
                    email.Send();
                }
                else
                {
                    // Edit
                    var entry = db.Entry(caremanager);
                    entry.State = EntityState.Unchanged;
                    entry.Property(p => p.Email).IsModified    = true;
                    entry.Property(p => p.Name).IsModified     = true;
                    entry.Property(p => p.Gender).IsModified   = true;
                    entry.Property(p => p.Licensed).IsModified = true;
                    entry.Property(p => p.Birthday).IsModified = true;
                    if (file != null)
                    {
                        entry.Property(p => p.MediaFileDataId).IsModified = true;
                    }
                    db.SaveChanges();
                }
                Log(LogType.CareHome, "所属するケアマネの情報を更新しました。");
                return(RedirectToAction("Index"));
            }
            ViewBag.Gender = EnumHelper <Gender> .GetSelectList(caremanager.Gender);

            ViewBag.Year     = Helper.Helper.GetBirthdayYears(caremanager.Birthday);
            ViewBag.Month    = Helper.Helper.GetBirthdayMonths(caremanager.Birthday);
            ViewBag.Day      = Helper.Helper.GetBirthdayDays(caremanager.Birthday);
            ViewBag.Licensed = Helper.Helper.GetLicensedYears(caremanager.Licensed);
            return(View(caremanager));
        }
コード例 #38
0
        public async Task <IdentityResult> RegisterAccount(RegisterViewModel model)
        {
            var user = new ApplicationUser
            {
                UserName       = model.Email,
                Email          = model.Email,
                FirstName      = model.FirstName,
                LastName       = model.LastName,
                RegisterDate   = DateTime.Now,
                RegisterIP     = System.Web.HttpContext.Current.Request.GetVisitorIP(),
                LastAccessDate = DateTime.Now,
                LastAccessIP   = System.Web.HttpContext.Current.Request.GetVisitorIP()
            };

            var result = await UserManager.CreateAsync(user, model.Password);

            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                // Send Message
                var roleAdministrator = await RoleManager.FindByNameAsync(BeYourMarket.Model.Enum.Enum_UserType.Administrator.ToString());

                var administrator = roleAdministrator.Users.FirstOrDefault();

                var message = new MessageSendModel()
                {
                    UserFrom = administrator.UserId,
                    UserTo   = user.Id,
                    Subject  = HttpContext.ParseAndTranslate(string.Format("[[[Welcome to {0}!]]]", CacheHelper.Settings.Name)),
                    Body     = HttpContext.ParseAndTranslate(string.Format("[[[Hi, Welcome to {0}! I am happy to assist you if you has any questions.]]]", CacheHelper.Settings.Name))
                };

                await MessageHelper.SendMessage(message);

                // Send an email with this link
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                var urlHelper   = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
                var callbackUrl = urlHelper.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: System.Web.HttpContext.Current.Request.Url.Scheme);

                var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "signup").SelectAsync();

                var emailTemplate = emailTemplateQuery.FirstOrDefault();

                if (emailTemplate != null)
                {
                    dynamic email = new Postal.Email("Email");
                    email.To          = CacheHelper.Settings.EmailContact;
                    email.From        = CacheHelper.Settings.EmailContact;
                    email.Subject     = emailTemplate.Subject;
                    email.Body        = emailTemplate.Body;
                    email.CallbackUrl = callbackUrl;
                    EmailHelper.SendEmail(email);
                }
            }

            return(result);
        }
コード例 #39
0
        public async Task<ActionResult> ContactUser(ContactUserModel model)
        {
            var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "privatemessage").SelectAsync();
            var emailTemplate = emailTemplateQuery.Single();

            dynamic email = new Postal.Email("Email");
            email.To = CacheHelper.Settings.EmailContact;
            email.From = CacheHelper.Settings.EmailContact;
            email.Subject = emailTemplate.Subject;
            email.Body = emailTemplate.Body;
            email.Message = model.Message;
            EmailHelper.SendEmail(email);

            TempData[TempDataKeys.UserMessage] = "[[[Message sent succesfully!]]]";

            return RedirectToAction("Listing", "Listing", new { id = model.ListingID });
        }
コード例 #40
0
        public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByNameAsync(model.Email);
                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return View("ForgotPasswordConfirmation");
                }

                // Check if email confirm required
                if (CacheHelper.Settings.EmailConfirmedRequired && !(await UserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    return View("ForgotPasswordConfirmation");
                }

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);		
                // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                // return RedirectToAction("ForgotPasswordConfirmation", "Account");

                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                var emailTemplateQuery = await _emailTemplateService.Query(x => x.Slug.ToLower() == "forgotpassword").SelectAsync();
                var emailTemplate = emailTemplateQuery.Single();

                dynamic email = new Postal.Email("Email");
                email.To = CacheHelper.Settings.EmailContact;
                email.From = CacheHelper.Settings.EmailContact;
                email.Subject = emailTemplate.Subject;
                email.Body = emailTemplate.Body;
                email.CallbackUrl = callbackUrl;
                EmailHelper.SendEmail(email);

                return RedirectToAction("ForgotPasswordConfirmation", "Account");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
コード例 #41
0
        public void ForwardToFriend()
        {
            //Act

            //var actual = new SpecialistPublicProfileHelper(Uow, new FakeMembershipProvider());

            //var controllerContext = new Mock<ControllerContext>();
            //controllerContext.SetupGet(x => x.HttpContext.Request.Url).Returns(new Uri("http://tempuri.org"));
            //actual.ControllerContext = controllerContext.Object;

            //var email = actual.SpecialPublicProfileComposeForwardToFriendEmail("myFriendName", "myFriendEmailAddress", "myMessage", 5);

            //Assert.AreEqual(email.SenderFirstName, "A Friend");

            //// email.ProfileUrl
            ////  email.CustomTitle
            ////email.PhotoPath
            //Assert.AreEqual(email.ProfileUrl, "A Friend");
            //Assert.AreEqual(email.CustomTitle, "A Friend");
            //Assert.AreEqual(email.PhotoPath, "A Friend");
            var controllerContext = new Mock<ControllerContext>();
            controllerContext.SetupGet(x => x.HttpContext.Request.Url).Returns(new Uri("http://tempuri.org"));
            Controller.ControllerContext = controllerContext.Object;

            var email = new Postal.Email("ForwardtoFriend/Multipart");
            try
            {
                email.SendAsync();
            }
            catch (Exception e)
            {

                throw;
            }

            var actual = Controller.ForwardtoFriend("myFriendName", "myFriendEmailAddress", "myMessage", 5);
            var viewResult = actual as ViewResult;
            if (viewResult != null)
            {
                Assert.AreEqual(viewResult.ViewBag.Email, 55.50);

            }

            //   public ActionResult ForwardtoFriend(string friendname, string friendemailaddress, string message, int id)
            //{
            //    dynamic email = new Email("ForwardtoFriend/Multipart");
            //    var poster = UserHelper.GetSendtoFriendPoster() ?? UserHelper.DefaultPoster;
            //    email.To = friendemailaddress;
            //    email.FriendName = friendname;
            //    email.From = "*****@*****.**";
            //    email.SenderFirstName = poster.FirstName;
            //    email.Title = string.Format("Request From {0}", poster.FirstName);
            //    email.SubTitle = "Request from ";
            //    email.Message = message;
            //    email.InvitationNote = " invite you to see this skilled professional.";
            //    email.FooterNote = "Check out this Professional";
            //    var uri = Request.Url;
            //    if (uri != null)
            //    {
            //        var host = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
            //        email.ProfileUrl = host + uri.AbsolutePath.Replace("ForwardtoFriend", "");
            //        var currentSpecialist = _unitOfWork.SpecialistRepository.FindBy(x => x.SpecialistId == id).FirstOrDefault();
            //        if (currentSpecialist != null)
            //        {
            //            var specialistTitle = currentSpecialist.FirstName + " , " + currentSpecialist.LastName;
            //            if (specialistTitle.Length >= 50)
            //            {
            //                specialistTitle = specialistTitle.Substring(0, 50);
            //            }
            //            email.CustomTitle = specialistTitle;
            //        }
            //        if (currentSpecialist != null)
            //        {
            //            email.PhotoPath = host + "/" + GetSpecialistPrimaryWorkPhoto(id).Replace("../../", "");

            //        }
            //    }
            //    try
            //    {
            //        email.SendAsync();

            //    }
            //    catch (Exception)
            //    {
            //        return RedirectToAction("Index", new { id, sharespecialist = false });
            //    }
            //    return RedirectToAction("Index", new { id, sharespecialist = true });

            //}

            //Act
            //string friendname, string friendemailaddress, string message, int id
            //string friendname = "Joe";
            //string friendemailaddress = "*****@*****.**";
            //string message = "message from Joe";
            //int id = 2;
            //var actual = Controller.ForwardtoFriend();

            //var DefaultPoster = new PosterAttributes(tenant.FirstName, tenant.LastName,
            //                                    currenturl + "/tenantprofile/index/" + tenant.TenantId, tenant.Photo,
            //                                    tenant.EmailAddress, "tenant", tenant.TenantId);
            Assert.Inconclusive("Not Implemented Yet");
        }