示例#1
0
 public ProfilesController(AppDbContext context, AccountServices accountServices, CognitiveServices cognitiveServices)
 {
     _context           = context;
     _accountServices   = accountServices;
     _cognitiveServices = cognitiveServices;
 }
示例#2
0
        private void SendApprovalRejectionEmail(OrderViewModelLight orderVMLight)
        {
            UserServices userSerivce = new UserServices();

            var user = new UserSessionModel();

            #pragma warning disable CS0472 // The result of the expression is always 'true' since a value of type 'long' is never equal to 'null' of type 'long?'
            if (orderVMLight.ProjectOwnerId != null)
            #pragma warning restore CS0472 // The result of the expression is always 'true' since a value of type 'long' is never equal to 'null' of type 'long?'
            {
                user = new AccountServices().GetUserSessionModel(orderVMLight.ProjectOwnerId).Model as UserSessionModel;
            }

            var orderEmailModel = new SendEmailApprovalModel();
            orderEmailModel.HelpLink = "mailto:[email protected]";

            orderEmailModel.Subject = string.Format("The status of an Order request has changed");

            orderEmailModel.Reason           = orderVMLight.Comments;
            orderEmailModel.ProjectId        = orderVMLight.ProjectId;
            orderEmailModel.ProjectName      = orderVMLight.ProjectName;
            orderEmailModel.QuoteTitle       = orderVMLight.QuoteTitle;
            orderEmailModel.ERPOrderNumber   = (orderVMLight.ERPOrderNumber != null) ? orderVMLight.ERPOrderNumber : string.Empty;
            orderEmailModel.ERPInvoiceNumber = (orderVMLight.ERPInvoiceNumber != null) ? orderVMLight.ERPInvoiceNumber : string.Empty;
            orderEmailModel.ERPPOKey         = (orderVMLight.ERPPOKey != null) ? orderVMLight.ERPPOKey.Value : 0;
            orderEmailModel.ERPInvoiceDate   = (orderVMLight.ERPInvoiceDate != null) ? orderVMLight.ERPInvoiceDate.Value : DateTime.Now;
            orderEmailModel.ERPOrderDate     = (orderVMLight.ERPOrderDate != null) ? orderVMLight.ERPOrderDate.Value : DateTime.Now;
            #pragma warning disable CS0472 // The result of the expression is always 'true' since a value of type 'decimal' is never equal to 'null' of type 'decimal?'
            orderEmailModel.TotalNet = (orderVMLight.TotalNetPrice != null) ? orderVMLight.TotalNetPrice : 0;
            #pragma warning restore CS0472 // The result of the expression is always 'true' since a value of type 'decimal' is never equal to 'null' of type 'decimal?'
            orderEmailModel.Approved     = (orderVMLight.OrderStatusTypeId == OrderStatusTypeEnum.InProcess);
            orderEmailModel.ModifierName = (user != null) ? user.FirstName + " " + user.LastName : orderVMLight.UpdatedByUserIdStr;

            orderEmailModel.ProjectOwnerName = (orderVMLight.ProjectOwner != null) ? orderVMLight.ProjectOwner : user.FirstName + " " + user.LastName;
            orderEmailModel.ProjectDate      = (orderVMLight.ProjectDate != null) ? orderVMLight.ProjectDate : DateTime.Now;

            var business = new BusinessServices().GetBusinessModel(user, user.BusinessId, false).Model as BusinessModel;
            orderEmailModel.BusinessName = (business != null && business.BusinessName != null) ? business.BusinessName : "No Business Name";

            orderEmailModel.From = new MailAddress(Utilities.Config("dpo.sys.email.discountrequest"), "DPO Project Desk");

            orderEmailModel.To.Add(orderEmailModel.From);

            if (!string.IsNullOrEmpty(business.AccountManagerEmail))
            {
                orderEmailModel.To.Add(new MailAddress(business.AccountManagerEmail));
            }

            if (!string.IsNullOrEmpty(business.AccountOwnerEmail))
            {
                orderEmailModel.To.Add(new MailAddress(business.AccountOwnerEmail));
            }

            orderEmailModel.RenderTextVersion = true;
            orderEmailModel.BodyTextVersion   = RenderView(this, "SendEmailOrderApproval", orderEmailModel);

            orderEmailModel.RenderTextVersion = false;
            orderEmailModel.BodyHtmlVersion   = RenderView(this, "SendEmailOrderApproval", orderEmailModel);

            new EmailServices().SendEmail(orderEmailModel);
        }
示例#3
0
        /// <summary>
        /// Prototype to force to https - doesn't work well
        /// </summary>
        //protected void Application_BeginRequest()
        //{
        //	if ( !Context.Request.IsSecureConnection
        //		&& !Context.Request.IsLocal // to avoid switching to https when local testing
        //		)
        //	{
        //		Response.Clear();
        //		Response.Status = "301 Moved Permanently";
        //		Response.AddHeader( "Location", Context.Request.Url.ToString().Insert( 4, "s" ) );
        //		Response.End();
        //	}
        //}
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();

            Response.Clear();

            HttpException httpException = exception as HttpException;

            if (httpException != null)
            {
                RouteData routeData = new RouteData();
                routeData.Values.Add("controller", "Error");
                switch (httpException.GetHttpCode())
                {
                case 404:
                    // page not found
                    routeData.Values.Add("action", "HttpError404");
                    break;

                //case 400:
                //    // page not found
                //    routeData.Values.Add( "action", "HttpError404" );
                //    break;
                case 500:
                    // server error
                    routeData.Values.Add("action", "HttpError500");
                    break;

                default:
                    routeData.Values.Add("action", "General");
                    break;
                }
                routeData.Values.Add("error", exception);
                bool loggingError = true;
                if (exception.Message.IndexOf("Server cannot set status after HTTP headers;") > -1)
                {
                    loggingError = false;
                }
                string url = "MISSING";
                try
                {
                    HttpContext con = HttpContext.Current;
                    url = con.Request.Url.ToString();
                    url = url.Trim();
                }
                catch
                {
                    //skip
                }
                string lRefererPage = GetUserReferrer();
                var    user         = AccountServices.GetCurrentUser();
                string currentUser  = "******";
                if (user != null && user.Id > 0)
                {
                    currentUser = string.Format("User: {0} ({1})", user.FullName(), user.Id);
                }
                if (url.EndsWith("&") || url.EndsWith(";"))
                {
                    LoggingHelper.DoTrace(4, string.Format("Application_Error. url: {0} referer: {1}, currentUser: {2}, message: {3}", url.Trim(), lRefererPage, currentUser, exception.Message));
                    url = url.TrimEnd('&').Trim();
                    url = url.TrimEnd(';').Trim();
                    Response.Redirect(url, true);
                }
                else
                {
                    if (loggingError)
                    {
                        LoggingHelper.LogError(exception, string.Format("Application HttpException. url: {0}, Referer: {1}, currentUser: {2}", url, lRefererPage, currentUser));
                    }
                }
                // clear error on server ==> this would hide the error in dev as well
                //Server.ClearError();

                // at this point how to properly pass route data to error controller?
            }
            else
            {
                string url = "MISSING";
                try
                {
                    HttpContext con = HttpContext.Current;
                    url = con.Request.Url.ToString();
                    url = url.Trim();
                }
                catch
                {
                    //skip
                }
                string lRefererPage = "unknown";
                try
                {
                    if (Request.UrlReferrer != null)
                    {
                        lRefererPage = Request.UrlReferrer.ToString();
                    }
                }
                catch (Exception ex)
                {
                    //skip
                }
                var user = AccountServices.GetUserFromSession();
                LoggingHelper.LogError(exception, string.Format("Application Exception. url: {0}, Referer: {1}, currentUser: {2}", url, lRefererPage, user));
            }
        }
