예제 #1
0
        public async Task <ActionResult> TicketList([FromBody] TicketListRequest request)
        {
            var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();

            nfi.NumberGroupSeparator = " ";

            var model = (from v in _db.VTicketCancelList
                         where v.TicketOperationDateTime >= DateTime.Parse(request.fromDate) &&
                         v.TicketOperationDateTime < DateTime.Parse(request.toDate).AddDays(1)
                         orderby v.TicketOperationDateTime descending
                         select new TicketCancelViewModel
            {
                Status = v.OperationTypeId,
                Payment = v.Payment.ToString("#,0.00", nfi),
                PassengerName = v.PassengerName,
                BSONumber = v.BSONumber,
                Route = v.Route,
                DealDateTime = v.DealDateTime,
                TicketOperationDateTime = v.TicketOperationDateTime,
                Description = v.Description,
                ManagerName = v.ManagerName,
                TicketStatus = v.OperationType,
                TicketId = v.TicketId
            }).ToList();

            return(Json(new { message = await _viewRenderService.RenderToStringAsync("Management/TicketList", model) }));
        }
예제 #2
0
        public override void Init(long websiteWidgetId)
        {
            WebSiteWidgetId = websiteWidgetId;
            ViewFileName    = "Widgets/Category";

            var webSiteWidget = _websiteWidgetService.Get(websiteWidgetId, true);

            if (webSiteWidget != null && !string.IsNullOrEmpty(webSiteWidget.WidgetConfigJson))
            {
                var configJson = webSiteWidget.WidgetConfigJson;
                var config     = JsonConvert.DeserializeObject <dynamic>(configJson);
                DisplayTitle = config.title;
                Footer       = config.footer;
                Language     = config.language;

                try
                {
                    string temp = config.showCategoryHasPost;
                    ShowCategoryHasPost = (temp == "on") ? true : false;

                    temp          = config.showPostCount;
                    ShowPostCount = (temp == "on") ? true : false;

                    temp          = config.showHierarchy;
                    ShowHierarchy = (temp == "on") ? true : false;

                    temp = config.displayAsDropdown;
                    DisplayAsDropdown = (temp == "on") ? true : false;
                }
                catch (Exception) { }
            }

            ConfigViewFileName = "Widgets/CategoryConfig";
            ConfigHtml         = _viewRenderService.RenderToStringAsync <BlogController>(ConfigViewFileName, webSiteWidget).Result;
        }
예제 #3
0
        public async Task Invoke(HttpContext context)
        {
            _DbNetGridConfiguration = SerialisationHelper.DeserialiseJson <DbNetGridConfiguration>(context.Request.Body);

            //         Db = new DbNetData(_DbNetGridConfiguration.ConnectionString, _DbNetGridConfiguration.DataProvider, _httpContextAccessor, _hostingEnvironment, _configuration);
            Db.Open(_DbNetGridConfiguration.ConnectionString, _DbNetGridConfiguration.DataProvider);

            var handler = (string)context.Request.Query["handler"] ?? string.Empty;

            switch (handler.ToLower())
            {
            case "init":
                ConfigureColumns();
                _DbNetGridConfiguration.Html["toolbar"] = await _viewRenderService.RenderToStringAsync("DbNetGrid", _DbNetGridConfiguration);

                GetPage();
                _DbNetGridConfiguration.Html["page"] = await _viewRenderService.RenderToStringAsync("DbNetGrid_Page", _DbNetGridConfiguration);

                break;

            case "page":
                GetPage();
                _DbNetGridConfiguration.Html["page"] = await _viewRenderService.RenderToStringAsync("DbNetGrid_Page", _DbNetGridConfiguration);

                break;
            }

            Db.Close();
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(SerialisationHelper.SerialiseToJson(_DbNetGridConfiguration));

            //   await _next.Invoke(context);
        }
