Example #1
0
 public void Initialize()
 {
     customUrl = new CustomUrl {
         Id = 1, Url = "https://github.com/marciotoshio", CustomPart = "github"
     };
     validationContext = new ValidationContext(customUrl, null, null);
 }
        protected string GetCatalogItemName(Object dataItem)
        {
            CustomUrl    customUrl = (CustomUrl)dataItem;
            ICatalogable node      = CatalogDataSource.Load(customUrl.CatalogNodeId, customUrl.CatalogNodeType);

            return(node.Name);
        }
Example #3
0
        public BsJsonResult ReturnDraft(DraftVm draft)
        {
            Article   model     = null;
            CustomUrl customUrl = null;

            if (ModelState.IsValid)
            {
                var article = _articleService.GetById(draft.Id);
                model = Mapper.Map(draft, article);
                model.ArticleState = ArticleState.ReturnedDraft;
                customUrl          = CreateOrUpdateCustomUrl(draft);
            }

            if (!ModelState.IsValid)
            {
                ModelState.AddFormError("Ошибка: ",
                                        "Поля заполнены не верно. Черновик не был сохранен и не может быть возвращен.");

                return(new BsJsonResult(
                           new Dictionary <string, object> {
                    { "Errors", ModelState.GetErrors() }
                },
                           BsResponseStatus.ValidationError));
            }

            _articleService.Update(model);
            if (customUrl != null)
            {
                _customUrlService.CreateOrUpdate(customUrl);
            }

            return(new BsJsonResult(new { Status = BsResponseStatus.Success }));
        }
        protected string GetEditUrl(object dataItem)
        {
            CustomUrl customUrl = (CustomUrl)dataItem;
            string    editUrl   = string.Empty;

            switch (customUrl.CatalogNodeType)
            {
            case CatalogNodeType.Category:
                editUrl = string.Format("~/Admin/Catalog/EditCategory.aspx?CategoryId={0}", customUrl.CatalogNodeId);
                break;

            case CatalogNodeType.Product:
                editUrl = string.Format("~/Admin/products/EditProduct.aspx?ProductId={0}", customUrl.CatalogNodeId);
                break;

            case CatalogNodeType.Webpage:
                editUrl = string.Format("~/Admin/Catalog/EditWebpage.aspx?WebpageId={0}", customUrl.CatalogNodeId);
                break;

            case CatalogNodeType.Link:
                editUrl = string.Format("~/Admin/Catalog/EditLink.aspx?LinkId={0}", customUrl.CatalogNodeId);
                break;
            }
            return(Page.ResolveUrl(editUrl));
        }
Example #5
0
        public ActionResult Add(SectionVm section)
        {
            if (!_customUrlService.IsUniquePath(section.Path))
            {
                ModelState.AddModelError("Path", "Путь не уникален");
            }
            if (ModelState.IsValid)
            {
                var model = Mapper.Map <SectionVm, Section>(section);
                model.SectionState = SectionState.Active;
                model = _sectionService.Create(model);

                if (!string.IsNullOrEmpty(section.Path))
                {
                    var customUrlModel = new CustomUrl();
                    customUrlModel.Url         = model.Path;
                    customUrlModel.ContentType = ContentType.Section;
                    customUrlModel.ContentId   = model.Id;
                    _customUrlService.Create(customUrlModel);
                    //TODO: remove (temporary for output cache)
                    MemoryCacheHelper.SectionsUpdateTime = DateTime.Now;
                }

                return(RedirectToAction("Index"));
            }
            return(View(section));
        }