示例#4
0
        public PartialViewResult _OrderDetail(int?Id, string pageSessionToken)
        {
            ViewBag.cases = false;
            DateTime?exp_dte = null;
            var      orderId = 0;

            if (!string.IsNullOrEmpty(Request.Params["OrderID"]))
            {
                orderId = int.Parse(Request.Params["OrderID"]);
            }
            if (Request.Params["exp_date"] != "")
            {
                exp_dte = DateTime.Parse(Request.Params["exp_date"].ToString());
            }

            var value = int.Parse(Request.Params["did"] ?? "0");

            if (Request.Params["rec_qty"] != null)
            {
                ViewBag.RecQty = Request.Params["rec_qty"].ToString();
            }

            ViewBag.Products        = new SelectList(_productServices.GetAllValidProductMasters(CurrentTenantId), "ProductId", "NameWithCode");
            ViewBag.ProductAccounts = new SelectList(new List <ProductAccountCodes>(), "ProdAccCodeID", "ProdAccCode");

            if (!string.IsNullOrEmpty(Request.Params["account"]))
            {
                var accountId = int.Parse(Request.Params["account"]);
                var data      =
                    (from pac in AccountServices.GetAllProductAccountCodesByAccount(accountId)
                     select new
                {
                    pac.ProdAccCodeID,
                    pac.ProdAccCode
                }).ToList();
                ViewBag.ProductAccounts = new SelectList(data, "ProdAccCodeID", "ProdAccCode");
            }
            if (!string.IsNullOrEmpty(Request.Params["product"]))
            {
                var productid = int.Parse(Request.Params["product"]);
                var product   = _productServices.GetProductMasterById(productid);
                if (product != null)
                {
                    ViewBag.ProductCurrentPrice = product.SellPrice;
                }
            }

            ViewBag.GlobalWarranties = new SelectList(LookupServices.GetAllTenantWarrenties(CurrentTenantId), "WarrantyID", "WarrantyName");

            var taxes = (from gtax in LookupServices.GetAllValidGlobalTaxes(CurrentTenant.CountryID)
                         select new
            {
                TaxId = gtax.TaxID,
                TaxName = gtax.TaxName + " - " + gtax.PercentageOfAmount + " %"
            }).ToList();

            ViewBag.GlobalTaxes = new SelectList(taxes, "TaxId", "TaxName");

            if (value == 0)
            {
                ViewBag.IsTransferOrderAdd = true;
                return(PartialView("Create", new OrderDetailSessionViewModel
                {
                    ExpectedDate = exp_dte,
                    OrderID = !string.IsNullOrEmpty(Request.Params["oid"]) ? (int.Parse(Request.Params["oid"])) : orderId,
                    TenentId = CurrentTenantId,
                    WarehouseId = CurrentWarehouseId
                }));
            }
            else
            {
                if (Request.UrlReferrer.AbsolutePath.Contains("ProcessOrder"))
                {
                    var cObject = OrderService.GetOrderDetailsById(value);
                    ViewBag.productId = cObject.ProductId;
                    var product = _productServices.GetProductMasterById(cObject.ProductId);

                    ViewBag.cases       = product?.ProcessByCase;
                    ViewBag.processcase = product?.ProductsPerCase == null ? 1 : product.ProductsPerCase;
                    if (product?.ProcessByCase != null && product?.ProcessByCase == true)
                    {
                        ViewBag.caseProcess = (cObject.Qty / (product?.ProductsPerCase == null ? 1 : product.ProductsPerCase));
                    }
                    var cOrderSessionViewModel = AutoMapper.Mapper.Map(cObject, new OrderDetailSessionViewModel());
                    return(PartialView("Create", cOrderSessionViewModel));
                }

                var odList = GaneOrderDetailsSessionHelper.GetOrderDetailSession(pageSessionToken);

                var model = odList.FirstOrDefault(a => a.OrderDetailID == value && a.IsDeleted != true);
                if (model != null)
                {
                    ViewBag.productId = model.ProductId;
                    var product = _productServices.GetProductMasterById(model.ProductId);
                    ViewBag.cases       = product?.ProcessByCase;
                    ViewBag.processcase = product?.ProductsPerCase == null ? 1 : product.ProductsPerCase;
                    if (product?.ProcessByCase != null && product?.ProcessByCase == true)
                    {
                        ViewBag.caseProcess = (model.Qty / (product?.ProductsPerCase == null ? 1 : product.ProductsPerCase));
                    }
                }
                if (model == null)
                {
                    model = new OrderDetailSessionViewModel()
                    {
                        OrderID = orderId
                    };
                    ViewBag.IsTransferOrderAdd = true;
                }

                return(PartialView("Create", model));
            }
        }
        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            HttpPageHelper.IsValidRequest = true;
            HttpPageHelper.CurrentItem    = null;

            var p = new PageServices().GetPageByURL(VirtualPath);

            HttpPageHelper.CurrentPage = p;

            string accountName = HttpUtility.HtmlDecode((string)requestContext.RouteData.Values["accountname"]);
            string accountID   = HttpUtility.HtmlDecode((string)requestContext.RouteData.Values["accountid"]);
            string contactID   = HttpUtility.HtmlDecode((string)requestContext.RouteData.Values["contactID"]);

            if (!string.IsNullOrEmpty(contactID))
            {
                var contact = new AccountServices().GetContactByID(Convert.ToInt32(contactID));
                if (contact != null && contact.ID > 0)
                {
                    var item = new Item();
                    item.Description           = "";
                    contact.URL                = "/Accounts/Name=" + contact.ContactAccount.Name.Replace(" ", "-") + "/Contacts/ID=" + contact.ID.ToString();
                    item.URL                   = "/Accounts/Name=" + contact.ContactAccount.Name.Replace(" ", "-") + "/Contacts/ID=" + contact.ID.ToString();
                    item.Name                  = contact.FirstName + " " + contact.LastName + " - " + contact.ContactAccount.Name + " Contact";
                    contact.Name               = item.Name;
                    item.ItemReference         = contact;
                    HttpPageHelper.CurrentItem = item;
                }
            }
            else if (!string.IsNullOrEmpty(accountName))
            {
                var a = new AccountRepository().GetByName(accountName.Replace("-", " "));
                a.Description = a.EmailDomain;
                var item = new Item();
                item.Description           = a.EmailDomain;
                item.URL                   = "/Accounts/Name=" + a.Name.Replace(" ", "-");
                a.URL                      = "/Accounts/Name=" + a.Name.Replace(" ", "-");
                item.Name                  = a.Name + " - " + p.Title;
                item.ItemReference         = a;
                HttpPageHelper.CurrentItem = item;
            }
            else if (!string.IsNullOrEmpty(accountID))
            {
                var a = new AccountRepository().GetByID(Convert.ToInt32(accountID), false);
                a.Description = a.EmailDomain;
                var item = new Item();
                item.Description           = a.EmailDomain;
                item.URL                   = "/Accounts/Name=" + a.Name.Replace(" ", "-");
                a.URL                      = "/Accounts/Name=" + a.Name.Replace(" ", "-");
                item.Name                  = a.Name + " - " + p.Title;
                item.ItemReference         = a;
                HttpPageHelper.CurrentItem = item;
            }
            else
            {
                var item = new Item();
                item.Description           = p.Name;
                item.Name                  = p.Title;
                item.URL                   = "/Accounts";
                item.ItemReference         = item;
                HttpPageHelper.CurrentItem = item;
            }



            InsightBasePage page;

            page = (InsightBasePage)BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(System.Web.UI.Page));

            HttpPageHelper.IsValidRequest = true;
            return(page);
        }
示例#6
0
 public TestsUserAccounts()
 {
     service = new AccountServices(this.TContext);
 }
 public BankAccountRepository()
 {
     _database       = new LinqDataDataContext();
     _accountService = new AccountServices();
 }
示例#8
0
 public AccountController()
 {
     _service = new AccountServices();
 }
示例#9
0
        static void Main(string[] args)
        {
            AccountServices services = new AccountServices();

            services.Test();
        }
