Пример #1
0
        public static async Task <bool> SendCreateAccountToTenantSendgrid(Person tenant, string email, string temPass, Person owner, string token, string address)
        {
            var nvc = new NameValueCollection();

            nvc.Set("token", token);
            nvc.Set("userId", tenant.Id.ToString());
            string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "Account/Activate", UtilService.ToQueryString(nvc));
            SendGridEmailModel mail = new SendGridEmailModel
            {
                RecipentName  = tenant.FirstName,
                ButtonUrl     = url,
                RecipentEmail = email,
                NewUserName   = email,
                NewPassWord   = temPass,
                OwnerName     = owner.FirstName,
                Address       = address
            };

            try
            {
                await SendEmailWithSendGrid(EmailType.OwnerCreatNewTenantEmail, mail);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
        public async Task <ActionResult> AddRentalApplication(RentalApplicationModel model)
        {
            if (ModelState.IsValid)
            {
                var files    = Request.Files;
                var userName = User.Identity.Name;

                if (String.IsNullOrEmpty(userName))
                {
                    return(Json(new { Success = false, ErrorMsg = "User not exist!" }));
                }


                var login  = AccountService.GetLoginByEmail(userName);
                var result = RentalService.AddRentallApllication(model, login, Request.Files);
                if (result.IsSuccess)
                {
                    var propertyOwner      = RentalService.GetOwnerDetails(model);
                    var propertyOwnerLogin = AccountService.GetLoginById(propertyOwner.Id);
                    var property           = db.Property.FirstOrDefault(x => x.Id == model.PropertyId);
                    var addressString      = "";
                    if (property != null)
                    {
                        var address = PropertyService.GetAddressById(property.AddressId);
                        if (address != null)
                        {
                            if (address.Street != "" && address.City != "")
                            {
                                addressString = address.Number + " " + address.Street + ", " + address.Suburb + ", " + address.City + ", " + address.PostCode;
                            }
                        }
                    }
                    //  string url = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "PropertyOwners/Property/RentalProperties");
                    var nvc = new NameValueCollection();
                    nvc.Add("PropId", model.PropertyId.ToString());
                    nvc.Add("returnUrl", "/PropertyOwners/Property/RentalProperties");
                    string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/PropertyOwners/Property/AllRentalApplications", UtilService.ToQueryString(nvc));
                    SendGridEmailModel mail = new SendGridEmailModel
                    {
                        RecipentName  = propertyOwner.FirstName,
                        ButtonText    = "",
                        ButtonUrl     = url,
                        RecipentEmail = propertyOwnerLogin.Email,
                        Address       = addressString,
                    };
                    await EmailService.SendEmailWithSendGrid(EmailType.NewApplicationEmail, mail);
                }
                return(result.IsSuccess ? Json(new { Success = true }) : Json(new { Success = false, ErrorMsg = result.ErrorMessage }));
            }
            return(Json(new { Success = false }));
        }
Пример #3
0
 public static async Task SendAcceptRequestEmail(string name, string email, string add)
 {
     string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "Tenants/Home/Requests?RequestStatus=2");
     SendGridEmailModel mail = new SendGridEmailModel
     {
         RecipentName  = name,
         ButtonText    = "",
         ButtonUrl     = url,
         RecipentEmail = email,
         Address       = add,
         PersonType    = "land lord"
     };
     await EmailService.SendEmailWithSendGrid(EmailType.AcceptRequestEmail, mail);
 }
Пример #4
0
 public static async Task SendEmailToGroup(EmailType emailType, IEnumerable <Recipient> recipients, string btnUrl = null, string address = null)
 {
     foreach (var person in recipients)
     {
         var mailModel = new SendGridEmailModel
         {
             RecipentName  = person.Name,
             ButtonText    = "",
             ButtonUrl     = btnUrl,
             RecipentEmail = person.Email,
             Address       = address,
             PersonType    = person.PersonType
         };
         await SendEmailWithSendGrid(emailType, mailModel);
     }
 }