예제 #4
0
        public async Task <IActionResult> ProviderAgentFeeList([FromBody] ProviderAgentFeePostModel postModel)
        {
            var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();

            nfi.NumberGroupSeparator = " ";

            var queryToDate   = postModel.ToDate ?? DateTime.Now;
            var queryFromDate = postModel.FromDate ?? queryToDate.AddDays(-30);

            var transactionGroups = from c in _db.Counterparties.Where(c => c.Type.Description == "Провайдер услуг")
                                    join t in _db.ProviderAgentFeeTransactions
                                    .Where(t => t.TransactionDateTime.Date >= queryFromDate.Date &&
                                           t.TransactionDateTime.Date <= queryToDate.Date) on c.ITN equals t.ProviderId into gt
                                    from st in gt.DefaultIfEmpty()
                                    group new { c, st } by c.ITN into g
            select g;

            var model = new ProviderAgentFeeListModel
            {
                Providers = (from tg in transactionGroups
                             select new ProviderData
                {
                    ProviderId = tg.FirstOrDefault().c.ITN,
                    Name = tg.FirstOrDefault().c.Name,
                    FeeAmount = tg.Sum(g => g.st == null ? 0 : g.st.Amount).ToString("#,0.00", nfi)
                }).ToList()
            };

            return(Json(new { message = await _viewRenderService.RenderToStringAsync("Revenue/ProviderAgentFeeList", model) }));
        }
예제 #5
0
        public ApiResponse Settings(string user_id, string business_id)
        {
            ApiResponse response     = new ApiResponse();
            var         access_token = Request.Cookies["access_token"] ?? "";
            AgentModel  model        = null;

            if (!string.IsNullOrWhiteSpace(user_id) && !string.IsNullOrWhiteSpace(access_token))
            {
                var u = _appSettings.BaseUrls.Api + "brands/agents/single/" + user_id + "/?access_token=" + access_token;
                model = Core.Helpers.WebHelper.HttpGetAsync <AgentModel>(u).Result;
            }
            if (model == null)
            {
                return(response);
            }

            var url = _appSettings.BaseUrls.Api + "brands/agents/list/" + business_id + "/?access_token=" + access_token;
            var rs  = Core.Helpers.WebHelper.HttpGetAsync <AgentFeed>(url).Result;

            if (rs == null || rs.Data == null)
            {
                return(response);
            }
            var result = _viewRenderService.RenderToStringAsync("Agent/Settings", new AgentSettings {
                admin = model.admin, user_id = model.id, business_id = business_id, Agents = rs.Data
            }).Result;

            response.view = result;
            response.ok   = true;
            return(response);
        }
예제 #6
0
        public IActionResult Register(RegisterViewModel register)
        {
            if (!ModelState.IsValid)
            {
                return(View(register));
            }
            if (_userService.IsExistUserName(register.UserName))
            {
                ModelState.AddModelError("UserName", "نام کاربری معتبر نمی باشد");
                return(View(register));
            }
            if (_userService.IsExistEmail(FixedText.FixEmail(register.Email)))
            {
                ModelState.AddModelError("Email", "ایمیل معتبر نمی باشد");
                return(View(register));
            }
            User user = new User()
            {
                ActiveCode   = NameGenerator.GenerateUniqCode(),
                Email        = FixedText.FixEmail(register.Email),
                IsActive     = false,
                Password     = PasswordHelper.EncodePasswordMd5(register.Password),
                RegisterDate = DateTime.Now,
                UserAvatar   = "Defult.jpg",
                UserName     = register.UserName
            };

            _userService.AddUser(user);
            #region SendEmail
            string body = _viewRender.RenderToStringAsync("_ActiveEmail", user);
            SendEmail.Send(user.Email, "فعالسازی", body);
            #endregion
            return(View("SuccessRegister", user));
        }
예제 #7
0
        public override void Init(long websiteWidgetId)
        {
            WebSiteWidgetId = websiteWidgetId;
            ViewFileName    = "Widgets/RecentPost";

            var webSiteWidget = _websiteWidgetService.Get(websiteWidgetId, true);

            if (webSiteWidget != null && !string.IsNullOrEmpty(webSiteWidget.WidgetConfigJson))
            {
                var configJson = webSiteWidget.WidgetConfigJson;
                var config     = JsonConvert.DeserializeObject <dynamic>(configJson);
                DisplayTitle = config.title;
                Footer       = config.footer;
                Language     = config.language;

                try
                {
                    string pc = config.postCount;
                    PostCount = Convert.ToInt32(pc);
                    string ds = config.isDateShow;
                    if (ds == "on")
                    {
                        IsDateShow = true;
                    }
                    else
                    {
                        IsDateShow = false;
                    }
                }
                catch (Exception) { PostCount = 5; }
            }

            ConfigViewFileName = "Widgets/RecentPostConfig";
            ConfigHtml         = _viewRenderService.RenderToStringAsync <BlogController>(ConfigViewFileName, webSiteWidget).Result;
        }