Example #6
0
        public BsJsonResult SaveDraft(DraftVm draft)
        {
            string    errorText = null;
            string    indexHtml = null;
            Article   model     = null;
            CustomUrl customUrl = null;

            if (ModelState.IsValid)
            {
                var article = _articleService.GetById(draft.Id);
                model = Mapper.Map(draft, article);


                customUrl = CreateOrUpdateCustomUrl(draft);

                if (model.ArticleState == ArticleState.New)
                {
                    model.ArticleState = ArticleState.Draft;
                }

                if (model.ArticleState == ArticleState.Article)
                {
                    if (!_htmlParserHelper.GetIndexHtmlFromArticleText(model.Text, out indexHtml))
                    {
                        errorText = "Статья не содержит линии разрыва печати. Без неё публиковать нельзя!";
                    }
                }
            }

            if (!ModelState.IsValid)
            {
                errorText = "Поля заполнены не верно. Черновик не был сохранен.";
            }

            if (errorText != null)
            {
                ModelState.AddFormError("Ошибка: ", errorText);

                return(new BsJsonResult(
                           new Dictionary <string, object> {
                    { "Errors", ModelState.GetErrors() }
                },
                           BsResponseStatus.ValidationError));
            }

            model.IndexHtml = indexHtml;
            _articleService.Update(model);
            //TODO: remove (temporary for output cache)
            MemoryCacheHelper.ArticlesUpdateTime = DateTime.Now;
            if (customUrl != null)
            {
                _customUrlService.CreateOrUpdate(customUrl);
            }

            return(new BsJsonResult(new { Status = BsResponseStatus.Success }));
        }
Example #7
0
        public string ToUrl(SubFloat?shiftedMinValue = null)
        {
            var str = new StringBuilder();

            if (!CustomUrl.IsEmpty())
            {
                str.Append(CustomUrl);
                if (MinPrice.HasValue && MinPrice.Value != 0)
                {
                    str.Append("&");
                    str.Append(_minPrice);
                    str.Append("=");
                    str.Append(MinPrice);
                }

                if (MaxPrice.HasValue && MaxPrice.Value != 0)
                {
                    str.Append("&");
                    str.Append(_maxPrice);
                    str.Append("=");
                    str.Append(MaxPrice);
                }
            }
            else
            {
                str.Append(@"https://www.aliexpress.com/wholesale?site=glo&tc=af&g=y");
                //var str = new StringBuilder(@"https://www.aliexpress.com/wholesale?tc=af&g=y");
                foreach (var prop in GetType().GetProperties())
                {
                    var attrs = prop.GetCustomAttributes(typeof(NameAttribute), false);
                    if (attrs.Length < 1)
                    {
                        continue;
                    }
                    var attr = attrs[0] as NameAttribute;
                    str.Append("&");
                    str.Append(attr.Name);
                    str.Append("=");
                    object value;

                    if (shiftedMinValue != null && attr.Name.IsEqual(_minPrice))
                    {
                        value = shiftedMinValue;
                    }
                    else
                    {
                        value = prop.GetValue(this);
                    }
                    str.Append(value.ToStringNull());
                }
                str.Append("&page=");
            }

            currentUrl = str.ToString();
            return(currentUrl);
        }
Example #8
0
        public void AddCustomUrl(string url, string customPart)
        {
            var customUrl = new CustomUrl {
                Url = url, CustomPart = customPart
            };

            customUrlRepository.Add(customUrl);
            customUrlRepository.Save();
            customUrlsCache.Add(customPart, url);
        }
Example #9
0
 public ActionResult Delete(int id, CustomUrl customUrl)
 {
     try
     {
         repo.Remove(id);
         repo.Save();
         return(RedirectToAction("Index"));
     }
     catch
     {
         return(View());
     }
 }
Example #10
0
 public ActionResult Create(CustomUrl customUrl)
 {
     try
     {
         repo.Add(customUrl);
         repo.Save();
         return(RedirectToAction("Index"));
     }
     catch
     {
         return(View(customUrl));
     }
 }
Example #11
0
 public string SetUrlPage(int pageNumber)
 {
     if (currentUrl.IsEmpty())
     {
         ToUrl();
     }
     if (!CustomUrl.IsEmpty())
     {
         return(currentUrl.ReplaceBetween("{", "}", pageNumber));
     }
     else
     {
         return(currentUrl + pageNumber);
     }
 }