示例#10
0
        public void Execute(IJobExecutionContext context)
        {
            QueuedSMSServices     _queuedSMSService     = ServiceProvider.GetQueuedSMSServices();
            UserServices          _userService          = ServiceProvider.GetUserServices();
            ClientServices        _clientService        = ServiceProvider.GetClientServices();
            AccountServices       _savingService        = ServiceProvider.GetAccountServices();
            PaymentMethodServices _paymentMethodService = ServiceProvider.GetPaymentMethodServices();

            var generalSettingsService = ServiceProvider.GetApplicationSettingsServices();

            Log.Info("Executing sms charges job");

            var queuedsms = _queuedSMSService.GetUncharged();

            Log.Debug("");
            Log.Debug("-------------------------------------");
            Log.Info("Charging SMS");
            Log.Debug("Uncharged sms count: " + queuedsms.Count);

            decimal smsCharge = Convert.ToDecimal(generalSettingsService.SelectParameterValue(OGeneralSettings.SMS_CHARGE));

            var adminUser     = _userService.Find(1);
            var paymentMethod = _paymentMethodService.GetPaymentMethodByName("Cash");

            foreach (QueuedSMS qe in queuedsms)
            {
                try
                {
                    if (qe.ContractId.HasValue && qe.Charged.HasValue && !qe.Charged.Value)
                    {
                        SavingBookContract _saving = (SavingBookContract)_savingService.GetSaving(qe.ContractId.Value);

                        //Get all sms for same saving book contract
                        var smsGroup = _queuedSMSService.FindByContractId(_saving.Id);

                        string description = "";

                        string formatedAccountNumber = "******" + _saving.Code.Substring(_saving.Code.Length - 4);

                        OCurrency SMSCharges = smsGroup.Count * smsCharge;

                        if (smsGroup.Count > 0)
                        {
                            string   desc  = "SMS charges of {0:.00} for {1:dd.MM.yyyy} - {2:dd.MM.yyyy} : {3}";
                            object[] items = new object[] { SMSCharges.GetFormatedValue(true), smsGroup.First().CreatedOnUtc, smsGroup.Last().CreatedOnUtc, formatedAccountNumber };
                            description = string.Format(desc, items);
                        }
                        if (smsGroup.Count == 0)
                        {
                            string   desc  = "SMS charges of {0:.00} for {1:dd.MM.yyyy} : {3}";
                            object[] items = new object[] { SMSCharges.GetFormatedValue(true), smsGroup.First().CreatedOnUtc, formatedAccountNumber };
                            description = string.Format(desc, items);
                            smsGroup.First().Charged = true;
                        }
                        _savingService.Withdraw(_saving, DateTime.Now, SMSCharges, true, description, "", adminUser,
                                                Teller.CurrentTeller, paymentMethod);

                        qe.Charged = true;
                        foreach (var sms in smsGroup)
                        {
                            sms.Charged = true;
                            if (queuedsms.Where(s => s.Id == sms.Id).FirstOrDefault() != null)
                            {
                                queuedsms.Where(s => s.Id == sms.Id).FirstOrDefault().Charged = true;
                            }
                            _queuedSMSService.Update(sms);
                        }

                        //Send sms charge notification
                        Person person = _clientService.FindPersonById(qe.RecipientId.Value);
                        if (person != null)
                        {
                            if (person.SmsDelivery.HasValue && person.SmsDelivery.Value)
                            {
                                string mfbName = Convert.ToString(generalSettingsService.SelectParameterValue(OGeneralSettings.MFI_NAME));
                                //var message = messageTemplate.Body;
                                var messageReplaced = mfbName + " " + description;// Tokenizer.Replace(message, tokens, false);

                                var sms = new QueuedSMS()
                                {
                                    From         = Convert.ToString(generalSettingsService.SelectParameterValue(OGeneralSettings.SMS_FROM_NUMBER)),
                                    Recipient    = person.PersonalPhone,
                                    RecipientId  = person.Id,
                                    ContractId   = _saving != null ? _saving.Id : 0,
                                    Charged      = true,
                                    Message      = messageReplaced,
                                    SentTries    = 0,
                                    CreatedOnUtc = DateTime.UtcNow,
                                };

                                _queuedSMSService.Add(sms);
                            }
                        }
                    }
                }
                catch (Exception exc)
                {
                    Log.Error(string.Format("Error charging sms: {0}", exc.Message), exc);
                }
                finally
                {
                }
            }
        }
示例#11
0
 public CarsController(IAllCars iAllCars, ICarsCategory iCarsCat, AccountServices carsContext)
 {
     _allCars       = iAllCars;
     _allCategories = iCarsCat;
     _context       = carsContext;
 }
示例#12
0
 public void DeleteAccount(Account account)
 {
     AccountServices.Delete(account);
     SearchAccount();
 }
示例#13
0
 public int GetCountAccount() => AccountServices.GetTotalCountWithName(ContentSearch);
示例#14
0
 public HomeController()
 {
     service = new AccountServices();
 }
        private void SendApprovalRejectionEmailForCommissionRequest(CommissionRequestModel model)
        {
            var emailModel = new SendEmailApprovalModel();

            emailModel.HelpLink = "mailto:[email protected]";

            emailModel.Subject = string.Format("The status of a DPO Commission request has changed");

            emailModel.Reason       = model.ResponseNotes;
            emailModel.ProjectId    = model.ProjectId;
            emailModel.ProjectName  = model.Project.Name;
            emailModel.QuoteTitle   = model.Quote.Title;
            emailModel.TotalNet     = model.Quote.TotalNet;
            emailModel.Approved     = (model.CommissionRequestStatusTypeId == (byte)CommissionRequestStatusTypeEnum.Approved);
            emailModel.ModifierName = model.CommissionRequestStatusModifiedBy;


            UserSessionModel user = new UserSessionModel();

            if (model.ProjectOwnerId != null)
            {
                user = new AccountServices().GetUserSessionModel(model.ProjectOwnerId.Value).Model as UserSessionModel;
            }
            else
            {
                user = new AccountServices().GetUserSessionModel(model.Project.OwnerId.Value).Model as UserSessionModel;
            }

            emailModel.ProjectOwnerName = user.FirstName + " " + user.LastName;
            emailModel.ProjectDate      = model.Project.ProjectDate;

            var business = new BusinessServices().GetBusinessModel(user, user.BusinessId, false).Model as BusinessModel;

            emailModel.BusinessName                  = business.BusinessName;
            emailModel.RequestedCommission           = model.RequestedCommissionTotal;
            emailModel.ApprovedCommission            = model.ApprovedCommissionTotal;
            emailModel.ApprovedTotalCommission       = model.ApprovedCommissionPercentage;
            emailModel.RequestedCommissionPercentage = model.RequestedCommissionPercentage;
            emailModel.ApprovedCommissionPercentage  = model.ApprovedCommissionPercentage;
            emailModel.RequestedMultiplier           = model.RequestedMultiplier;
            emailModel.ApprovedMultiplier            = model.ApprovedMultiplier;
            emailModel.ApprovedTotalNet              = model.TotalRevised;
            emailModel.TotalNet  = model.Quote.TotalNet;
            emailModel.TotalList = model.Quote.TotalList;

            emailModel.From = new MailAddress(Utilities.Config("dpo.sys.email.commissionrequest"), "DPO Project Desk");

            if (model.ShouldSendEmail == true)
            {
                emailModel.To.Add(new MailAddress(user.Email, user.DisplayName));
            }

            emailModel.To.Add(emailModel.From);

            if (!string.IsNullOrEmpty(business.AccountManagerEmail))
            {
                emailModel.To.Add(new MailAddress(business.AccountManagerEmail));
            }

            if (!string.IsNullOrEmpty(business.AccountOwnerEmail))
            {
                emailModel.To.Add(new MailAddress(business.AccountOwnerEmail));
            }

            List <string> emailsList = new List <string>();

            if (model.EmailsList != null && model.EmailsList.Length > 0)
            {
                emailsList = model.EmailsList.ToString().Split(',', ';').ToList();
            }

            foreach (string email in emailsList)
            {
                if (String.IsNullOrWhiteSpace(email))
                {
                    continue;
                }
                emailModel.To.Add(new MailAddress(email.Trim()));
            }

            emailModel.RenderTextVersion = true;
            emailModel.BodyTextVersion   = RenderView(this, "SendEmailCommissionRequestApproval", emailModel);

            emailModel.RenderTextVersion = false;
            emailModel.BodyHtmlVersion   = RenderView(this, "SendEmailCommissionRequestApproval", emailModel);

            new EmailServices().SendEmail(emailModel);
        }
示例#16
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            LoggingHelper.DoTrace(5, "AccountController.ExternalLoginConfirmation - enter ");

            if (User.Identity.IsAuthenticated)
            {
                LoggingHelper.DoTrace(5, "AccountController.ExternalLoginConfirmation - user is already authenticated ");

                return(RedirectToAction("Index", "Manage"));
            }
            string statusMessage = "";

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    //return View( "ExternalLoginFailure" );
                    return(RedirectToAction("ExternalLoginFailure"));
                }
                //todo - may change to not persist the names
                var user = new ApplicationUser
                {
                    UserName  = model.Email,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName
                };
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    //add mirror account
                    new AccountServices().Create(model.Email,
                                                 model.FirstName, model.LastName,
                                                 model.Email,
                                                 user.Id,
                                                 "",
                                                 ref statusMessage, false, true);

                    result = await UserManager.AddLoginAsync(user.Id, info.Login);

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

                        //get user and add to session (TEMP)
                        //or only do on demand?
                        AccountServices.GetUserByKey(user.Id);

                        return(RedirectToLocal(returnUrl));
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            //return View( model );
            return(View("~/Views/Account/ExternalLoginConfirmation.cshtml", model));
        }
示例#17
0
 public HomeController(AppDbContext context, AccountServices accountServices)
 {
     _context         = context;
     _accountServices = accountServices;
 }