예제 #8
0
        public override void Init(long websiteWidgetId)
        {
            WebSiteWidgetId = websiteWidgetId;
            ViewFileName    = "Widgets/RecentComments";

            var webSiteWidget = _websiteWidgetService.Get(websiteWidgetId, true);

            if (webSiteWidget != null && !string.IsNullOrEmpty(webSiteWidget.WidgetConfigJson))
            {
                var configJson = webSiteWidget.WidgetConfigJson;
                var config     = JsonConvert.DeserializeObject <dynamic>(configJson);
                DisplayTitle = config.title;
                Footer       = config.footer;
                Language     = config.language;

                try
                {
                    string cc = config.commentsCount;
                    CommentsCount = Convert.ToInt32(cc);
                }
                catch (Exception) { CommentsCount = 5; }
            }

            ConfigViewFileName = "Widgets/RecentCommentsConfig";
            ConfigHtml         = _viewRenderService.RenderToStringAsync <BlogController>(ConfigViewFileName, webSiteWidget).Result;
        }
예제 #9
0
        public override void Init(long websiteWidgetId)
        {
            WebSiteWidgetId = websiteWidgetId;
            ViewFileName    = "Widgets/NewsVertical";

            var webSiteWidget = _websiteWidgetService.Get(websiteWidgetId, true);

            if (webSiteWidget != null && !string.IsNullOrEmpty(webSiteWidget.WidgetConfigJson))
            {
                var configJson = webSiteWidget.WidgetConfigJson;
                var config     = JsonConvert.DeserializeObject <dynamic>(configJson);
                DisplayTitle  = "";
                Footer        = "";
                Language      = config.language;
                headerTitle   = config.headerTitle;
                category      = config.category;
                columnClass   = config.columnClass;
                columnColor   = config.columnColor;
                columnBgColor = config.columnBgColor;
                footerTitle   = config.footerTitle;
            }

            ConfigViewFileName = "Widgets/NewsConfig";
            ConfigHtml         = _viewRenderService.RenderToStringAsync <NewsWidgetController>(ConfigViewFileName, webSiteWidget).Result;
        }
예제 #10
0
        public override void Init(long websiteWidgetId, bool renderConfig = false)
        {
            WebSiteWidgetId = websiteWidgetId;
            ViewFileName    = "Widgets/TagCloud";

            var webSiteWidget = _websiteWidgetService.Get(websiteWidgetId, true);

            if (webSiteWidget != null && !string.IsNullOrEmpty(webSiteWidget.WidgetConfigJson))
            {
                var configJson = webSiteWidget.WidgetConfigJson;
                //var config = JsonConvert.DeserializeObject<dynamic>(configJson);
                var config = JsonHelper.Deserilize <dynamic>(configJson);
                DisplayTitle = config.title;
                Footer       = config.footer;
                Language     = config.language;

                try
                {
                    string temp = config.showPostCount;
                    ShowPostCount = (temp == "on") ? true : false;

                    temp           = config.showTagHasPost;
                    ShowTagHasPost = (temp == "on") ? true : false;
                }
                catch (Exception) { }
            }
            if (renderConfig)
            {
                ConfigViewFileName = "Widgets/TagCloudConfig";
                ConfigHtml         = _viewRenderService.RenderToStringAsync <BlogController>(ConfigViewFileName, webSiteWidget).Result;
            }
        }