Example #12
0
        public Category ParseCategoryBySlug(string slug, out CustomUrl customUrl)
        {
            customUrl = null;
            var result = CatalogServices.Categories.FindBySlug(slug);

            if (result == null)
            {
                // Check for custom URL
                customUrl = ContentServices.CustomUrls.FindByRequestedUrl(slug, CustomUrlType.Category);
                if (customUrl != null)
                {
                    result = CatalogServices.Categories.FindBySlug(customUrl.RedirectToUrl);
                }
            }

            return(result);
        }
Example #13
0
        public Product ParseProductBySlug(string slug, out CustomUrl customUrl)
        {
            customUrl = null;
            var result = CatalogServices.Products.FindBySlug(slug);

            if (result == null || result.Status == ProductStatus.Disabled)
            {
                // Check for custom URL
                customUrl = ContentServices.CustomUrls.FindByRequestedUrl(slug, CustomUrlType.Product);
                if (customUrl != null)
                {
                    result = CatalogServices.Products.FindBySlug(customUrl.RedirectToUrl);
                }
            }

            return(result);
        }
Example #14
0
        private Product ParseProductFromSlug(string slug)
        {
            Product result = null;

            if (slug != string.Empty)
            {
                result = MTApp.CatalogServices.Products.FindBySlug(slug);
                bool possibleError = false;
                if (result == null)
                {
                    possibleError = true;
                }
                else if (result.Status == ProductStatus.Disabled)
                {
                    possibleError = true;
                }

                if (possibleError)
                {
                    // Check for custom URL
                    string    potentialCustom = Url.RouteUrl("bvroute", new { slug = slug });
                    CustomUrl url             = MTApp.ContentServices.CustomUrls.FindByRequestedUrl(potentialCustom);
                    if (url != null)
                    {
                        if (url.Bvin != string.Empty)
                        {
                            if (url.IsPermanentRedirect)
                            {
                                Response.RedirectPermanent(url.RedirectToUrl);
                            }
                            else
                            {
                                Response.Redirect(url.RedirectToUrl);
                            }
                        }
                    }
                    Response.Redirect(Url.Content("~/Error?type=product"));
                }
            }

            return(result);
        }
        private bool Save()
        {
            bool result = false;

            if (UrlRewriter.IsUrlInUse(this.RequestedUrlField.Text.Trim(), this.BvinField.Value, MTApp.CurrentRequestContext, MTApp))
            {
                this.MessageBox1.ShowWarning("Another item already uses this URL. Please choose another one");
                return(false);
            }

            CustomUrl c;

            c = MTApp.ContentServices.CustomUrls.Find(this.BvinField.Value);
            if (c == null)
            {
                c = new CustomUrl();
            }
            if (c != null)
            {
                c.RequestedUrl        = this.RequestedUrlField.Text.Trim();
                c.RedirectToUrl       = this.RedirectToUrlField.Text.Trim();
                c.IsPermanentRedirect = this.chkPermanent.Checked;

                if (this.BvinField.Value == string.Empty)
                {
                    result = MTApp.ContentServices.CustomUrls.Create(c);
                }
                else
                {
                    result = MTApp.ContentServices.CustomUrls.Update(c);
                }

                if (result == true)
                {
                    // Update bvin field so that next save will call updated instead of create
                    this.BvinField.Value = c.Bvin;
                }
            }

            return(result);
        }
Example #16
0
        public ActionResult Edit(SectionVm section)
        {
            if (ModelState.IsValid)
            {
                var model = Mapper.Map <SectionVm, Section>(section);
                model.SectionState = SectionState.Active;

                var customUrl =
                    _customUrlService.GetAll()
                    .FirstOrDefault(x => x.ContentId == section.Id && x.ContentType == ContentType.Section);

                if (customUrl == null && !string.IsNullOrEmpty(section.Path))
                {
                    customUrl = new CustomUrl();
                }

                if (customUrl != null && customUrl.Url != section.Path)
                {
                    if (!_customUrlService.IsUniquePath(section.Path))
                    {
                        ModelState.AddModelError("Path", "Путь не уникален");
                        return(View(section));
                    }

                    customUrl.Url         = section.Path;
                    customUrl.ContentType = ContentType.Section;
                    customUrl.ContentId   = section.Id;

                    _customUrlService.CreateOrUpdate(customUrl);
                }

                _sectionService.Update(model);
                //TODO: remove (temporary for output cache)
                MemoryCacheHelper.SectionsUpdateTime = DateTime.Now;

                return(RedirectToAction("Index"));
            }
            return(View(section));
        }