示例#18
0
        public async Task <ActionResult> CE_Login(string nextUrl)
        {
            // check for token
            string token = Request.Params["Token"];

            if (string.IsNullOrWhiteSpace(token))
            {
                SiteMessage msg = new SiteMessage()
                {
                    Title = "Authorization Failed"
                };
                msg.Message = "A valid authorization token was not found.";
                Session["SystemMessage"] = msg;
                return(RedirectToAction("Index", "Message"));
            }
            LoggingHelper.DoTrace(6, "CE_Login - start");
            string publisherSecretToken = UtilityManager.GetAppKeyValue("finderSecretToken");
            var    output = new ApiResult();
            var    accountsAuthorizeApi = UtilityManager.GetAppKeyValue("accountsAuthorizeApi") + "?Token=" + token + "&Secret=" + publisherSecretToken;

            try
            {
                LoggingHelper.DoTrace(6, "CE_Login - MakeAuthorizationRequest");
                string    rawData = MakeAuthorizationRequest(accountsAuthorizeApi);
                ApiResult data    = new ApiResult();
                //check rawdata for {"data"
                //&& rawData.ToLower().IndexOf( "{\"data\"" ) > 0
                if (rawData != null)
                {
                    data = new JavaScriptSerializer().Deserialize <ApiResult>(rawData);
                    if (data == null)
                    {
                        SiteMessage msg = new SiteMessage()
                        {
                            Title = "Authorization Failed"
                        };
                        msg.Message = "A valid authorization token was not found.";
                        Session["SystemMessage"] = msg;
                        return(RedirectToAction("Index", "Message"));
                    }
                    else
                    {
                        //do error checking, for error, and existing user.
                        if (data.valid == false)
                        {
                            SiteMessage msg = new SiteMessage()
                            {
                                Title = "Authorization Failed"
                            };
                            msg.Message = "Reason: " + data.status;
                            Session["SystemMessage"] = msg;
                            return(RedirectToAction("Index", "Message"));
                        }
                    }
                    LoggingHelper.DoTrace(6, "CE_Login - MakeAuthorizationRequest - data is OK");
                }
                else
                {
                    //check for error string
                    //{"data":null,"valid":false,"status":"Error: Invalid token","extra":null}
                    SiteMessage msg = new SiteMessage()
                    {
                        Title = "Authorization Failed"
                    };
                    msg.Message = "A valid authorization token was not found.</br>" + rawData;
                    Session["SystemMessage"] = msg;
                    return(RedirectToAction("Index", "Message"));
                }
                nextUrl = string.IsNullOrWhiteSpace(nextUrl) ? "~/credentials" : nextUrl;
                //19-12-17 mp - uncommented this:
                nextUrl = UtilityManager.FormatAbsoluteUrl(nextUrl);

                string statusMessage = "";
                //now what
                //login user like external
                //				AppUser user = AccountServices.GetUserByUserName( data.data.Email );

                AccountServices acctServices = new AccountServices();
                LoggingHelper.DoTrace(6, "CE_Login - GetUserByCEAccountId");
                AppUser user = AccountServices.GetUserByCEAccountId(data.data.AccountIdentifier);
                //note user may not yet exist here,
                if (user == null || user.Id == 0)
                {
                    LoggingHelper.DoTrace(4, string.Format("Account.CE_Login. First time login for {0} {1}", data.data.FirstName, data.data.LastName));

                    //will eventually not want to use AspNetUsers
                    var newUser = new ApplicationUser
                    {
                        UserName  = data.data.Email,
                        Email     = data.data.Email,
                        FirstName = data.data.FirstName,
                        LastName  = data.data.LastName
                    };
                    var result = await UserManager.CreateAsync(newUser);

                    if (result.Succeeded)
                    {
                        //add mirror account
                        acctServices.Create(data.data.Email,
                                            data.data.FirstName, data.data.LastName,
                                            data.data.Email,
                                            newUser.Id,
                                            "",
                                            data.data.AccountIdentifier,
                                            ref statusMessage, false, true);
                        UserLoginInfo     info  = new UserLoginInfo("CredentialEngine", data.data.AccessToken);
                        ExternalLoginInfo einfo = new ExternalLoginInfo()
                        {
                            DefaultUserName = data.data.Email, Email = data.data.Email, Login = info
                        };
                        result = await UserManager.AddLoginAsync(newUser.Id, info);

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

                            //now get user and add to session, will include any orgs if found
                            AppUser thisUser = AccountServices.GetUserByCEAccountId(data.data.AccountIdentifier);
                            //get organizations
                            GetOrganizationsForUser(thisUser);
                            return(RedirectToLocal(nextUrl));
                            //return RedirectToAction( "Index", "Search" );
                        }
                    }
                    AddErrors(result);
                    ConsoleMessageHelper.SetConsoleErrorMessage("Error - unexpected issue encountered attempting to sign in.<br/>" + result);
                    LoggingHelper.DoTrace(6, "CE_Login - Error - unexpected issue encountered attempting to add user.<br/>" + result);
                    //where to go for errors?
                }
                else
                {
                    //may want to compare user, and update as needed
                    if (user.Email != data.data.Email ||
                        user.FirstName != data.data.FirstName ||
                        user.LastName != data.data.LastName)
                    {
                        //update user
                        user.Email     = data.data.Email;
                        user.FirstName = data.data.FirstName;
                        user.LastName  = data.data.LastName;

                        acctServices.Update(user, false, ref statusMessage);
                    }
                    LoggingHelper.DoTrace(6, "CE_Login - existing user");
                    ApplicationUser aspUser = this.UserManager.FindByEmail(data.data.Email.Trim());
                    await SignInManager.SignInAsync(aspUser, isPersistent : false, rememberBrowser : false);

                    AppUser thisUser = AccountServices.SetUserByEmail(aspUser.Email);
                    if (thisUser != null && thisUser.Id > 0)
                    {
                        //get organizations - currently only those who can create widgets
                        GetOrganizationsForUser(thisUser);
                    }
                    ActivityServices.UserExternalAuthentication(appUser, "CE SSO");
                    string message = string.Format("Email: {0}, provider: {1}", data.data.Email, "CE SSO");
                    LoggingHelper.DoTrace(5, "AccountController.CE_Login: "******"CE_Login Unable to login user");
            }

            return(View());
        }
示例#19
0
 void CallHandler_CloudGoodsInitilized()
 {
     AccountServices.Login(new LoginRequest(CloudGoodsSettings.ExpSceneUserName, CloudGoodsSettings.ExpScenePassword), OnRegisteredtoSession);
 }
示例#20
0
        public ActionResult BlindShipment(bool?delivery)
        {
            if (!caSession.AuthoriseSession())
            {
                return(Redirect((string)Session["ErrorUrl"]));
            }

            var accounts = AccountServices.GetAllValidAccounts(CurrentTenantId).Select(acnts => new
            {
                acnts.AccountID,
                acnts.AccountNameCode
            }).ToList();

            ViewBag.AccountID        = new SelectList(accounts, "AccountID", "AccountNameCode");
            ViewBag.AccountAddresses = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = "Select", Value = "0"
                }
            };
            ViewBag.ShowPriceInBlindShipment = caCurrent.CurrentWarehouse().ShowPriceInBlindShipment;
            ViewBag.ShowTaxInBlindShipment   = caCurrent.CurrentWarehouse().ShowTaxInBlindShipment;
            ViewBag.ShowQtyInBlindShipment   = caCurrent.CurrentWarehouse().ShowQtyInBlindShipment;
            ViewBag.ProductGroup             = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = "Select Group", Value = "0"
                }
            };
            ViewBag.ProductDepartment = new List <SelectListItem>()
            {
                new SelectListItem()
                {
                    Text = "Select Department", Value = "0"
                }
            };
            ViewBag.Groups      = new SelectList(LookupServices.GetAllValidProductGroups(CurrentTenantId), "ProductGroupId", "ProductGroup");
            ViewBag.Departments = new SelectList(LookupServices.GetAllValidTenantDepartments(CurrentTenantId), "DepartmentId", "DepartmentName");
            var taxes = (from gtax in LookupServices.GetAllValidGlobalTaxes(CurrentTenant.CountryID)
                         select new
            {
                TaxId = gtax.TaxID,
                TaxName = gtax.TaxName + " - " + gtax.PercentageOfAmount + " %"
            }).ToList();

            ViewBag.GlobalTaxes = new SelectList(taxes, "TaxId", "TaxName");
            ViewBag.DeliveryNo  = GaneStaticAppExtensions.GenerateDateRandomNo();
            Session["bsList"]   = new List <BSDto>();
            if (delivery != null && delivery == true)
            {
                ViewBag.type     = (int)InventoryTransactionTypeEnum.SalesOrder;
                ViewBag.Title    = "Create Delivery";
                ViewBag.delivery = delivery;
                return(View());
            }

            ViewBag.Title = "Create Shipment";
            ViewBag.type  = (int)InventoryTransactionTypeEnum.PurchaseOrder;
            return(View());
        }