예제 #11
0
        protected override async Task RenderContentAsync(TagHelperOutput output)
        {
            output.TagMode = TagMode.StartTagAndEndTag;

            if (Field.IsListValue)
            {
                var list = Field.GetModelValue(Content) as IList;
                if (Field.HasValue(list))
                {
                    for (var i = 0; i < list.Count; i++)
                    {
                        var itemContentContext = ContentContext.Navigate($"{FieldName.Name}[{i}]");
                        var itemHtml           = await viewRenderService.RenderToStringAsync(itemContentContext);

                        output.Content.AppendHtmlLine(itemHtml);
                    }
                }
            }
            else
            {
                var value = Field.GetModelValue(Content);
                if (Field.HasValue(value))
                {
                    var itemContentContext = ContentContext.Navigate(FieldName.Name);
                    var itemHtml           = await viewRenderService.RenderToStringAsync(itemContentContext);

                    output.Content.AppendHtmlLine(itemHtml);
                }
            }
        }
예제 #12
0
        public async Task PrintOrdersToPdf(Stream stream, IList <Order> orders, string languageId = "", string vendorId = "")
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (orders == null)
            {
                throw new ArgumentNullException("orders");
            }

            _generatePdf.SetConvertOptions(new ConvertOptions()
            {
                PageSize    = Wkhtmltopdf.NetCore.Options.Size.A4,
                PageMargins = new Wkhtmltopdf.NetCore.Options.Margins()
                {
                    Bottom = 10, Left = 10, Right = 10, Top = 10
                },
                FooterHtml = CommonHelper.WebMapPath(_orderFooter)
            });

            var html = await _viewRenderService.RenderToStringAsync <IList <Order> >(_orderTemaplate, orders);

            var pdfBytes = _generatePdf.GetPDF(html);

            stream.Write(pdfBytes);
        }
예제 #13
0
        public async Task <JsonResult> GetProcessDetail(int id)
        {
            var viewModel = await _utilityService.GetTransaction(id);

            var result = await _viewRenderService.RenderToStringAsync("LoadTestApp/_Details", viewModel);

            return(Json(new { status = 1, message = "Transaction loaded", data = result }));
        }
예제 #14
0
        public async Task <byte[]> GenerateDetailsPdf(int id, string sgrqChart, PatientDetailsViewModel patientDetailsViewModel)
        {
            ProcessSGRQChart(id, sgrqChart, patientDetailsViewModel);
            ProcessIgCharts(patientDetailsViewModel);
            string htmlView = await _htmlRenderService.RenderToStringAsync("/Views/Patients/PdfDetails.cshtml", patientDetailsViewModel);

            return(GeneratePdfFromHtml(htmlView));
        }
예제 #15
0
        public async Task <ActionResult> Save([FromBody] CreateVote model)
        {
            //This needs fixed
            if (!VotesEnabled)
            {
                return(ErrorView(ErrorViewModel.GetErrorViewModel(ErrorType.Unauthorized)));
            }

            try
            {
                ModelState.Clear();

                //Map to Domain Model
                var domainModel = model.Map();

                ////Reinsert Cache
                //cache.Replace($"VoteCreate:{User.Identity.Name}", domainModel);


                var valResult = Voat.Validation.ValidationHandler.Validate(domainModel);
                if (valResult != null)
                {
                    valResult.ForEach(x => ModelState.AddModelError(x.MemberNames.FirstOrDefault(), x.ErrorMessage));
                }
                CommandResponse <SaveVoteResponse> response = new CommandResponse <SaveVoteResponse>(new SaveVoteResponse(), Status.Success, "");

                if (ModelState.IsValid)
                {
                    //Save Vote
                    var cmd    = new PersistVoteCommand(domainModel).SetUserContext(User);
                    var result = await cmd.Execute();

                    if (result.Success)
                    {
                        response.Response.ID   = result.Response.ID;
                        response.Response.Html = await _viewRenderService.RenderToStringAsync("_View", await VoteAggregate.Load(result.Response));

                        return(JsonResult(response));
                        //return PartialView("_View", result.Response);
                    }
                    else
                    {
                        ModelState.AddModelError("", result.Message);
                    }
                }

                response.Status        = Status.Error;
                response.Response.Html = await _viewRenderService.RenderToStringAsync("_Edit", domainModel, ModelState);

                return(JsonResult(response));
                //return PartialView("_Edit", domainModel);
            }
            catch (Exception ex)
            {
                var x = ex;
                throw ex;
            }
        }