Example #17
0
        private CustomUrl CreateOrUpdateCustomUrl(DraftVm draft)
        {
            var customUrl = _customUrlService.GetAll().FirstOrDefault(x => x.ContentId == draft.Id && x.ContentType == ContentType.Article);

            if (customUrl == null && !string.IsNullOrEmpty(draft.SeoUrl))
            {
                customUrl = new CustomUrl();
            }

            if (customUrl != null && customUrl.Url != draft.SeoUrl)
            {
                if (!_customUrlService.IsUniquePath(draft.SeoUrl))
                {
                    ModelState.AddModelError("SeoUrl", "Путь не уникален");
                    return(null);
                }
                customUrl.Url         = draft.SeoUrl;
                customUrl.ContentType = ContentType.Article;
                customUrl.ContentId   = draft.Id;
            }

            return(customUrl);
        }
        protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
        {
            string    controller = String.Empty;
            string    action     = String.Empty;
            int       page;
            string    path;
            CustomUrl customUrl = null;

            var fullUrl = ((string)requestContext.RouteData.Values["url"]).ToLower();

            if (TryParseUrl(fullUrl, out path, out page))
            {
                if (CustomUrlCache.CustomUrls.ContainsKey(path))
                {
                    customUrl = CustomUrlCache.CustomUrls[path];
                }
                else
                {
                    ICustomUrlService customUrlService = (ICustomUrlService)DependencyResolver.Current.GetService(typeof(ICustomUrlService));

                    customUrl = customUrlService.GetAll().FirstOrDefault(x => String.Equals(x.Url, path, StringComparison.CurrentCultureIgnoreCase));
                    if (customUrl != null)
                    {
                        CustomUrlCache.CustomUrls.TryAdd(path, customUrl);
                    }
                }

                if (customUrl != null)
                {
                    switch (customUrl.ContentType)
                    {
                    case ContentType.Article:
                        controller = "Post";
                        action     = "Article";
                        break;

                    case ContentType.Section:
                        controller = "Home";
                        action     = "Section";
                        requestContext.RouteData.Values["page"] = page;
                        break;

                    default:
                        throw new ArgumentException("Invalid ContentType");
                    }
                }
            }

            if (customUrl == null)
            {
                controller = "Common";
                action     = "NoPageFound";
            }
            else
            {
                requestContext.RouteData.Values["id"] = customUrl.ContentId;
            }
            requestContext.RouteData.DataTokens.Add("namespaces", new string[] { "ZelectroCom.Web.Controllers" });
            requestContext.RouteData.Values["controller"] = controller;
            requestContext.RouteData.Values["action"]     = action;

            return(base.GetHttpHandler(requestContext));
        }
Example #19
0
 public void AddCustomUrl(CustomUrl customUrl)
 {
     customUrlRepository.Add(customUrl);
     customUrlRepository.Save();
     customUrlsCache.TryAdd(customUrl.CustomPart, customUrl.Url);
 }