示例#21
0
 public AccountServicesDataAccessTests(ITestOutputHelper testOutputHelper)
 {
     connectionString      = Properties.Settings.Default.connectionStr;
     accountService        = new AccountServices(new AccountRepository(connectionString), new ModelDataAnnotationCheck());
     this.testOutputHelper = testOutputHelper;
 }
        public ActionResult CreatePostTrans(string id, FormCollection collection)
        {
            try
            {
                AccountServices service = new AccountServices();
                string          name    = collection["name"];
                if (service.checkName(name) == true)
                {
                    return(Content("<script language='javascript' type='text/javascript'>alert('Name Already Exists , Try Again with diffrent name !');</script>"));
                }


                int identity = int.Parse(id);


                SubHeadAccount     sub   = service.findSubHeadAcc(identity);
                TransactionAccount trans = new TransactionAccount();

                trans.type_ = collection["Type"];
                if (collection["OB"] == "Cr.")
                {
                    trans.cr_     = Convert.ToInt32(collection["amount"]);
                    trans.dr_     = 0;
                    trans.balance = trans.cr_ * (-1);
                }
                else
                {
                    trans.dr_     = Convert.ToInt32(collection["amount"]);
                    trans.cr_     = 0;
                    trans.balance = trans.dr_;
                }
                trans.head_id        = sub.head_id;
                trans.main_id        = sub.main_id;
                trans.sub_head_id    = sub.sub_head_id;
                trans.description    = "Opening new Account";
                trans.WEIGHT         = collection["weight"];
                trans.opening_weight = trans.WEIGHT;
                trans.name           = collection["name"];
                trans.is_active      = "Y";

                trans.updated_at_ = DateTime.UtcNow;
                trans.created_at_ = Convert.ToDateTime(collection["date"]);
                // for Opening Balance store
                trans.parent = trans.balance.ToString();
                trans.code   = "0";
                service.addTransAcc(trans);
                // AccountServices.addRistrictedAccount(trans.name);

                trans.code = "0" + trans.main_id + "00" + trans.head_id + "000" + trans.sub_head_id + "0000" + trans.id;
                service.save();
                if (sub.sub_head_id == 34) // finished good inventories id
                {
                    SubHeadAccount subHead = new SubHeadAccount();
                    subHead.head_id    = 16;
                    subHead.main_id    = 12;
                    subHead.parent     = "Sales of Products";
                    subHead.code       = "0" + sub.main_id + "00" + sub.head_id + "000";
                    subHead.name       = collection["name"] + " Sale ";
                    subHead.is_active  = "Y";
                    subHead.update_at  = DateTime.UtcNow;
                    subHead.created_at = DateTime.UtcNow;
                    service.addSubHeadAcc(subHead);
                    service.save();

                    subHead.code = subHead.sub_head_id.ToString();
                    subHead.code = "0" + sub.main_id + "00" + sub.head_id + "000" + sub.sub_head_id;
                    TransactionAccount transNew = new TransactionAccount();
                    transNew.type_       = "income";
                    transNew.cr_         = 0;
                    transNew.dr_         = 0;
                    transNew.balance     = 0;
                    transNew.head_id     = 16;
                    transNew.sub_head_id = subHead.sub_head_id;
                    transNew.main_id     = 12;
                    transNew.description = "Opening new Account";
                    transNew.name        = collection["name"] + " Sale " + " Account ";
                    transNew.is_active   = "Y";

                    transNew.updated_at_    = DateTime.UtcNow;
                    transNew.created_at_    = Convert.ToDateTime(collection["date"]);
                    transNew.code           = "0";
                    transNew.WEIGHT         = trans.WEIGHT;
                    transNew.opening_weight = trans.opening_weight;
                    service.addTransAcc(transNew);
                    transNew.code            = "0" + transNew.main_id + "00" + transNew.head_id + "000" + transNew.sub_head_id + "0000" + transNew.id;
                    transNew.sale_account_id = trans.id;
                    transNew.parent          = trans.parent;
                    service.save();
                    trans.sale_account_id = transNew.id;
                    service.save();
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                                               validationErrors.Entry.Entity.GetType().FullName,
                                               validationError.PropertyName,
                                               validationError.ErrorMessage);
                    }
                }
            }
            return(RedirectToAction("Index"));
        }
示例#23
0
 public CustomerController(ILogger <HomeController> logger, ApplicationDbContext dbContext, IAccountsRepository accountRepository,
                           ICustomersRepository customersRepository, IDispositionsRepository dispositionsRepository, ITransactionsRepository transactionsRepository, CustomerSearchService searchService, AccountServices accountServices, ViewModelsService viewmodelsServices)
 {
     _logger                 = logger;
     this.dbContext          = dbContext;
     _accountsRepository     = accountRepository;
     _customersRepository    = customersRepository;
     _dispositionsRepository = dispositionsRepository;
     _transactionsRepository = transactionsRepository;
     _customerSearchService  = searchService;
     _accountServices        = accountServices;
     _viewmodelsServices     = viewmodelsServices;
 }