예제 #16
0
        async public Task <IActionResult> Register(RegisterViewModel model)
        {
            string error = "";

            var result = await _userManager.CreateAsync(new ApplicationUser {
                Email          = model.Email,
                EmailConfirmed = false,
                UserName       = model.Login,
                FirstName      = model.FirstName,
                LastName       = model.LastName,
            }, model.Password);

            if (!result.Succeeded)
            {
                error = String.Join("\r\n", result.Errors.Select(s => s.Description).ToArray());
            }
            else
            {
                var user = await _userManager.FindByNameAsync(model.Login);

                if (user != null)
                {
                    int countAddInfo = (await _roleManager.FindByNameAsync("default")).MoreInfoCount;
                    user.MoreInfoCount = countAddInfo;
                    _db.SaveChanges();

                    var res = await _userManager.AddToRoleAsync(user, "default");

                    if (!res.Succeeded)
                    {
                        error = String.Join("\r\n", result.Errors.Select(s => s.Description).ToArray());
                    }
                    else
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);

                        var emailModel = new ConfirmEmailViewModel
                        {
                            ConfirmLink = callbackUrl,
                            FirstName   = user.FirstName,
                            LastName    = user.LastName
                        };

                        var htmlEmailText = await _viewRenderService.RenderToStringAsync("Emails/ConfirmationEmailTemplate", emailModel);

                        await _emailSender.SendEmailConfirmationAsync(model.Email, "Confirm your email", htmlEmailText);
                    }
                }
                else
                {
                    error = "Can not find user: " + model.Login;
                }
            }

            return(Json(new { error = error }));
        }
예제 #17
0
        public async Task <IActionResult> Register(RegisterViewModel registerForm)
        {
            if (!ModelState.IsValid)
            {
                return(View(registerForm));
            }

            var user = new User
            {
                Email          = OptimizeText.OptimizeEmail(registerForm.Email),
                IsActive       = false,
                Name           = registerForm.Name,
                RegisterDate   = DateTime.Now,
                ActivationCode = Generator.GenerationUniqueName(),
                Password       = PasswordHelper.Hash(registerForm.Password),
                Avatar         = "default-avatar.png"
            };

            await _userService.AddUserAsync(user);

            var userRole = new UserRole
            {
                RoleId = 3,
                UserId = (await _userService.GetUserByEmailAsync(user.Email)).Id
            };

            await _permissionService.AddUserRoleAsync(userRole);

            #region Send Account Activation Email

            var emailTemplateViewModel = new EmailTemplateViewModel()
            {
                Name = user.Name,
                Url  = string.Concat(Request.Scheme, "://", Request.Host.ToUriComponent(),
                                     $"/Account/ActivateAccount/{user.ActivationCode}")
            };

            var email = new Email()
            {
                To      = user.Email,
                Subject = "فعال سازی حساب کاربری - تاپ لرن",
                Body    = await _viewRenderService.RenderToStringAsync("_AccountActivationTemplate", emailTemplateViewModel)
            };

            var emailSuccessfullySent = await _mailService.SendEmailAsync(email);

            if (!emailSuccessfullySent)
            {
                TempData["Error"] = "مشکلی پیش آمد، لطفا مجددا امتحان کنید";
                return(View(registerForm));
            }

            #endregion

            return(View("SuccessRegister", user));
        }
예제 #18
0
        /// <summary>
        /// Sends an email to the specified recipient using a Razor template.
        /// </summary>
        /// <param name="email"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public Task SendEmailAsync(string email, string subject, string templateName, object model)
        {
            string message = _emailRenderer.RenderToStringAsync(templateName, model).Result;

            return(Task.Run(() =>
            {
                MailMessage mailMessage = BuildEmailMessage(subject, message);
                mailMessage.To.Add(email);
                SendEmail(mailMessage);
            }));
        }