Example #20
0
    protected void UpgradeButton_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            List <string> errorList   = new List <string>();
            List <string> warningList = new List <string>();

            //PROCESS SQL UPDATES
            string upgradeSqlFile = Server.MapPath("~/Install/Upgrade_AC7_AC708.sql");
            if (File.Exists(upgradeSqlFile))
            {
                //RUN THE SCRIPT
                string connectionString = ConfigurationManager.ConnectionStrings["AbleCommerce"].ConnectionString;
                errorList = RunScript(connectionString, upgradeSqlFile);

                // ADD DEFAULT DATA FOR WEB PAGES
                Webpage categoryWebpage = AddNewWebpage("Category Grid (Deep Item Display)", "Displays products for the selected category and all of it's sub-categories. Items are displayed in a grid format with breadcrumb links, sorting, page navigation, and sub-category link options.", "[[ConLib:CategoryGridPage]]", null, WebpageType.CategoryDisplay, errorList);
                AddNewWebpage("Category Details Page", "Displays categories, products, webpages, and links for only the selected category.  Items are displayed in a left-aligned, row format, with descriptions and images.", "[[ConLib:CategoryDetailsPage]]", null, WebpageType.CategoryDisplay, errorList);
                AddNewWebpage("Category Grid (Shallow Item Display)", "Displays products for only the selected category.  Items are displayed in a grid format with breadcrumb links, sorting, page navigation, and sub-category link options.", "[[ConLib:CategoryGridPage2]]", null, WebpageType.CategoryDisplay, errorList);
                AddNewWebpage("Category Grid (Deep Item Display) With Add To Basket", "Displays products for the selected category and all of it's sub-categories. Items are displayed in a grid format, each with a quantity box so user can purchase multiple items with one click.  Includes breadcrumb links, sorting, page navigation, and sub-cat", "[[ConLib:CategoryGridPage3]]", null, WebpageType.CategoryDisplay, errorList);
                AddNewWebpage("Category Grid (Shallow Item Display) With Category Data", "Displays categories, products, webpages, and links for only the selected category.  Items are displayed in a grid format with breadcrumb links, sorting, and page navigation.", "[[ConLib:CategoryGridPage4]]", null, WebpageType.CategoryDisplay, errorList);
                AddNewWebpage("Category List", "Displays products for only the selected category.  Items are displayed in a row format with columns for SKU, manufacturer, and pricing.  Includes breadcrumb links, sorting, page navigation, and sub-category link options.", "[[ConLib:CategoryListPage]]", null, WebpageType.CategoryDisplay, errorList);
                Webpage productWebpage = AddNewWebpage("Basic Product", "A product display page that shows the basic product details.", "[[ConLib:ProductPage]]", null, WebpageType.ProductDisplay, errorList);
                AddNewWebpage("Product with Options Grid", "A product display page that shows all variants of a product in a grid layout.  This display page should not be used with products having more than 8 options.", "[[ConLib:ProductPage OptionsView=\"TABULAR\"]]", null, WebpageType.ProductDisplay, errorList);
                AddNewWebpage("Product Display in Rows", "A product display page that shows the product details in rows.", "[[ConLib:ProductRow]]", null, WebpageType.ProductDisplay, errorList);

                // ADD HOME PAGE
                Webpage homepage = AddNewWebpage("Home Page", "<p>Hello and welcome to your store! To edit this text, log in to the merchant administration. From the menu bar, select Website &gt; Webpages. Then you can edit the Home Page to modify this content.</p>", "[[ConLib:FeaturedProductsGrid]]", "~/Layouts/LeftSidebar.master", WebpageType.Content, errorList);

                // ADD CONTACT US PAGE
                Webpage contactusPage = AddNewWebpage("Contact Us", "Standard contact us page.", "<h2>Contact Us</h2>\r\n<p>Need help placing your order or have a question about an order you placed? You can call us toll free at 1-800-555-0199. </p><p>Our Business Address Is:<br />123 Anywhere Lane<br />Corona, CA 92882 </p><p>You can also email us at <a href=\"#\">[email protected]</a> </p><p>To edit this text, log in to the merchant administration. From the menu bar, select Website &gt; Webpages. Then you can edit the Contact Us page to modify this content.</p> ", "~/Layouts/OneColumn.master", WebpageType.Content, errorList);

                try
                {
                    // ADD CUSTOM URL's FOR HOME PAGE AND CONTACTUS PAGE
                    if (homepage != null)
                    {
                        CustomUrl url1 = new CustomUrl(AbleContext.Current.Store, homepage.Id, (byte)CatalogNodeType.Webpage, "Default.aspx");
                        url1.Save();
                    }

                    if (contactusPage != null)
                    {
                        CustomUrl url2 = new CustomUrl(AbleContext.Current.Store, contactusPage.Id, (byte)CatalogNodeType.Webpage, "ContactUs.aspx");
                        url2.Save();
                    }
                }
                catch (Exception ex)
                {
                    errorList.Add(string.Format("An error occurred while adding custorm url(s), error: {0}", ex.Message));
                }

                // UPDATE STORE SETTINGS
                IList <StoreSetting> settings = StoreSettingDataSource.LoadAll();
                CheckAndAddSetting(settings, "WebpagesDefaultLayout", "~/Layouts/LeftSidebar.master", errorList);
                CheckAndAddSetting(settings, "CategoriesDefaultLayout", "~/Layouts/Category.master", errorList);
                CheckAndAddSetting(settings, "ProductsDefaultLayout", "~/Layouts/Product.master", errorList);
                CheckAndAddSetting(settings, "EnableCustomerOrderNotes", "True", errorList);

                Store  store    = AbleContext.Current.Store;
                string storeUrl = GetStoreUrl();
                store.StoreUrl = storeUrl;
                string storeUrlKey = "Store_StoreUrl";
                StoreSetting storeUrlSt = settings.Find <StoreSetting>(delegate(StoreSetting s) { return(s.FieldName == storeUrlKey); });
                if (storeUrlSt == null)
                {
                    storeUrlSt = new StoreSetting(AbleContext.Current.Store, storeUrlKey, storeUrl);
                    store.Settings.Add(storeUrlSt);
                }
                else
                {
                    storeUrlSt.FieldValue = storeUrl;
                }
                storeUrlSt.Save();

                //store.Settings.Save();

                if (categoryWebpage != null)
                {
                    CheckAndAddSetting(settings, "CategoryWebpageId", categoryWebpage.Id.ToString(), errorList);
                }
                else
                {
                    errorList.Add("Can not add CategoryWebpageId store setting as adding respective webpage failed.");
                }

                if (productWebpage != null)
                {
                    CheckAndAddSetting(settings, "ProductWebpageId", productWebpage.Id.ToString(), errorList);
                }
                else
                {
                    errorList.Add("Can not add ProductWebpageId store setting as adding respective webpage failed.");
                }
            }
            else
            {
                HandleError("<b>Can not continue with upgrade, SQL script file does not exist: " + upgradeSqlFile + " .</b><br/><br />");
                return;
            }

            if (ApplicationSettings.Instance.SearchProvider == "LuceneSearchProvider")
            {
                AbleContext.Container.Resolve <IFullTextSearchService>().AsyncReindex();
                IndexesInfoPanel.Visible = true;
            }

            // Recreate/Reindex the SQL FTS Catalog if search provider is SQL FTS
            if (ApplicationSettings.Instance.SearchProvider == "SqlFtsSearchProvider")
            {
                try
                {
                    if (KeywordSearchHelper.EnsureCatalog())
                    {
                        KeywordSearchHelper.EnsureIndexes();
                    }
                }
                catch (Exception ex)
                {
                    warningList.Add(string.Format("An error occurred creating/updating SQL FTS Search Indexes. You may have to run the re-indexing manually. Error: {0}", ex.Message));
                }
            }

            //SHOW ANY ERRORS
            if (errorList.Count > 0)
            {
                UpgradeErrorList.Text     = string.Join("<br /><br />", errorList.ToArray());
                UpgradeErrorPanel.Visible = true;
            }
            //SHOW ANY WARNINGS
            if (warningList.Count > 0)
            {
                UpgradeWarnList.Text        = string.Join("<br /><br />", warningList.ToArray());
                UpgradeWarningPanel.Visible = true;
            }

            UpgradeCompletePanel.Visible = true;
            phUpgrade.Visible            = false;
        }
    }