示例#24
0
        private void BSaveClick(object sender, EventArgs e)
        {
            nudAmount_ValueChanged(sender, e);
            bool pending = cbxPending.Visible && cbxPending.Checked;
            bool?local   = null;

            local = rbxLocal.Visible && rbxLocal.Checked;

            try
            {
                _date = new DateTime(dtpDate.Value.Year, dtpDate.Value.Month, dtpDate.Value.Day, TimeProvider.Now.Hour,
                                     TimeProvider.Now.Minute, TimeProvider.Now.Second);

                AccountServices savingServices = ServicesProvider.GetInstance().GetAccountServices();

                if (_saving.Events.Find(ev => ev.Code == OSavingEvents.SavingClosure &&
                                        ev.Date.Date >= _date.Date && ev is SavingClosureEvent) != null)
                {
                    savingServices.CanPostAfterClosureEvent();
                }

                List <SavingEvent> savingEvents = new List <SavingEvent>();

                if (_date.Date < TimeProvider.Today.Date)
                {
                    savingServices.PerformBackDateOperations(_date);
                }
                else if (_date.Date > TimeProvider.Today.Date)
                {
                    savingServices.PerformFutureDateOperations(_date);
                }

                if (_saving.HasPendingEvents())
                {
                    if (!savingServices.AllowOperationsDuringPendingDeposit())
                    {
                        return;
                    }
                }

                if ((_flatFees.HasValue && updAmountFees.Value != _flatFees) || (_rateFees.HasValue && updAmountFees.Value != (decimal)(_rateFees * 100)))
                {
                    if (!savingServices.AllowSettingSavingsOperationsFeesManually())
                    {
                        return;
                    }
                }

                switch (_bookingDirection)
                {
                case OSavingsOperation.Credit:
                {
                    OSavingsMethods savingsMethod =
                        (OSavingsMethods)
                        Enum.Parse(typeof(OSavingsMethods), "Cash");
                    var paymentMethod = (PaymentMethod)cbSavingsMethod.SelectedItem;
                    if (_saving is SavingBookContract)
                    {
                        if (savingsMethod == OSavingsMethods.Cheque)
                        {
                            ((SavingBookContract)_saving).ChequeDepositFees = updAmountFees.Value;
                        }
                        else
                        {
                            ((SavingBookContract)_saving).DepositFees = updAmountFees.Value;
                        }

                        //modified
                        OCurrency dutyStampFeeMin = Convert.ToDecimal(ApplicationSettings.GetInstance("").GetSpecificParameter(OGeneralSettings.STAMP_DUTY_VALID_ABOVE));
                        if (_amount < dutyStampFeeMin)
                        {
                            ((SavingBookContract)_saving).DutyStampFees = 0;
                        }
                    }

                    savingEvents = savingServices.Deposit(_saving, _date, _amount, _description, _referenceNumber, User.CurrentUser, pending, local,
                                                          savingsMethod, paymentMethod, null, Teller.CurrentTeller);
                    break;
                }

                case OSavingsOperation.Debit:
                {
                    var paymentMethod = (PaymentMethod)cbSavingsMethod.SelectedItem;
                    if (_saving is SavingBookContract)
                    {
                        if (_flatFees.HasValue)
                        {
                            ((SavingBookContract)_saving).FlatWithdrawFees = updAmountFees.Value;
                        }
                        else
                        {
                            ((SavingBookContract)_saving).RateWithdrawFees = (double)(updAmountFees.Value / 100);
                        }


                        OCurrency _feesMin, _feesMax;
                        decimal   value = _flatAMFees.HasValue ? _flatAMFees.Value : ((decimal)(_rateAMFees)) * 100;

                        if (((SavingsBookProduct)_saving.Product).FlatAMFees.HasValue ||
                            ((SavingsBookProduct)_saving.Product).FlatAMFeesMin.HasValue)
                        {
                            if (((SavingsBookProduct)_saving).FlatAMFees.HasValue)
                            {
                                _feesMin = ((SavingsBookProduct)_saving.Product).FlatAMFees;
                                _feesMax = ((SavingsBookProduct)_saving.Product).FlatAMFees;
                            }
                            else
                            {
                                _feesMin = ((SavingsBookProduct)_saving.Product).FlatAMFeesMin;
                                _feesMax = ((SavingsBookProduct)_saving.Product).FlatAMFeesMax;
                            }

                            OCurrency amFee = value <_feesMin || value> _feesMax ? _feesMin : value;
                            ((SavingBookContract)_saving).FlatAMFees = amFee;
                        }
                        else
                        {
                            if (((SavingsBookProduct)_saving.Product).RateAMFees.HasValue)
                            {
                                _feesMin = (decimal)((SavingsBookProduct)_saving.Product).RateAMFees * 100;
                                _feesMax = (decimal)((SavingsBookProduct)_saving.Product).RateAMFees * 100;
                            }
                            else
                            {
                                _feesMin = (decimal)((SavingsBookProduct)_saving.Product).RateAMFeesMin * 100;
                                _feesMax = (decimal)((SavingsBookProduct)_saving.Product).RateAMFeesMax * 100;
                            }

                            var amFee = value <_feesMin || value> _feesMax ? _feesMin : value;
                            ((SavingBookContract)_saving).RateAMFees = (double)(amFee.Value / 100);
                        }
                    }

                    savingEvents = savingServices.Withdraw(_saving, _date, _amount, _description, _referenceNumber, User.CurrentUser,
                                                           Teller.CurrentTeller, paymentMethod);
                    break;
                }

                case OSavingsOperation.Transfer:
                {
                    if (_saving is SavingBookContract)
                    {
                        if (_flatFees.HasValue)
                        {
                            ((SavingBookContract)_saving).FlatTransferFees = updAmountFees.Value;
                        }
                        else
                        {
                            ((SavingBookContract)_saving).RateTransferFees = (double)(updAmountFees.Value / 100);
                        }
                    }
                    decimal fee = nudTotalAmount.Value - nudAmount.Value;
                    savingEvents = savingServices.Transfer(_saving, _savingTarget, _date, _amount, fee, _description, _referenceNumber,
                                                           User.CurrentUser, false);
                    break;
                }

                case OSavingsOperation.SpecialOperation:
                {
                    OSavingsMethods savingsMethod =
                        (OSavingsMethods)
                        Enum.Parse(typeof(OSavingsMethods), ((PaymentMethod)cbSavingsMethod.SelectedItem).Name);
                    if (cbBookings.SelectedItem != null)
                    {
                        Booking booking = (Booking)cbBookings.SelectedItem;
                        booking.Branch = _saving.Branch;
                        savingServices.SpecialOperation(_saving, _date, _amount, _description, User.CurrentUser,
                                                        savingsMethod, rbxCredit.Checked, booking);
                        break;
                    }
                    throw new OpenCbsSavingException(OpenCbsSavingExceptionEnum.TransactionInvalid);
                }
                }


                try
                {
                    //slycode
                    MessagingService messagingService = new MessagingService(Person);

                    foreach (SavingEvent savingEvent in savingEvents)
                    {
                        if (!(savingEvent is SavingInstrumentFeeEvent ||
                              savingEvent is SavingSearchFeeEvent
                              //|| savingEvent is SavingDutyStampFeeEvent
                              || savingEvent is SavingAMFeeEvent))
                        {
                            messagingService.SendNotification(savingEvent, _saving, _bookingDirection.Description());
                        }
                    }
                }
                catch (Exception exc)
                {
                    new frmShowError(CustomExceptionHandler.ShowExceptionText(exc)).ShowDialog();
                }

                Close();
            }
            catch (Exception ex)
            {
                new frmShowError(CustomExceptionHandler.ShowExceptionText(ex)).ShowDialog();
            }
        }