예제 #19
0
        private async Task SendConfirmationEmailAsync(string email, string cTokenLink)
        {
            var appUser = await _userManager.FindByEmailAsync(email);

            string message = await _viewRenderService.RenderToStringAsync("ConfirmEmailTemplate", email);

            message = message.Replace("{username}", appUser.UserName);
            message = message.Replace("{email}", appUser.Email);
            message = message.Replace("{confirmLink}", cTokenLink);
            var jobId = BackgroundJob.Enqueue(
                () => _emailService.ConfirmEmail(appUser.Email, message));
        }
예제 #20
0
        public async Task <IActionResult> DetailsVendor([FromQuery] long id)
        {
            var item = await _vendorBusinessManager.GetVendor(id);

            if (item == null)
            {
                return(NotFound());
            }

            var html = await _viewRenderService.RenderToStringAsync("Details", _mapper.Map <VendorViewModel>(item));

            return(Ok(html));
        }
예제 #21
0
        public async Task <JsonResult> Register([FromBody] CreateUser model)
        {
            try
            {
                var collForInserting = _database.GetCollection <InsertUser>("users");
                var collForReading   = _database.GetCollection <ReadUser>("users");

                model.Email = model.Email.ToLower();

                var user = new InsertUser()
                {
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    Email     = model.Email,
                    Type      = 0,
                    Password  = model.Password
                };

                //checking if the user already exists.
                var isAlreadyPresent = collForReading.AsQueryable().Any(x => x.Email == model.Email);
                if (isAlreadyPresent)
                {
                    return(Json(new { Error = 0, Message = "Sorry, the email has already been used. Please use the procedure to retrieve your password instead" }.ToJson(jsonWriterSettings)));
                }

                String salt = String.Empty;
                user.Password = AuthHelper.EncryptPassword(user.Password, out salt);
                user.Salt     = salt;
                if (temporaryUsers.ContainsKey(model.Email))
                {
                    temporaryUsers.Remove(model.Email);
                }

                temporaryUsers.Add(model.Email, user);
                var randomCode = Randomizer.RandomString(5);
                var body       = await _renderService.RenderToStringAsync("EmailTemplates/ConfirmEmail", new ConfirmEmailViewModel()
                {
                    Name = user.FirstName,
                    Code = randomCode
                });

                await Task.Run(() => _emailHelper.SendEmail("The Curious Carrot - Verify Your Email", "*****@*****.**", user.Email, body));

                return(Json(new { Error = 0, GeneratedCode = randomCode }.ToJson(jsonWriterSettings)));
            }

            catch (Exception ex)
            {
                return(Json(ex.RaiseException()));
            }
        }
예제 #22
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(Redirect("/"));
            }
            var viewModel = new ToplearnDemo.Web.ViewModels.Account.RegisterViewModel
            {
                Email           = model.Email,
                Name            = model.Name,
                Family          = model.Family,
                Password        = model.Password,
                ConfirmPassword = model.ConfirmPassword,
                Username        = model.Username,
            };

            if (ModelState.IsValid)
            {
                if (await _userRepo.EmailExists(model.Email.FixEmail()))
                {
                    ModelState.AddModelError("Email", "ایمیل وارد شده در دسترس نیست.");
                    return(View(viewModel));
                }
                if (await _userRepo.UsernameExists(model.Username.FixUsername()))
                {
                    ModelState.AddModelError("Username", "نام کاربری وارد شده در دسترس نیست.");
                    return(View(viewModel));
                }
                var result = await _userRepo.AddUser(model);

                if (result)
                {
                    var message = await _viewRender.RenderToStringAsync("_ActiveAccount", new ActiveAccountViewModel
                    {
                        Username       = model.Username,
                        ActivationCode = await _userRepo.GetActivationCode(model.Email)
                    });

                    await _messageSender.SendEmailAsync(model.Email.FixEmail(), "فعالسازی حساب کاربری", message, true);

                    return(View("SuccessfulRegister", model));
                }
                else
                {
                    ViewBag.ErrorMessage = "متاسفانه ثبت نام با موفقیت صورت نگرفت.لطفا دوباره تلاش کنید.";
                }
            }

            return(View(viewModel));
        }