Пример #5
0
        // [ValidateAntiForgeryToken]
        public async Task <JsonResult> ApplicationAccepted(AcceptAndDeclineRentalApplicationModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Json(new { Success = false }));
            }
            var user   = User.Identity.Name;
            var login  = AccountService.GetLoginByEmail(user);
            var result = PropertyService.AcceptApplication(model, login);


            // send email here
            if (result.IsSuccess)
            {
                var tenantPersonDetails = AccountService.GetPersonById(model.TenantId);
                var tenatLoginDetails   = AccountService.GetLoginById(model.TenantId);


                var property      = db.Property.FirstOrDefault(x => x.Id == model.PropertyId);
                var addressString = "";
                if (property != null)
                {
                    var address = PropertyService.GetAddressById(property.AddressId);
                    if (address != null)
                    {
                        if (address.Street != "" && address.City != "")
                        {
                            addressString = address.Number + " " + address.Street + ", " + address.Suburb + ", " + address.City + ", " + address.PostCode;
                        }
                    }
                }

                string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "Tenants/Home/MyRentals");
                SendGridEmailModel mail = new SendGridEmailModel
                {
                    RecipentName  = tenantPersonDetails.FirstName,
                    ButtonText    = "",
                    ButtonUrl     = url,
                    RecipentEmail = tenatLoginDetails.Email,
                    Address       = addressString,
                };
                await EmailService.SendEmailWithSendGrid(EmailType.AcceptRentalApplication, mail);

                return(Json(new { Success = result.IsSuccess }));
            }
            return(Json(new { Success = result.IsSuccess, Msg = result.ErrorMessage }));
        }
Пример #6
0
        public static async Task <HttpStatusCode> SendEmailSendGrid(SendGridEmailModel mailModel)
        {
            var client      = new SendGridClient(SendGridApiKey);
            var personlized = new[]
            {
                new {
                    Subject = mailModel.Subject,
                    To      = new List <Recipient>
                    {
                        new Recipient
                        {
                            Email = mailModel.RecipentEmail,
                        }
                    },
                    Substitutions = new Dictionary <string, string>
                    {
                        { "%first_name%", mailModel.RecipentName },
                        { "%owner%", mailModel.OwnerName },
                        { "%body%", mailModel.Body },
                        { "%button_text%", mailModel.ButtonText },
                        { "%button_url%", mailModel.ButtonUrl },
                        { "%subject%", mailModel.Subject }
                    }
                }
            }.ToList();
            var jsonObject = new {
                from = new Recipient {
                    Email = "*****@*****.**",
                    Name  = "Property Community"
                },
                template_id      = SendGridActivationTemplateId,
                personalizations = personlized
            };

            var json     = new JavaScriptSerializer().Serialize(jsonObject);
            var response = await client.RequestAsync(method : SendGridClient.Method.POST,
                                                     requestBody : json.ToString(),
                                                     urlPath : "mail/send");

            return(response.StatusCode);
        }
Пример #7
0
        public async System.Threading.Tasks.Task <JsonResult> SaveJobQuote(QuoteModel jobQuoteViewModel)
        {
            if (ModelState.IsValid)
            {
                var files  = Request.Files;
                var user   = User.Identity.Name;
                var login  = AccountService.GetLoginByEmail(user);
                var result = JobService.AddJobQuote(jobQuoteViewModel, login, Request.Files);
                #region


                if (result.IsSuccess)
                {
                    var propertyOwner      = JobService.GetOwnerDetails(jobQuoteViewModel.JobRequestId);
                    var propertyOwnerLogin = AccountService.GetLoginById(propertyOwner.Id);

                    var property = db.TenantJobRequest.Where(x => x.Id == jobQuoteViewModel.JobRequestId).Select(x => x.Property).FirstOrDefault();
                    var nvc      = new NameValueCollection();
                    nvc.Add("marketJobId", jobQuoteViewModel.JobRequestId.ToString());
                    string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/Jobs/Home/GetJobQuotes", UtilService.ToQueryString(nvc));
                    SendGridEmailModel mail = new SendGridEmailModel
                    {
                        RecipentName  = propertyOwner.FirstName,
                        ButtonText    = "",
                        ButtonUrl     = url,
                        Address       = property.Address.ToAddressString(),
                        RecipentEmail = propertyOwnerLogin.Email,
                        JobTitle      = jobQuoteViewModel.Title ?? "No Title",
                    };
                    await EmailService.SendEmailWithSendGrid(EmailType.NewQuoteEmail, mail);
                }

                #endregion
                return(Json(new { Success = result.IsSuccess, ErrorMsg = result.ErrorMessage ?? "" }));
            }
            return(Json(new { success = false }));
        }