示例#25
0
        public ActionResult SendEmailOrderSubmit(OrderViewModelLight orderVMLight)
        {
            log.InfoFormat("Involke SendEmailOrderSubmit ControllerAction");

            CreateOrderFormPdfForSendMail(orderVMLight);

            var emailModel = this.orderService.getOrderSendEmailModel(orderVMLight);

            emailModel.HelpLink = "mailto:[email protected]";

            var fromEmails = Utilities.Config("dpo.sys.email.ordersubmit").Split(',').ToList();

            if (orderVMLight.HasConfiguredModel)
            {
                emailModel.Subject = string.Format("BTO - An Order has been submitted by " + orderVMLight.BusinessName + " - Project: " + orderVMLight.ProjectName);
            }
            else
            {
                emailModel.Subject = string.Format("An Order has been submitted by " + orderVMLight.BusinessName + " - Project: " + orderVMLight.ProjectName);
            }


            emailModel.From = new MailAddress(fromEmails.First(), "DPO Order");

            foreach (string email in fromEmails)
            {
                emailModel.To.Add(new MailAddress(email, "Daikin Project Desk"));
            }

            //Todo: propery need to check for EmailAccount or EmailAccountManager is null
            //if model return null. maybe need to write code to reget it from db
            //currently it based on value of ViewModel.

            AccountServices  accountService  = new AccountServices();
            UserSessionModel admin           = accountService.GetUserSessionModel(orderVMLight.CreatedByUserId).Model as UserSessionModel;
            BusinessServices businessService = new BusinessServices();
            BusinessModel    businessModel   = businessService.GetBusinessModel(admin, admin.BusinessId).Model as BusinessModel;

            if (!string.IsNullOrEmpty(emailModel.AccountManagerEmail))
            {
                emailModel.To.Add(new MailAddress(emailModel.AccountManagerEmail));
            }
            else
            {
                var emailAccountManager = businessModel.AccountManagerEmail;
                if (emailAccountManager != null)
                {
                    emailModel.AccountManagerEmail = emailAccountManager;
                }
            }

            log.DebugFormat("Account Manager Email: {0}", emailModel.AccountManagerEmail);

            if (emailModel.AccountOwnerEmail != null)
            {
                emailModel.To.Add(new MailAddress(emailModel.AccountOwnerEmail));
            }
            else
            {
                var emailAccountOwner = businessModel.AccountOwnerEmail;
                if (emailAccountOwner != null)
                {
                    emailModel.AccountOwnerEmail = emailAccountOwner;
                }
            }

            if (CurrentUser.Email != null)
            {
                emailModel.To.Add(new MailAddress(CurrentUser.Email));
            }

            if (!string.IsNullOrEmpty(orderVMLight.ProjectOwnerId.ToString()))
            {
                UserServices userService  = new UserServices();
                var          projectOwner = userService.GetUserModel(CurrentUser, orderVMLight.ProjectOwnerId, true, true).Model as UserModel;
                if (projectOwner != null && !string.IsNullOrEmpty(projectOwner.Email))
                {
                    if (CurrentUser.Email != null && CurrentUser.Email != projectOwner.Email)
                    {
                        emailModel.To.Add(new MailAddress(projectOwner.Email));
                    }
                }
            }

            log.DebugFormat("AccountOwnerEmail: {0}", emailModel.AccountOwnerEmail);

            string root                    = Server.MapPath("~");
            string parent                  = System.IO.Path.GetDirectoryName(root);
            string grandParent             = System.IO.Path.GetDirectoryName(parent);
            string _last5DigitsOfProjectId = orderVMLight.ProjectIdStr.Substring(orderVMLight.ProjectIdStr.Length - 5);

            string OrderPdfFile = "Daikin City Order " +
                                  DateTime.Now.ToString("MM-dd-yyyy") +
                                  "-" +
                                  _last5DigitsOfProjectId + ".pdf";

            string OrderPdfFilePath = grandParent + "/CustomerDataFiles/OrderSubmitFiles/" + orderVMLight.QuoteId + "/" + OrderPdfFile;

            log.DebugFormat("OrderPdfFilePath: {0}", OrderPdfFilePath);

            string DARPdfFile = "Daikin City Discount Request " +
                                DateTime.Now.ToString("MM-dd-yyyy") +
                                "-" +
                                _last5DigitsOfProjectId + ".pdf";

            string DARPdfFilePath = grandParent + Utilities.Config("dpo.setup.customerdata.location") + "DiscountRequestFiles/" + orderVMLight.QuoteId + "/" + DARPdfFile;

            log.DebugFormat("DarPdfFilePath: {0}", DARPdfFilePath);

            string COMPdfFile     = orderVMLight.CommissionRequestId.ToString() + ".pdf";
            string COMPdfFilePath = grandParent + "/CustomerDataFiles/DiscountRequestFiles/" + orderVMLight.QuoteId + "/" + COMPdfFile;

            log.DebugFormat("COMPdfFilePath: {0}", COMPdfFilePath);

            if (orderVMLight.DiscountRequestId != null)
            {
                if (System.IO.File.Exists(DARPdfFilePath))
                {
                    orderVMLight.DARAttachmentFileName = DARPdfFilePath;
                }
                else
                {
                    orderVMLight.DARAttachmentFileName = System.IO.Directory.GetFiles(grandParent + Utilities.Config("dpo.setup.customerdata.location") + "DiscountRequestFiles/").FirstOrDefault();
                }
            }
            else
            {
                var discountRequest = discountRequestService.GetDiscountRequestModel(this.CurrentUser, orderVMLight.ProjectId, orderVMLight.QuoteId).Model as DiscountRequestModel;

                if (discountRequest.DiscountRequestId != null)
                {
                    orderVMLight.DiscountRequestId = discountRequest.DiscountRequestId;
                }

                if (orderVMLight.DiscountRequestId != null && orderVMLight.DiscountRequestId > 0)
                {
                    if (System.IO.File.Exists(DARPdfFilePath))
                    {
                        orderVMLight.DARAttachmentFileName = DARPdfFilePath;
                    }
                    else
                    {
                        string currentDARDirectory = grandParent + Utilities.Config("dpo.setup.customerdata.location") + @"DiscountRequestFiles\" + orderVMLight.QuoteId + @"\";
                        if (System.IO.Directory.Exists(currentDARDirectory))
                        {
                            orderVMLight.DARAttachmentFileName = System.IO.Directory.GetFiles(currentDARDirectory, "*.pdf").FirstOrDefault();
                        }
                        else
                        {
                            CreateDarPdfForSendMail(discountRequest);
                            orderVMLight.DARAttachmentFileName = System.IO.Directory.GetFiles(currentDARDirectory, "*.pdf").FirstOrDefault();
                        }
                    }

                    emailModel.order.RequestedDiscountPercentage = (discountRequest != null & discountRequest.RequestedDiscount > 0) ? discountRequest.RequestedDiscount : 0;
                    emailModel.order.ApprovedDiscountPercentage  = (discountRequest != null && discountRequest.ApprovedDiscount > 0) ? discountRequest.ApprovedDiscount : 0;
                }
            }

            log.DebugFormat("RequesteDiscountPercentage: {0}", emailModel.order.RequestedDiscountPercentage);
            log.DebugFormat("ApprovedDiscountPercentage: {0}", emailModel.order.ApprovedDiscountPercentage);

            if (emailModel.order.ProjectDate == DateTime.MinValue)
            {
                emailModel.order.ProjectDate = orderVMLight.ProjectDate;
                if (emailModel.order.ProjectDate == DateTime.MinValue)
                {
                    var project = projectService.GetProjectModel(this.CurrentUser, orderVMLight.ProjectId).Model as ProjectModel;
                    emailModel.order.ProjectDate = project.ProjectDate.Value;
                }
            }

            log.DebugFormat("Project Date: {0}", emailModel.order.ProjectDate);

            if (orderVMLight.CommissionRequestId != null)
            {
                orderVMLight.COMAttachmentFileName = COMPdfFilePath;
            }

            if (orderVMLight.OrderId != 0 || orderVMLight.QuoteId != 0)
            {
                orderVMLight.OrderAttachmentFileName = OrderPdfFilePath;
            }

            emailModel.OrderAttachmentFile = orderVMLight.OrderAttachmentFileName;
            emailModel.DARAttachmentFile   = orderVMLight.DARAttachmentFileName;
            emailModel.COMAttachmentFile   = orderVMLight.COMAttachmentFileName;

            if (orderVMLight.DiscountRequestId != null && orderVMLight.DiscountRequestId > 0)
            {
                log.DebugFormat("DARAttachmentFile: {0}", emailModel.DARAttachmentFile);
            }
            if (orderVMLight.CommissionRequestId != null && orderVMLight.CommissionRequestId > 0)
            {
                log.DebugFormat("COMAttachmentFile: {0}", emailModel.COMAttachmentFile);
            }

            log.DebugFormat("OrderAttachmentFile: {0}", emailModel.OrderAttachmentFile);

            //string[] filePaths = Directory.GetFiles(grandParent + "/CustomerDataFiles/POAttachment/" + orderVMLight.QuoteId + "/", "*.*",
            //                         SearchOption.AllDirectories);

            if (emailModel.OtherAttachmentFiles == null)
            {
                emailModel.OtherAttachmentFiles = new List <string>();
            }

            var uploadDirectory  = new System.IO.DirectoryInfo(Utilities.GetPOAttachmentDirectory(orderVMLight.QuoteId));
            var LatestUploadFile = (from f in uploadDirectory.GetFiles()
                                    orderby f.LastWriteTime descending
                                    select f).First();

            if (LatestUploadFile != null)
            {
                emailModel.OtherAttachmentFiles.Add(LatestUploadFile.FullName);
            }

            SendEmailModel sendEmailModel = emailModel;

            sendEmailModel.DARAttachmentFile     = (emailModel.DARAttachmentFile != null) ? emailModel.DARAttachmentFile : null;
            sendEmailModel.COMAttachmentFile     = (emailModel.COMAttachmentFile != null) ? emailModel.COMAttachmentFile : null;
            sendEmailModel.DARAttachmentFileName = DARPdfFile;
            sendEmailModel.COMAttachmentFileName = COMPdfFile;

            if (orderVMLight.DiscountRequestId != null && orderVMLight.DiscountRequestId > 0)
            {
                log.DebugFormat("sendEmailModel.DARAttachmentFile: {0}", sendEmailModel.DARAttachmentFile);
                log.DebugFormat("sendEmailModel.DARAttachmentFileName: {0}", sendEmailModel.DARAttachmentFileName);
            }
            if (orderVMLight.CommissionRequestId != null && orderVMLight.CommissionRequestId > 0)
            {
                log.DebugFormat("sendEmailModel.COMAttachmentFile: {0}", sendEmailModel.COMAttachmentFile);
                log.DebugFormat("sendEmailModel.COMAttachmentFileName: {0}", sendEmailModel.COMAttachmentFileName);
            }

            sendEmailModel.OrderAttachmentFile     = (emailModel.OrderAttachmentFile != null) ? emailModel.OrderAttachmentFile : null;
            sendEmailModel.OrderAttachmentFileName = OrderPdfFile;

            log.DebugFormat("sendEmailModel.OrderAttachmentFile: {0}", sendEmailModel.OrderAttachmentFile);
            log.DebugFormat("sendEmailModel.OrderAttachmentFileName: {0}", sendEmailModel.OrderAttachmentFileName);

            sendEmailModel.OtherAttachmentFiles = emailModel.OtherAttachmentFiles;

            if (sendEmailModel.OtherAttachmentFiles.Count > 0)
            {
                log.DebugFormat("sendEmailModel.OtherAttachmentFiles: {0}", sendEmailModel.OtherAttachmentFiles);
            }

            emailModel.RenderTextVersion = true;
            emailModel.BodyTextVersion   = RenderView(this, "SendEmailOrderSubmit", emailModel);

            emailModel.RenderTextVersion = false;
            emailModel.BodyHtmlVersion   = RenderView(this, "SendEmailOrderSubmit", emailModel);

            sendEmailModel.ProjectId = orderVMLight.ProjectId;
            sendEmailModel.QuoteId   = orderVMLight.QuoteId;

            try
            {
                log.DebugFormat("Start sending Order submit email....");
                new EmailServices().SendEmail(sendEmailModel);
            }
            catch (Exception ex)
            {
                log.DebugFormat("Start sending Order Submit error email.... ");
                SendEmailToTeamWhenFailToSendEmailOnOrder(orderVMLight.QuoteId, ex.Message);
            }

            return(null);
        }
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            HttpPageHelper.IsValidRequest = true;
            HttpPageHelper.CurrentItem    = null;

            var p = new PageServices().GetPageByURL(VirtualPath);

            HttpPageHelper.CurrentPage = p;

            string accountName = HttpUtility.HtmlDecode((string)requestContext.RouteData.Values["accountName"]);
            string isnew       = HttpUtility.HtmlDecode((string)requestContext.RouteData.Values["new"]);
            string accountID   = HttpUtility.HtmlDecode((string)requestContext.RouteData.Values["accountID"]);
            string addressID   = HttpUtility.HtmlDecode((string)requestContext.RouteData.Values["addressID"]);

            //if (!string.IsNullOrEmpty(accountID))
            //{
            //    var account = new AccountRepository().GetByID(Convert.ToInt16(accountID), false);
            //    account.Description = account.EmailDomain;
            //    var item = new Item();
            //    item.Description = account.EmailDomain;
            //    item.ItemReference = account;
            //    HttpPageHelper.CurrentItem = item;
            //}
            //if (!string.IsNullOrEmpty(accountName))
            //{
            //    var a = new AccountRepository().GetByName(accountName.Replace("-", " "));
            //    a.Description = a.EmailDomain;
            //    var item = new Item();
            //    item.Description = a.EmailDomain;
            //    item.ItemReference = a;
            //    HttpPageHelper.CurrentItem = item;
            //}

            if (string.IsNullOrEmpty(isnew))
            {
                if (!string.IsNullOrEmpty(addressID)) //We're looking at an address properties
                {
                    if (!string.IsNullOrEmpty(accountID) || !string.IsNullOrEmpty(accountName))
                    {
                        var address = new AccountServices().GetAddressByAddressID(Convert.ToInt32(addressID));
                        var item    = new Item();
                        item.Description           = address.Description;
                        item.Name                  = accountName + " " + address.Title + " " + p.Title;
                        address.Name               = accountName;
                        item.ItemReference         = address;
                        HttpPageHelper.CurrentItem = item;
                    }
                }
                else //this is the address list page
                {
                    if (!string.IsNullOrEmpty(accountName))
                    {
                        var account = new AccountServices().GetByAccountName(accountName.Replace("-", " "));
                        var item    = new Item();
                        item.Name                  = account.Name + " Address List";
                        item.URL                   = "/Accounts/Name=" + account.Name.Replace(" ", "-");
                        account.URL                = "/Accounts/Name=" + account.Name.Replace(" ", "-");
                        item.ItemReference         = account;
                        HttpPageHelper.CurrentItem = item;
                    }
                }
            }
            else
            {
                var address = new AccountAddress();
                if (!string.IsNullOrEmpty(accountName))
                {
                    var account = new AccountServices().GetByAccountName(accountName.Replace("-", " "));
                    var item    = new Item();
                    item.Description = account.ID.ToString();
                    item.Name        = account.Name + " " + address.Title + " " + p.Title;
                    //address.Name = account.Name;
                    //address.AccountID = account.ID;
                    item.URL                   = "/Accounts/Name=" + account.Name.Replace(" ", "-");
                    item.ItemReference         = item;
                    HttpPageHelper.CurrentItem = item;
                }
                else if (!string.IsNullOrEmpty(accountID))
                {
                    var account = new AccountRepository().GetByID(Convert.ToInt16(accountID), false);
                    var item    = new Item();
                    item.Description           = "New Address";
                    item.Name                  = account.Name + " " + address.Title + " " + p.Title;
                    address.Name               = account.Name;
                    item.URL                   = "/Accounts/Name=" + account.Name.Replace(" ", "-");
                    address.URL                = "/Accounts/Name=" + account.Name.Replace(" ", "-");
                    address.AccountID          = account.ID;
                    item.ItemReference         = address;
                    HttpPageHelper.CurrentItem = item;
                }
            }



            InsightBasePage page;

            page = (InsightBasePage)BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(System.Web.UI.Page));

            HttpPageHelper.IsValidRequest = true;
            return(page);
        }