예제 #23
0
        public async Task <IActionResult> SearchProducts(string search, string partialName = "", int partialIndex = 0)
        {
            var products = new GetProductSearch(_ctx).Do(new GetProductSearchQuery
            {
                SearchString = search
            }).ToList();

            if (!string.IsNullOrEmpty(partialName))
            {
                if (partialName.Contains("_FavLine"))
                {
                    foreach (var product in products)
                    {
                        product.ProductAddPartialHtml = await _viewRenderService.RenderToStringAsync(partialName, new FavouriteListProductViewModel()
                        {
                            Index      = partialIndex,
                            Id         = product.Id,
                            Code       = product.Code,
                            ImageUrl   = product.ImageUrl,
                            Name       = product.Name,
                            Price      = product.PriceDec.ToString(),
                            Qty        = 1,
                            Uom        = product.UOM,
                            TotalPrice = product.PriceDec.ToString(),
                            Deleted    = false
                        });
                    }
                }
                else if (partialName.Contains("_QuoteLine"))
                {
                    foreach (var product in products)
                    {
                        product.ProductAddPartialHtml = await _viewRenderService.RenderToStringAsync(partialName, new QuoteProductViewModel()
                        {
                            Index       = partialIndex,
                            ProductId   = product.Id,
                            ProductCode = product.Code,
                            ImageUrl    = product.ImageUrl,
                            ProductName = product.Name,
                            Price       = product.PriceDec,
                            Qty         = 1,
                            Uom         = product.UOM,
                            Deleted     = false
                        });
                    }
                }
            }

            return(Ok(products));
        }
예제 #24
0
        public IActionResult Filter(PagedResultBase filter)
        {
            var data        = _productCategoryService.GetAllPaging(filter.Keyword, filter.CurrentPage, filter.PageSize);
            var listContent = _viewRenderService.RenderToStringAsync("ProductCategory/_ListProductCategory", data.Results);
            var pagination  = _viewRenderService.RenderToStringAsync("Common/_CommonPagination", data);

            return(Json(new JsonResponse()
            {
                Success = true,
                StatusCode = Utilities.Constants.StatusCode.GetDataSuccess,
                Message = Constants.GetDataSuccess,
                Data = listContent.Result,
                Pagination = pagination.Result
            }));
        }
예제 #25
0
        public async Task <ActionResult> DashboardAttractionFastPassRequestCardAsync(long[] attractionFastPassRequestIDs)
        {
            var requestsInfo = facade.GetAttractionFastPassRequestsWithStatistics(this.HttpContext.AppUser().UserID);
            var recentChecksForAttractionFastPassRequests = facade.GetMostRecentChecksForAttractionFastRequests(this.HttpContext.AppUser().UserID, 3);
            List <Models.KeyValuePair> requestResults     = new List <Models.KeyValuePair>();

            ((ViewRenderServiceUsingHttpContext)_viewRenderService).HttpContext = this.HttpContext;

            foreach (long id in attractionFastPassRequestIDs)
            {
                string html    = null;
                var    request = requestsInfo.FirstOrDefault(p => p.AttractionFastPassRequestID == id);
                if (request != null)
                {
                    html = await _viewRenderService.RenderToStringAsync("DashboardAttractionFastPassRequestCard", new DashboardAttractionFastPassRequestCardViewModel
                    {
                        GetAttractionFastPassRequestsWithStatistics = request,
                        UserPlan = this.HttpContext.AppUser().UserPlan,
                        RecentChecksForAttractionFastPassRequests = recentChecksForAttractionFastPassRequests.Where(p => p.AttractionFastPassRequestID == id),
                        HowOftenTheSystemChecksAndProcessesAttractionFastPassRequestsInMinutes = _appSettings.HowOftenTheSystemChecksAndProcessesAttractionFastPassRequestsInMinutes
                    });

                    requestResults.Add(new Models.KeyValuePair {
                        key = id.ToString(), value = html
                    });
                }
            }
            return(Ok(requestResults));
        }
예제 #26
0
        public string RenderBody()
        {
            var webSite = _nccWebSiteService.LoadAll().FirstOrDefault();

            _body = _viewRenderService.RenderToStringAsync <HelloWidgetController>(_viewFileName, null).Result;
            return(_body);
        }