Пример #8
0
        public static async Task <bool> SendActivationEmail(string userName, string userEmail, string confirmUrl)
        {
            string             subject = "";
            string             body    = "";
            SendGridEmailModel mail    = new SendGridEmailModel
            {
                RecipentName  = userName,
                Subject       = subject,
                Body          = body,
                ButtonUrl     = confirmUrl,
                RecipentEmail = userEmail
            };

            try
            {
                await SendEmailWithSendGrid(EmailType.ActivationEmail, mail);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Пример #9
0
        public async Task <ActionResult> AccceptQuote(JobAcceptedModel jobModel)
        {
            var user = User.Identity.Name;

            if (String.IsNullOrEmpty(user))
            {
                return(Json(new { Success = false, Msg = "User not found!" }));
            }
            var login  = AccountService.GetLoginByEmail(user);
            var result = JobService.AcceptQuote(jobModel, login);

            if (result.IsSuccess)
            {
                var serviceProviderPersonDetails = JobService.GetPersonByJobQuoteId(jobModel);
                var serviceProviderLoginDetails  = AccountService.GetLoginById(serviceProviderPersonDetails.Id);
                var jobDetails = JobService.GetMarketJobById(jobModel.JobRequestId);
                var nvc        = new NameValueCollection();
                nvc.Add("userAction", "2");

                string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/Jobs/Home", UtilService.ToQueryString(nvc));
                SendGridEmailModel mail = new SendGridEmailModel
                {
                    RecipentName  = serviceProviderPersonDetails.FirstName,
                    ButtonText    = "",
                    ButtonUrl     = url,
                    RecipentEmail = serviceProviderLoginDetails.Email,
                    JobTitle      = jobDetails.Title ?? "No Title",
                };
                await EmailService.SendEmailWithSendGrid(EmailType.AcceptQuote, mail);

                return(Json(new { Success = result.IsSuccess, Msg = result.ErrorMessage }));
            }


            return(Json(new { Success = false }));
        }
Пример #10
0
        public static async Task <HttpStatusCode> SendEmailWithSendGrid(EmailType emailType, SendGridEmailModel mailModel)
        {
            var client      = new SendGridClient(SendGridApiKey);
            var personlized = new[]
            {
                new {
                    Subject = mailModel.Subject,
                    To      = new List <Recipient>
                    {
                        new Recipient
                        {
                            Email = mailModel.RecipentEmail,
                        }
                    },
                    Substitutions = new Dictionary <string, string>
                    {
                        { "%first_name%", mailModel.RecipentName },
                        { "%owner_name%", mailModel.OwnerName },
                        { "%body%", mailModel.Body },
                        { "%button_text%", mailModel.ButtonText },
                        { "%button_url%", mailModel.ButtonUrl },
                        { "%subject%", mailModel.Subject },
                        { "%new_user_name%", mailModel.NewUserName },
                        { "%new_password%", mailModel.NewPassWord },
                        { "%address%", mailModel.Address },
                        { "%job_title%", mailModel.JobTitle },
                        { "%person_type%", mailModel.PersonType },
                        { "%tenant_name%", mailModel.TenantName },
                        { "%date%", mailModel.Date },
                    }
                }
            }.ToList();
            var jsonObject = new
            {
                from = new Recipient
                {
                    Email = "*****@*****.**",
                    Name  = "Property Community"
                },
                template_id      = GetSendGridTemplateId(emailType),
                personalizations = personlized
            };

            var json     = new JavaScriptSerializer().Serialize(jsonObject);
            var response = await client.RequestAsync(method : SendGridClient.Method.POST,
                                                     requestBody : json.ToString(),
                                                     urlPath : "mail/send");

            return(response.StatusCode);
        }
Пример #11
0
        private async Task MessageMonitor()
        {
            CancellationToken cancellation = cts.Token;
            TimeSpan          interval     = TimeSpan.Zero;

            while (!cancellation.WaitHandle.WaitOne(interval))
            {
                using (var db = new KeysEntities())
                {
                    try
                    {
                        var items = db.OutGoingMessage.Where(x => x.IsActive && (!x.IsProcessed || x.Error != null));
                        foreach (var m in items)
                        {
                            var per   = db.Person.FirstOrDefault(x => x.Id == m.PersonId);
                            var login = per.Login;
                            var nvc   = new NameValueCollection();

                            string ownerUrl  = "http://new-keys.azurewebsites.net/PropertyOwners/Manage/RentalPaymentTracking";
                            string tenantUrl = "http://new-keys.azurewebsites.net/Teanants/Home/MyRentals";
                            var    mailModel = new SendGridEmailModel
                            {
                                RecipentName  = per.FirstName,
                                RecipentEmail = login.UserName,
                                Address       = m.Subject,
                            };
                            HttpStatusCode res;
                            switch (m.MessageTypeId)
                            {
                            case 1:
                                mailModel.ButtonUrl = tenantUrl;
                                mailModel.Date      = m.Message;
                                res = await EmailService.SendEmailWithSendGrid(EmailType.TenantPaymentReminder, mailModel);

                                if (res != HttpStatusCode.Accepted)
                                {
                                    m.Error = res.ToString();
                                }
                                else
                                {
                                    m.Error = null;
                                }
                                break;

                            case 2:
                                mailModel.ButtonUrl = ownerUrl;
                                var tokens = m.Message.Split(new char[0]).ToList();
                                var date   = tokens.ElementAt(tokens.Count - 1);
                                tokens.RemoveAt(tokens.Count - 1);
                                var tenantName = String.Join(" ", tokens);
                                mailModel.TenantName = tenantName;
                                mailModel.Date       = date;
                                res = await EmailService.SendEmailWithSendGrid(EmailType.OwnerUpcomingRentalPayment, mailModel);

                                if (res != HttpStatusCode.Accepted)
                                {
                                    m.Error = res.ToString();
                                }
                                else
                                {
                                    m.Error = null;
                                }
                                break;
                            }
                            m.IsProcessed = true;
                        }
                        db.SaveChanges();
                        if (cancellation.IsCancellationRequested)
                        {
                            break;
                        }
                        interval = new TimeSpan(0, 0, 10);
                    }
                    catch (Exception ex)
                    {
                        // Log the exception.
                        Debug.WriteLine(ex.StackTrace);
                        interval = new TimeSpan(0, 0, 10);
                    }
                }
            }
        }
Пример #12
0
        public async Task <ActionResult> AddProperty(PropertyMyOnboardModel model)
        {
            var status  = true;
            var message = "Record added successfully";
            var data    = model;
            AddTenantToPropertyModel tenant = new AddTenantToPropertyModel();

            //*********** AddNewProperty
            var user        = User.Identity.Name;
            var login       = AccountService.GetLoginByEmail(user);
            var newProp     = PropertyOwnerService.AddOnboardProperty(login, model);
            var address     = model.Address.ToAddressString();
            var ownerPerson = AccountService.GetPersonByLoginId(login.Id);
            ////*********** AddRepayments

            var newRepayment = new PropertyRepayment();

            if (newProp == null)
            {
                return(Json(new { Success = false, message = "Cannot find the property!" }));
            }
            else
            {
                newRepayment = PropertyOwnerService.AddOnboardRepayment(login, model.Repayments, newProp.Id);
                decimal _totalRepayment = 0;

                int _nosWeeks      = 0;
                int _nosFortnights = 0;
                int _nosMonthly    = 0;
                if (newRepayment != null)
                {
                    foreach (Service.Models.RepaymentViewModel repayment in model.Repayments)
                    {
                        switch (repayment.FrequencyType)
                        {
                        case 1:     // Weekly
                                    // find the nos of weeks in datediff(StartDate, EndDate)
                            _nosWeeks = ((newRepayment.EndDate - newRepayment.StartDate) ?? TimeSpan.Zero).Days / 7;
                            // _totalAmount = nos weeks * amount
                            _totalRepayment = _nosWeeks * newRepayment.Amount;
                            break;

                        case 2:       // Fortnightly
                                      // find the nos of Fortnights in datediff(StartDate, EndDate)
                            _nosFortnights = ((newRepayment.EndDate - newRepayment.StartDate) ?? TimeSpan.Zero).Days / 14;
                            // _totalAmount = nos weeks * amount
                            _totalRepayment = _nosFortnights * newRepayment.Amount;
                            break;

                        case 3:     //Monthly
                                    // find the nos of Monthls in datediff(StartDate, EndDate)
                            _nosMonthly     = ((newRepayment.EndDate - newRepayment.StartDate) ?? TimeSpan.Zero).Days / 30;
                            _totalRepayment = _nosMonthly * newRepayment.Amount;
                            // _totalAmount = nos Monthls * amount
                            break;
                        }

                        actualTotalRepayment += _totalRepayment;
                    }
                }

                ////*****AddExpenses
                //var newExpense = new PropertyExpense();
                //newExpense = PropertyOwnerService.AddOnboardExpense(login, model.Expenses, newProp.Id);
                //******AddFinancial
                var newFinancial = new PropertyFinance();
                newFinancial = PropertyOwnerService.AddOnboardFinance(login, model, newProp.Id, actualTotalRepayment);

                //return Json( new { Success = true , PropertyId = newProp.Id});
                if (!model.IsOwnerOccupied)
                {
                    var ten = AccountService.GetExistingLogin(model.TenantToPropertyModel.TenantEmail);
                    if (ten == null)
                    {
                        var    sendEmail = false;
                        string temPass   = null;
                        /// CREATE AN ACCOUNT AND SEND EMAIL TO TENANT TO ACTIVATE AND RESET ACCOUNT
                        temPass = UtilService.GeneraterRandomKey(8);
                        var createRes = AccountService.CreateTenantAccount(model.TenantToPropertyModel, login, temPass);
                        if (createRes.IsSuccess)
                        {
                            ten       = createRes.NewObject as Login;
                            sendEmail = true;
                        }
                        if (sendEmail && temPass != null)
                        {
                            var per = AccountService.GetPersonByLoginId(ten.Id);
                            await EmailService.SendCreateAccountToTenantSendgrid(per, model.TenantToPropertyModel.TenantEmail, temPass, ownerPerson, ten.EmailConfirmationToken, address);
                        }
                    }
                    else
                    {
                        if (!ten.IsActive)
                        {
                            var resultTenantActive = PropertyService.ActivateTenant(login, ten.Id);
                            if (resultTenantActive.IsSuccess)
                            {
                                // SEND EMAIL INTIMATING THAT ACCOUNT HAS BEEN ACTIVATED BY THE OWNER
                                //await SendActivationEmailToTenant(model);
                            }
                            else
                            {
                                return(Json(new { Sucess = false, redirect = "Redirect", url = Url.Action("Index", "PropertyOwners") }));
                            }
                        }
                    }
                    var person = AccountService.GetPersonByLoginId(ten.Id);
                    var result = PropertyService.AddTenantToProperty(login, person.Id, newProp.Id, model.TenantToPropertyModel.StartDate,
                                                                     model.TenantToPropertyModel.EndDate, model.TenantToPropertyModel.PaymentFrequencyId, model.TenantToPropertyModel.PaymentAmount);
                    if (result.IsSuccess)
                    {
                        string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "Tenant/Home/MyRentals");
                        SendGridEmailModel mail = new SendGridEmailModel
                        {
                            RecipentName  = model.TenantToPropertyModel.FirstName,
                            ButtonText    = "",
                            ButtonUrl     = url,
                            RecipentEmail = model.TenantToPropertyModel.TenantEmail,
                            OwnerName     = ownerPerson.FirstName,
                            Address       = address,
                        };
                        await EmailService.SendEmailWithSendGrid(EmailType.OwnerAddTenantEmail, mail);

                        return(Json(new { Sucess = true, Msg = "Added!", result = "Redirect", url = Url.Action("Index", "PropertyOwners") }));
                    }
                    else
                    {
                        return(Json(new { Sucess = false, Msg = result.ErrorMessage, redirect = "Redirect", url = Url.Action("Index", "PropertyOwners") }));
                    }
                }
            }

            return(Json(new { success = status, message = message, data = tenant }));
        }
Пример #13
0
        public static ServiceResponseResult AcceptQuote(JobAcceptedModel model, Login login)
        {
            using (var db = new KeysEntities())
            {
                var quote = db.JobQuote.FirstOrDefault(x => x.Id == model.QuoteId);
                if (quote == null)
                {
                    return(new ServiceResponseResult {
                        IsSuccess = false, ErrorMessage = "Can note find quote"
                    });
                }
                quote.IsViewed = true;
                quote.Status   = "accepted";
                var job = new Job
                {
                    ProviderId     = quote.ProviderId,
                    PropertyId     = quote.TenantJobRequest.PropertyId,
                    AcceptedQuote  = quote.Amount,
                    JobDescription = model.JobDescription,
                    JobRequestId   = model.JobRequestId,
                    JobStatusId    = 2,
                    UpdatedBy      = login.Email,
                    CreatedOn      = DateTime.UtcNow,
                    UpdatedOn      = DateTime.UtcNow,
                    CreatedBy      = login.Email,
                    OwnerId        = login.Id
                };
                db.Job.Add(job);
                var marketJob = db.TenantJobRequest.FirstOrDefault(x => x.Id == model.JobRequestId);

                if (marketJob == null)
                {
                    return(new ServiceResponseResult {
                        IsSuccess = false, ErrorMessage = "Can not find job!"
                    });
                }
                marketJob.JobStatusId = 5;
                var otherQuotes = db.JobQuote.Where(x => x.JobRequestId == model.JobRequestId && x.Id != model.QuoteId).ToList();
                otherQuotes.ForEach(x => x.Status = "unsuccessful");
                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    return(new ServiceResponseResult {
                        IsSuccess = false, ErrorMessage = _error
                    });
                }
                foreach (var item in otherQuotes)
                {
                    var nvc = new NameValueCollection();
                    nvc.Add("status", "unsuccessful");


                    string             url  = UtilService.UrlGenerator(System.Web.HttpContext.Current.Request, "/Companies/Manage/MyQuotes", UtilService.ToQueryString(nvc));
                    SendGridEmailModel mail = new SendGridEmailModel
                    {
                        RecipentName  = item.ServiceProvider.Company.Name,
                        ButtonText    = "",
                        ButtonUrl     = url,
                        RecipentEmail = item.ServiceProvider.Company.CreatedBy,
                        JobTitle      = item.TenantJobRequest.JobDescription ?? "No Description",
                    };
                    EmailService.SendEmailWithSendGrid(EmailType.DeclineQuote, mail);
                }
                return(new ServiceResponseResult {
                    IsSuccess = true
                });
            }
        }