示例#27
0
 public LoginController(AccountServices accountService)
 {
     _accountService = accountService;
 }
        private void SendApprovalRejectionEmail(DiscountRequestModel model)
        {
            string root        = Server.MapPath("~");
            string parent      = System.IO.Path.GetDirectoryName(root);
            string grandParent = System.IO.Path.GetDirectoryName(parent);

            string _last5DigitsOfProjectId = model.ProjectId.ToString().Substring(model.ProjectId.ToString().Length - 5);

            string DARPdfFile = "Daikin City Discount Request " +
                                DateTime.Now.ToString("MM-dd-yyyy") +
                                "-" +
                                _last5DigitsOfProjectId + ".pdf";

            string DARPdfFilePath = grandParent + "/CustomerDataFiles/DiscountRequestFiles/" + model.QuoteId + "/" + DARPdfFile;

            var emailModel = new SendEmailApprovalModel();

            emailModel.HelpLink = "mailto:[email protected]";

            emailModel.Subject = string.Format("The status of a DPO Discount request has changed");

            emailModel.Reason       = model.ResponseNotes;
            emailModel.ProjectId    = model.ProjectId;
            emailModel.ProjectName  = model.Project.Name;
            emailModel.QuoteTitle   = model.Quote.Title;
            emailModel.TotalNet     = model.Quote.TotalNet;
            emailModel.Approved     = (model.DiscountRequestStatusTypeId == (byte)DiscountRequestStatusTypeEnum.Approved);
            emailModel.ModifierName = model.DiscountRequestStatusModifiedBy;

            //only sent Dar attachment when approved Dar
            if (model.DiscountRequestStatusTypeId != (byte)DiscountRequestStatusTypeEnum.Rejected &&
                model.DiscountRequestStatusTypeId != (byte)DiscountRequestStatusTypeEnum.Deleted)
            {
                emailModel.DARAttachmentFile     = DARPdfFilePath;
                emailModel.DARAttachmentFileName = DARPdfFile;
            }

            UserSessionModel user = new UserSessionModel();

            if (model.ProjectOwnerId != null)
            {
                user = new AccountServices().GetUserSessionModel(model.ProjectOwnerId.Value).Model as UserSessionModel;
            }
            else
            {
                user = new AccountServices().GetUserSessionModel(model.Project.OwnerId.Value).Model as UserSessionModel;
            }

            emailModel.ProjectOwnerName = user.FirstName + " " + user.LastName;
            emailModel.ProjectDate      = model.Project.ProjectDate;

            var business = new BusinessServices().GetBusinessModel(user, user.BusinessId, false).Model as BusinessModel;

            emailModel.BusinessName      = business.BusinessName;
            emailModel.RequestedDiscount = model.RequestedDiscount;
            emailModel.ApprovedDiscount  = model.ApprovedDiscount;

            emailModel.From = new MailAddress(Utilities.Config("dpo.sys.email.discountrequest"), "DPO Project Desk");

            if (model.ShouldSendEmail == true)
            {
                emailModel.To.Add(new MailAddress(user.Email, user.DisplayName));
            }

            emailModel.To.Add(emailModel.From);

            if (!string.IsNullOrEmpty(business.AccountManagerEmail))
            {
                emailModel.To.Add(new MailAddress(business.AccountManagerEmail));
            }

            if (!string.IsNullOrEmpty(business.AccountOwnerEmail))
            {
                emailModel.To.Add(new MailAddress(business.AccountOwnerEmail));
            }

            List <string> emailsList = new List <string>();

            if (model.EmailsList != null && model.EmailsList.Length > 0)
            {
                emailsList = model.EmailsList.ToString().Split(',', ';').ToList();
            }

            foreach (string email in emailsList)
            {
                if (String.IsNullOrWhiteSpace(email))
                {
                    continue;
                }
                emailModel.To.Add(new MailAddress(email.Trim()));
            }

            emailModel.RenderTextVersion = true;
            emailModel.BodyTextVersion   = RenderView(this, "SendEmailDiscountRequestApproval", emailModel);

            emailModel.RenderTextVersion = false;
            emailModel.BodyHtmlVersion   = RenderView(this, "SendEmailDiscountRequestApproval", emailModel);

            new EmailServices().SendEmail(emailModel);
        }
示例#29
0
 public ManageUsersController(AccountServices service)
 {
     _service = service;
 }
示例#30
0
 public TestHomeControllers()
 {
     service = new AccountServices(this.TContext);
 }