예제 #27
0
        public async Task <IActionResult> OnPost()
        {
            string htmlString = await _viewRenderService.RenderToStringAsync("CurrentWebPageToPdf", "~/Pages/_Layout.cshtml", new CurrentWebPageToPdfModel(_viewRenderService)
            {
                TxtSampleText     = this.TxtSampleText,
                DdlDropDownList1  = this.DdlDropDownList1,
                ChkSampleCheckbox = this.ChkSampleCheckbox,
                TxtSampleText2    = this.TxtSampleText2,
                TxtSampleText3    = this.TxtSampleText3,
            });

            // get base url
            string baseUrl = Startup.WebRootPath;

            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // create a new pdf document converting a html string
            PdfDocument doc = converter.ConvertHtmlString(htmlString, baseUrl);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");

            fileResult.FileDownloadName = "Document.pdf";
            return(fileResult);
        }
예제 #28
0
        public async Task <RegisterUserResult> RegisterUser(RegisterUserDTO register)
        {
            if (IsUserExistByEmail(register.Email))
            {
                return(RegisterUserResult.EmailExist);
            }

            var user = new User
            {
                Email           = register.Email.SanitizeText(),
                Address         = register.Address.SanitizeText(),
                FirstName       = register.FirstName.SanitizeText(),
                LastName        = register.LastName.SanitizeText(),
                EmailActiveCode = Guid.NewGuid().ToString(),
                Password        = _passwordHelper.EncodePasswordMd5(register.Password)
            };

            await _userRepository.AddEntity(user);

            await _userRepository.SaveChanges();


            #region Sending Activated Email
            var body = await _renderView.RenderToStringAsync("Email/_ActivateAccount", user);

            _mailSender.Send("*****@*****.**", "تست فعالسازی", body);
            #endregion

            return(RegisterUserResult.Success);
        }
예제 #29
0
        public async Task <RegisterUserDto.RegisterUserResult> RegisterUser(RegisterUserDto registerUserDto)
        {
            var isUserExist = _userRepository.IsUserExist(registerUserDto.UserName.Trim().ToLowerInvariant());

            if (isUserExist)
            {
                return(RegisterUserDto.RegisterUserResult.UserExist);
            }
            var user = new User
            {
                Email           = registerUserDto.Email.SanitizeText(),
                FirstName       = registerUserDto.FirstName.SanitizeText(),
                LastName        = registerUserDto.LastName.SanitizeText(),
                EmailActiveCode = Guid.NewGuid().ToString(),
                UserName        = registerUserDto.UserName.SanitizeText(),
                Password        = _passwordHelper.EncodePasswordMd5(registerUserDto.Password)
            };
            await _userRepository.AddEntity(user);

            await _userRepository.SaveChanges();

            var userDto = new RegisterUserDto()
            {
                Email           = user.Email,
                FirstName       = user.FirstName,
                LastName        = user.LastName,
                UserName        = user.UserName,
                EmailActiveCode = user.EmailActiveCode,
                Password        = _passwordHelper.EncodePasswordMd5(registerUserDto.Password)
            };
            var body = await _renderView.RenderToStringAsync("Email/ActivateAccount", userDto);

            _mailSender.Send(userDto.Email.ToLower().Trim(), "سیستم مدیریت فروش ارز-فعالسازی حساب کاربری جدید", body);
            return(RegisterUserDto.RegisterUserResult.Success);
        }
        private async Task <ResponseViewModel> CreateVoucher(Voucher voucher)
        {
            var response = new ResponseViewModel
            {
                Result = true,
            };

            response.Result = voucher.VoucherId <= 0 ? await _voucherService.Insert(voucher) : await _voucherService.Update(voucher);

            if (response.Result == false)
            {
                response.Messages.Add($"Thao tác không thành công");
            }
            else
            {
                response.RefObjectId = voucher.VoucherId;

                // send email

                var account = await _accountService.GetById(voucher.AccountId);

                voucher.Account = account;
                var subject  = "Bạn có 1 Voucher";
                var bodyHtml = await _viewRenderService.RenderToStringAsync <Voucher>("EmailTemplates/VoucherEmailTemplate", voucher);

                var alias = "";
                await _emailService.Send(subject, bodyHtml, alias, new List <string>() { account.Email });
            }

            return(response);
        }