Beispiel #1
0
        public static string UploadImage(HttpPostedFileBase image, string filePathOriginal, string fileName = null)
        {
            if (image == null || image.ContentLength == 0)
            {
                return(null);
            }

            if (!IsImage(image))
            {
                return(null);
            }

            //Save image to file
            var imageExtension = Path.GetExtension(image.FileName);
            var fileNameASCII  = string.IsNullOrEmpty(fileName) ? SeoHelper.GetSeName(Path.GetFileNameWithoutExtension(image.FileName)) : SeoHelper.GetSeName(fileName);
            var newName        = fileNameASCII + imageExtension;

            string savedFileName = Path.Combine(filePathOriginal, newName);

            Directory.CreateDirectory(filePathOriginal);

            int fileCount = 0;

            while (File.Exists(savedFileName))
            {
                fileCount++;
                newName       = $"{fileNameASCII}_{fileCount}{imageExtension}";
                savedFileName = Path.Combine(filePathOriginal, newName);
            }
            image.SaveAs(savedFileName);

            return(newName);
        }
Beispiel #2
0
 public override void Validate(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
 {
     base.Validate(_context, _transaction);
     FileFolder = $"{MixService.GetTemplateUploadFolder(Specificulture)}";
     if (MediaFile?.FileStream != null)
     {
         MediaFile.Filename   = $"{SeoHelper.GetSEOString(MediaFile.Filename).ToLower()}-{ DateTime.UtcNow.Ticks}";
         MediaFile.FileFolder = FileFolder;
         var isSaved = MixFileRepository.Instance.SaveWebFile(MediaFile);
         if (isSaved)
         {
             Extension  = MediaFile.Extension.ToLower();
             FileName   = MediaFile.Filename;
             FileFolder = MediaFile.FileFolder;
             if (string.IsNullOrEmpty(Title))
             {
                 Title = FileName;
             }
         }
         else
         {
             IsValid = false;
         }
     }
     else
     {
         if (File != null)
         {
             FileName  = $"{SeoHelper.GetSEOString(File.FileName[..File.FileName.LastIndexOf('.')]).ToLower()}-{ DateTime.UtcNow.Ticks}";
Beispiel #3
0
        /// <summary>
        /// Resolves the file name pattern for an export profile
        /// </summary>
        /// <param name="profile">Export profile</param>
        /// <param name="store">Store</param>
        /// <param name="fileIndex">One based file index</param>
        /// <param name="maxFileNameLength">The maximum length of the file name</param>
        /// <returns>Resolved file name pattern</returns>
        public static string ResolveFileNamePattern(this ExportProfile profile, Store store, int fileIndex, int maxFileNameLength)
        {
            var sb = new StringBuilder(profile.FileNamePattern);

            sb.Replace("%Profile.Id%", profile.Id.ToString());
            sb.Replace("%Profile.FolderName%", profile.FolderName);
            sb.Replace("%Store.Id%", store.Id.ToString());
            sb.Replace("%File.Index%", fileIndex.ToString("D4"));

            if (profile.FileNamePattern.Contains("%Profile.SeoName%"))
            {
                sb.Replace("%Profile.SeoName%", SeoHelper.GetSeName(profile.Name, true, false).Replace("/", "").Replace("-", ""));
            }
            if (profile.FileNamePattern.Contains("%Store.SeoName%"))
            {
                sb.Replace("%Store.SeoName%", profile.PerStore ? SeoHelper.GetSeName(store.Name, true, false) : "allstores");
            }
            if (profile.FileNamePattern.Contains("%Random.Number%"))
            {
                sb.Replace("%Random.Number%", CommonHelper.GenerateRandomInteger().ToString());
            }
            if (profile.FileNamePattern.Contains("%Timestamp%"))
            {
                sb.Replace("%Timestamp%", DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture));
            }

            var result = sb.ToString()
                         .ToValidFileName("")
                         .Truncate(maxFileNameLength);

            return(result);
        }
Beispiel #4
0
 protected static void InitPages(string culture, MixCmsContext context, IDbContextTransaction transaction)
 {
     V_0 = JObject.Parse(FileRepository.get_Instance().GetFile("pages.json", "data", true, "{}").get_Content()).get_Item("data").ToObject <List <MixPage> >().GetEnumerator();
     try
     {
         while (V_0.MoveNext())
         {
             V_1 = V_0.get_Current();
             V_1.set_Specificulture(culture);
             V_1.set_SeoTitle(V_1.get_Title().ToLower());
             V_1.set_SeoName(SeoHelper.GetSEOString(V_1.get_Title(), '-'));
             V_1.set_SeoDescription(V_1.get_Title().ToLower());
             V_1.set_SeoKeywords(V_1.get_Title().ToLower());
             V_1.set_CreatedDateTime(DateTime.get_UtcNow());
             V_1.set_CreatedBy("SuperAdmin");
             context.Entry <MixPage>(V_1).set_State(4);
             stackVariable43 = new MixUrlAlias();
             stackVariable43.set_Id(V_1.get_Id());
             stackVariable43.set_SourceId(V_1.get_Id().ToString());
             stackVariable43.set_Type(0);
             stackVariable43.set_Specificulture(culture);
             stackVariable43.set_CreatedDateTime(DateTime.get_UtcNow());
             stackVariable43.set_Alias(V_1.get_Title().ToLower());
             stackVariable43.set_Status(2.ToString());
             context.Entry <MixUrlAlias>(stackVariable43).set_State(4);
         }
     }
     finally
     {
         ((IDisposable)V_0).Dispose();
     }
     return;
 }
        public void Initialize(InitializationEngine context)
        {
            var contentRepository = ServiceLocator.Current.GetInstance <IContentRepository>();

            try
            {
                if (!ContentReference.IsNullOrEmpty(ContentReference.StartPage))
                {
                    var content = contentRepository.GetChildren <SBRobotsTxt>(ContentReference.StartPage);

                    if (content != null)
                    {
                        var list = content.ToList();

                        if (list.Any())
                        {
                            Task.Run(async() => await SeoHelper.AddRoute());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.GetLogger().Error("SEOBOOST Initialization", ex);
            }
        }
Beispiel #6
0
		private void GenerateSEO()
		{
			V_0 = new Mix.Cms.Lib.ViewModels.MixPosts.UpdateViewModel.u003cu003ec__DisplayClass220_0();
			V_0.u003cu003e4__this = this;
			if (string.IsNullOrEmpty(this.get_SeoName()))
			{
				this.set_SeoName(SeoHelper.GetSEOString(this.get_Title(), '-'));
			}
			V_1 = 1;
			V_0.name = this.get_SeoName();
			while (ViewModelBase<MixCmsContext, MixPost, Mix.Cms.Lib.ViewModels.MixPosts.UpdateViewModel>.Repository.CheckIsExists(new Func<MixPost, bool>(V_0.u003cGenerateSEOu003eb__0), null, null))
			{
				V_0.name = string.Concat(this.get_SeoName(), "_", V_1.ToString());
				V_1 = V_1 + 1;
			}
			this.set_SeoName(V_0.name);
			if (string.IsNullOrEmpty(this.get_SeoTitle()))
			{
				this.set_SeoTitle(SeoHelper.GetSEOString(this.get_Title(), '-'));
			}
			if (string.IsNullOrEmpty(this.get_SeoDescription()))
			{
				this.set_SeoDescription(SeoHelper.GetSEOString(this.get_Title(), '-'));
			}
			if (string.IsNullOrEmpty(this.get_SeoKeywords()))
			{
				this.set_SeoKeywords(SeoHelper.GetSEOString(this.get_Title(), '-'));
			}
			return;
		}
Beispiel #7
0
        private void GenerateSEO(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            if (string.IsNullOrEmpty(this.SeoName))
            {
                this.SeoName = SeoHelper.GetSEOString(this.Title);
            }
            int    i    = 1;
            string name = SeoName;

            while (UpdateViewModel.Repository.CheckIsExists(a => a.SeoName == name && a.Specificulture == Specificulture && a.Id != Id, _context, _transaction))
            {
                name = SeoName + "_" + i;
                i++;
            }
            SeoName = name;

            if (string.IsNullOrEmpty(this.SeoTitle))
            {
                this.SeoTitle = this.Title;
            }

            if (string.IsNullOrEmpty(this.Excerpt))
            {
                this.SeoDescription = this.Excerpt;
            }

            if (string.IsNullOrEmpty(this.SeoKeywords))
            {
                this.SeoKeywords = SeoHelper.GetSEOString(this.Title);
            }
        }
        public static IndexVm GetIndexSearchVm()
        {
            IndexVm indexVm = new IndexVm();

            indexVm.PageType = PageType.Index;
            indexVm.Seo      = SeoHelper.GetSeo(indexVm);
            indexVm.Criteria = GetInitSearchCriteriaVm();
            CountryStubSearchModel countryStubSearchModel = new CountryStubSearchModel();

            countryStubSearchModel.Criteria         = indexVm.Criteria.ToSearchCriteria();
            countryStubSearchModel.MaxCount         = ConfigurationManager.Instance.IndexStubCitiesMaxCount;
            countryStubSearchModel.IsMarketAreaOnly = true;
            List <CityListingsInfo> result = SearchBc.Instance.SearchStubCities(countryStubSearchModel).Result;

            indexVm.Result.Add(SearchType.ActiveAdultCommunities, result.OrderByDescending((CityListingsInfo li) => li.AdultCommunitiesCount).Take(countryStubSearchModel.MaxCount).MapToCitiesLinks(SearchType.ActiveAdultCommunities, addCounting: false));
            indexVm.Result.Add(SearchType.ActiveAdultHomes, result.OrderByDescending((CityListingsInfo li) => li.AdultHomesCount).Take(countryStubSearchModel.MaxCount).MapToCitiesLinks(SearchType.ActiveAdultHomes, addCounting: false));
            indexVm.Result.Add(SearchType.SeniorHousingAndCare, result.OrderByDescending((CityListingsInfo li) => li.SeniorHousingCount).Take(countryStubSearchModel.MaxCount).MapToCitiesLinks(SearchType.SeniorHousingAndCare, addCounting: false));
            indexVm.Result.Add(SearchType.ProductsAndServices, result.OrderByDescending((CityListingsInfo li) => li.ServicesCount).Take(countryStubSearchModel.MaxCount).MapToCitiesLinks(SearchType.ProductsAndServices, addCounting: false));
            List <KeyValuePair <int, string> > shcCategoriesForCommunity = ItemTypeBc.Instance.GetShcCategoriesForCommunity();
            List <int> ShcCategories = new List <int>();

            indexVm.Refine = new CommunityRefineVm();
            indexVm.SearchBar.SHCategories = shcCategoriesForCommunity.MapToSelectListItemList(ShcCategories);
            //indexVm.Refine.ShcCategories =
            return(indexVm);
        }
        public static SearchTypeStubSearchVm GetSearchTypeSearchVm(SearchTypeStubSearchVm searchVm)
        {
            List <CityListingsInfo> result;

            if (searchVm.PageType == PageType.ServiceProvidersByType)
            {
                CountryStubSearchModel countryStubSearchModel = new CountryStubSearchModel();
                countryStubSearchModel.Criteria = searchVm.Criteria.ToSearchCriteria();
                countryStubSearchModel.MaxCount = ConfigurationManager.Instance.SearchTypeStubCitiesMaxCount;
                result = SearchBc.Instance.SearchServiceProvidersStubCities(countryStubSearchModel).Result;
            }
            else
            {
                CommunityCountryStubSearchModel communityCountryStubSearchModel = new CommunityCountryStubSearchModel();
                communityCountryStubSearchModel.Criteria    = searchVm.Criteria.ToSearchCriteria();
                communityCountryStubSearchModel.ListingType = searchVm.PageType.ToSearchType().ToListingType();
                communityCountryStubSearchModel.MaxCount    = ConfigurationManager.Instance.SearchTypeStubCitiesMaxCount;
                result = SearchBc.Instance.SearchCommunitiesStubCities(communityCountryStubSearchModel).Result;
            }
            searchVm.Result      = result.MapToCitiesTabs(searchVm.PageType.ToSearchType());
            searchVm.Seo         = SeoHelper.GetSeo(searchVm);
            searchVm.SearchBar   = GetSearchBarVm(searchVm);
            searchVm.Breadcrumbs = GetBreadcrumbs(searchVm);
            return(searchVm);
        }
Beispiel #10
0
        protected static void InitPages(string culture, MixCmsContext context, IDbContextTransaction transaction)
        {
            /* Init Languages */
            var pages   = FileRepository.Instance.GetFile(MixConstants.CONST_FILE_PAGES, "data", true, "{}");
            var obj     = JObject.Parse(pages.Content);
            var arrPage = obj["data"].ToObject <List <MixPage> >();

            foreach (var page in arrPage)
            {
                page.Specificulture       = culture;
                page.SeoTitle             = page.Title.ToLower();
                page.SeoName              = SeoHelper.GetSEOString(page.Title);
                page.SeoDescription       = page.Title.ToLower();
                page.SeoKeywords          = page.Title.ToLower();
                page.CreatedDateTime      = DateTime.UtcNow;
                page.CreatedBy            = "SuperAdmin";
                context.Entry(page).State = EntityState.Added;
                var alias = new MixUrlAlias()
                {
                    Id              = page.Id,
                    SourceId        = page.Id.ToString(),
                    Type            = (int)UrlAliasType.Page,
                    Specificulture  = culture,
                    CreatedDateTime = DateTime.UtcNow,
                    Alias           = page.Title.ToLower(),
                    Status          = (int)MixContentStatus.Published
                };
                context.Entry(alias).State = EntityState.Added;
            }
        }
Beispiel #11
0
 public override MixTheme ParseModel(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
 {
     Id              = 1;
     Name            = SeoHelper.GetSEOString(Title);
     CreatedDateTime = DateTime.UtcNow;
     return(base.ParseModel(_context, _transaction));
 }
Beispiel #12
0
 public override void Validate(SioCmsContext _context = null, IDbContextTransaction _transaction = null)
 {
     if (MediaFile?.FileStream != null)
     {
         MediaFile.Filename   = SeoHelper.GetSEOString(MediaFile.Filename) + Guid.NewGuid().ToString("N");
         MediaFile.FileFolder = CommonHelper.GetFullPath(new[] {
             //SioService.GetConfig<string>("UploadFolder"),
             SioService.GetTemplateUploadFolder(Specificulture),
             DateTime.UtcNow.ToString("yyyy-MM")
         });;
         var isSaved = FileRepository.Instance.SaveWebFile(MediaFile);
         if (isSaved)
         {
             Extension  = MediaFile.Extension;
             FileName   = MediaFile.Filename;
             FileFolder = MediaFile.FileFolder;
         }
         else
         {
             IsValid = false;
         }
     }
     FileType = FileType ?? "image";
     base.Validate(_context, _transaction);
 }
        /// <summary>
        /// Gets all blog posts
        /// </summary>
        /// <param name="storeId">The store identifier; pass 0 to load all records</param>
        /// <param name="languageId">Language identifier. 0 if you want to get all news</param>
        /// <param name="tag">Tag</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>Blog posts</returns>
        public virtual IPagedList <BlogPost> GetAllBlogPostsByTag(
            int storeId,
            int languageId,
            string tag,
            int pageIndex,
            int pageSize,
            bool showHidden = false)
        {
            tag = tag.Trim();

            //we laod all records and only then filter them by tag
            var blogPostsAll    = GetAllBlogPosts(storeId, languageId, null, null, 0, int.MaxValue, showHidden);
            var taggedBlogPosts = new List <BlogPost>();

            foreach (var blogPost in blogPostsAll)
            {
                var tags = blogPost.ParseTags().Select(x => SeoHelper.GetSeName(x,
                                                                                _seoSettings.ConvertNonWesternChars,
                                                                                _seoSettings.AllowUnicodeCharsInUrls,
                                                                                _seoSettings.SeoNameCharConversion));

                if (!String.IsNullOrEmpty(tags.FirstOrDefault(t => t.Equals(tag, StringComparison.InvariantCultureIgnoreCase))))
                {
                    taggedBlogPosts.Add(blogPost);
                }
            }

            //server-side paging
            var result = new PagedList <BlogPost>(taggedBlogPosts, pageIndex, pageSize);

            return(result);
        }
        public static CommunitiesSearchVm GetCommunitiesSearchVm(CommunitiesSearchVm searchVm)
        {
            if (!ValidatePageNumber(searchVm.PageNumber))
            {
                return(null);
            }
            searchVm.ValidationResult = GetLookupLocationValidationVm(searchVm.SearchBar);
            if (!searchVm.ValidationResult.IsValid)
            {
                return(searchVm);
            }
            searchVm.Criteria  = searchVm.ValidationResult.Criteria;
            searchVm.SearchBar = GetSearchBarVm(searchVm);
            CommunitySearchModel         searchModel  = searchVm.ToCommunitySearchModel();
            FeaturedCommunitySearchModel searchModel2 = searchVm.ToFeaturedCommunitySearchModel();

            searchModel                  = SearchBc.Instance.SearchCommunities(searchModel);
            searchModel2                 = SearchBc.Instance.SearchFeaturedCommunities(searchModel2);
            searchVm.PageSize            = searchModel.PageSize;
            searchVm.TotalCount          = searchModel.Result.TotalCount;
            searchVm.Paging              = searchVm.MapToPagingVm();
            searchVm.Refine              = searchVm.MapToCommunityRefineVm();
            searchVm.Result              = searchModel.Result.Results.MapToCommunityBlockVmList(searchVm.Criteria.SearchType());
            searchVm.FeaturedCommunities = searchModel2.Result.MapToCommunityShortVmList(searchVm.Criteria.SearchType());
            PopulateFeaturedServices(searchVm);
            searchVm.Breadcrumbs = GetBreadcrumbs(searchVm);
            searchVm.LeadForm    = GetLeadFormVm(searchVm);
            searchVm.Seo         = SeoHelper.GetSeo(searchVm);
            return(searchVm);
        }
 /// <summary>
 /// Get SEO friendly name
 /// </summary>
 /// <param name="name">Name</param>
 /// <param name="seoSettings">SEO settings</param>
 /// <returns>Result</returns>
 public static string GetSeName(string name, SeoSettings seoSettings)
 {
     return(SeoHelper.GetSeName(
                name,
                seoSettings == null ? false : seoSettings.ConvertNonWesternChars,
                seoSettings == null ? false : seoSettings.AllowUnicodeCharsInUrls));
 }
        public static ServiceProvidersSearchVm GetServiceProvidersSearchVm(ServiceProvidersSearchVm searchVm)
        {
            if (!ValidatePageNumber(searchVm.PageNumber))
            {
                return(null);
            }
            searchVm.ValidationResult = GetLookupLocationValidationVm(searchVm.SearchBar);
            if (!searchVm.ValidationResult.IsValid)
            {
                return(searchVm);
            }
            searchVm.Criteria  = searchVm.ValidationResult.Criteria;
            searchVm.SearchBar = GetSearchBarVm(searchVm);
            ServiceProviderSearchModel searchModel = searchVm.ToServiceProviderSearchModel();

            searchModel         = SearchBc.Instance.SearchServiceProviders(searchModel);
            searchVm.PageSize   = searchModel.PageSize;
            searchVm.TotalCount = searchModel.Result.TotalCount;
            searchVm.Paging     = searchVm.MapToPagingVm();
            searchVm.Refine     = searchVm.MapToServiceProviderRefineVm();
            searchVm.Result     = searchModel.Result.Results.MapToServiceProviderBlockVmList();
            PopulateFeaturedServices(searchVm);
            searchVm.Breadcrumbs       = GetBreadcrumbs(searchVm);
            searchVm.LeadForm          = GetLeadFormVm(searchVm);
            searchVm.DisplayProperties = new SearchDisplayProperties();
            searchVm.Seo = SeoHelper.GetSeo(searchVm);
            return(searchVm);
        }
Beispiel #17
0
 private void ContentEvents_DeletingContent(object sender, ContentEventArgs e)
 {
     if (e.Content is SBRobotsTxt)
     {
         Task.Run(async() => await SeoHelper.RemoveRoute());
     }
 }
        public static CommunityDetailsVm GetCommunityDetailsVm(long communityId, PageType pageType)
        {
            CommunityDetailsVm result    = null;
            Community          community = SearchBc.Instance.GetCommunity(communityId);

            if (community != null)
            {
                result             = community.MapToCommunityDetailsVm(pageType);
                result.Breadcrumbs = GetBreadcrumbs(result);
                result.Seo         = SeoHelper.GetSeo(result);
                PopulateFeaturedServices(result, communityId);
                foreach (FloorPlanVm floorPlan in result.FloorPlans)
                {
                    floorPlan.LeadForm = GetLeadFormVm(floorPlan, communityId, pageType.ToSearchType());
                }
                foreach (SpecHomeVm specHome in result.SpecHomes)
                {
                    specHome.LeadForm = GetLeadFormVm(specHome, communityId, pageType.ToSearchType());
                }
                {
                    foreach (HomeVm home in result.Homes)
                    {
                        home.LeadForm = GetLeadFormVm(home, communityId, pageType.ToSearchType());
                    }
                    return(result);
                }
            }
            return(result);
        }
Beispiel #19
0
 private void Instance_PublishingPage(object sender, ContentEventArgs e)
 {
     if (e.Content is SBRobotsTxt content)
     {
         Task.Run(async() => await SeoHelper.AddRoute());
     }
 }
        public void OnHandleSeoValues_MultipleAttributes_AddsEntriesToCustomMetas()
        {
            // Arrange
            var seoHelper = new SeoHelper();

            var attribute1 = new CustomMetaAttribute(
                "TEST_META_CUSTOM_KEY1",
                "TEST_META_CUSTOM_VALUE1");
            var attribute2 = new CustomMetaAttribute(
                "TEST_META_CUSTOM_KEY2",
                "TEST_META_CUSTOM_VALUE1");
            var attribute3 = new CustomMetaAttribute(
                "TEST_META_CUSTOM_KEY2",
                "TEST_META_CUSTOM_VALUE2");

            // Act
            attribute1.OnHandleSeoValues(seoHelper);
            attribute2.OnHandleSeoValues(seoHelper);
            attribute3.OnHandleSeoValues(seoHelper);

            // Assert
            var customMetas = seoHelper.CustomMetas;

            Assert.Equal(2, customMetas.Count);
            Assert.Equal(
                "TEST_META_CUSTOM_VALUE1",
                customMetas["TEST_META_CUSTOM_KEY1"]);
            Assert.Equal(
                "TEST_META_CUSTOM_VALUE2",
                customMetas["TEST_META_CUSTOM_KEY2"]);
        }
Beispiel #21
0
        private void GenerateSEO()
        {
            if (string.IsNullOrEmpty(this.SeoName))
            {
                this.SeoName = SeoHelper.GetSEOString(this.Title);
            }
            int    i    = 1;
            string name = SeoName;

            while (Repository.CheckIsExists(a => a.SeoName == name && a.Specificulture == Specificulture && a.Id != Id))
            {
                name = SeoName + "_" + i;
                i++;
            }
            SeoName = name;

            if (string.IsNullOrEmpty(this.SeoTitle))
            {
                this.SeoTitle = SeoHelper.GetSEOString(this.Title);
            }

            if (string.IsNullOrEmpty(this.SeoDescription))
            {
                this.SeoDescription = SeoHelper.GetSEOString(this.Title);
            }

            if (string.IsNullOrEmpty(this.SeoKeywords))
            {
                this.SeoKeywords = SeoHelper.GetSEOString(this.Title);
            }
        }
Beispiel #22
0
		public override MixTheme ParseModel(MixCmsContext _context = null, IDbContextTransaction _transaction = null)
		{
			this.set_Id(1);
			this.set_Name(SeoHelper.GetSEOString(this.get_Title(), '-'));
			this.set_CreatedDateTime(DateTime.get_UtcNow());
			return this.ParseModel(_context, _transaction);
		}
Beispiel #23
0
        private void EnsureInitialized()
        {
            if (initialized)
            {
                return;
            }
            string connectionString = _fileSystemSettings.AzureUsingEmulator
                ? string.Format("UseDevelopmentStorage=true;")
                : string.Format(
                "DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
                _fileSystemSettings.AzureAccountName, _fileSystemSettings.AzureAccountKey);

            if (CloudStorageAccount.TryParse(connectionString, out _storageAccount))
            {
                CloudBlobClient cloudBlobClient = _storageAccount.CreateCloudBlobClient();
                _container =
                    cloudBlobClient.GetContainerReference(
                        SeoHelper.TidyUrl(
                            _fileSystemSettings.AzureContainerName.RemoveInvalidUrlCharacters()));
                if (_container.CreateIfNotExists())
                {
                    _container.SetPermissions(new BlobContainerPermissions
                    {
                        PublicAccess =
                            BlobContainerPublicAccessType.Blob
                    });
                }
                initialized = true;
            }
        }
Beispiel #24
0
        /// <summary>
        /// Get bundled file name
        /// </summary>
        /// <param name="parts">Parts to bundle</param>
        /// <returns>File name</returns>
        protected virtual string GetBundleFileName(string[] parts)
        {
            if (parts == null || parts.Length == 0)
            {
                throw new ArgumentException("parts");
            }

            //calculate hash
            var hash = string.Empty;

            using (SHA256 sha = new SHA256Managed())
            {
                // string concatenation
                var hashInput = string.Empty;
                foreach (var part in parts)
                {
                    hashInput += part;
                    hashInput += ",";
                }

                var input = sha.ComputeHash(Encoding.Unicode.GetBytes(hashInput));
                hash = WebEncoders.Base64UrlEncode(input);
            }

            //ensure only valid chars
            hash = SeoHelper.GetSeName(hash);

            return(hash);
        }
Beispiel #25
0
        /// <summary>
        /// Step 4
        ///     - Init default theme
        /// </summary>
        /// <param name="siteName"></param>
        /// <param name="_context"></param>
        /// <param name="_transaction"></param>
        /// <returns></returns>
        public async Task <RepositoryResponse <bool> > InitThemesAsync(string siteName
                                                                       , MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            UnitOfWorkHelper <MixCmsContext> .InitTransaction(_context, _transaction, out MixCmsContext context, out IDbContextTransaction transaction, out bool isRoot);

            var result = new RepositoryResponse <bool>()
            {
                IsSucceed = true
            };
            var getThemes = ViewModels.MixThemes.InitViewModel.Repository.GetModelList(_context: context, _transaction: transaction);

            if (!context.MixTheme.Any())
            {
                ViewModels.MixThemes.InitViewModel theme = new ViewModels.MixThemes.InitViewModel(new MixTheme()
                {
                    Id              = 1,
                    Title           = siteName,
                    Name            = SeoHelper.GetSEOString(siteName),
                    CreatedDateTime = DateTime.UtcNow,
                    CreatedBy       = "Admin",
                    Status          = (int)MixContentStatus.Published,
                }, context, transaction);

                var saveResult = await theme.SaveModelAsync(true, context, transaction);

                ViewModelHelper.HandleResult(saveResult, ref result);
            }
            UnitOfWorkHelper <MixCmsContext> .HandleTransaction(result.IsSucceed, isRoot, transaction);

            return(new RepositoryResponse <bool>()
            {
                IsSucceed = result.IsSucceed
            });
        }
Beispiel #26
0
        [RequestFormSizeLimit(valueCountLimit: 214748364)] // 200Mb
        public async Task <RepositoryResponse <Cms.Lib.ViewModels.MixThemes.InitViewModel> > Save([FromForm] string model, [FromForm] IFormFile assets, [FromForm] IFormFile theme)
        {
            var json = JObject.Parse(model);
            var data = json.ToObject <Lib.ViewModels.MixThemes.InitViewModel>();

            if (theme != null)
            {
                string importFolder = $"Imports/Themes/{DateTime.UtcNow.ToString("dd-MM-yyyy")}/{data.Name}";
                FileRepository.Instance.SaveWebFile(theme, theme.FileName, importFolder);
                data.TemplateAsset = new Lib.ViewModels.FileViewModel(theme, importFolder);
            }
            else
            {
                if (data.IsCreateDefault)
                {
                    data.TemplateAsset = new Lib.ViewModels.FileViewModel()
                    {
                        Filename   = "default",
                        Extension  = ".zip",
                        FileFolder = "Imports/Themes"
                    };
                }
                else
                {
                    data.TemplateAsset = new Lib.ViewModels.FileViewModel()
                    {
                        Filename   = "default_blank",
                        Extension  = ".zip",
                        FileFolder = "Imports/Themes"
                    };
                }
            }

            if (data != null)
            {
                string culture = MixService.GetConfig <string>("DefaultCulture");
                data.Title          = MixService.GetConfig <string>("SiteName", culture);
                data.Name           = SeoHelper.GetSEOString(data.Title);
                data.CreatedBy      = User.Claims.FirstOrDefault(c => c.Type == "Username")?.Value ?? "Init";
                data.Specificulture = _lang;
                var result = await data.SaveModelAsync(true);

                if (result.IsSucceed)
                {
                    // MixService.SetConfig<string>("SiteName", _lang, data.Title);
                    MixService.LoadFromDatabase();
                    MixService.SetConfig("InitStatus", 3);
                    MixService.SetConfig("IsInit", false);
                    MixService.SaveSettings();
                    _ = MixCacheService.RemoveCacheAsync();
                    MixService.Reload();
                }
                return(result);
            }
            return(new RepositoryResponse <Lib.ViewModels.MixThemes.InitViewModel>()
            {
                Status = 501
            });
        }
Beispiel #27
0
        protected async Task <List <TView> > GetListAsync <TView>(Expression <Func <TModel, bool> > predicate, string key, ODataQueryOptions <TModel> queryOptions)
            where TView : ODataViewModelBase <TDbContext, TModel, TView>
        {
            if (queryOptions.Filter != null)
            {
                ODataHelper <TModel> .ParseFilter(queryOptions.Filter.FilterClause.Expression, ref predicate);
            }
            int?          top     = queryOptions.Top?.Value;
            var           skip    = queryOptions.Skip?.Value ?? 0;
            RequestPaging request = new RequestPaging()
            {
                PageIndex = 0,
                PageSize  = top.HasValue ? top + top * (skip / top + 1) : null,
                OrderBy   = queryOptions.OrderBy?.RawValue
                            //Top = queryOptions.Top?.Value,
                            //Skip = queryOptions.Skip?.Value
            };
            var          cacheKey = $"odata_{_lang}_{typeof(TView).FullName}_{key}_{SeoHelper.GetSEOString(queryOptions.Filter?.RawValue, '_')}_ps-{request.PageSize}";
            List <TView> data     = null;

            //if (MixService.GetConfig<bool>("IsCache"))
            //{
            //    var getData = await MixCacheService.GetAsync<RepositoryResponse<PaginationModel<TView>>>(cacheKey);
            //    if (getData != null)
            //    {
            //        data = getData.Data.Items;
            //    }
            //}

            if (data == null)
            {
                if (predicate != null)
                {
                    var getData = await ODataDefaultRepository <TDbContext, TModel, TView> .Instance.GetModelListByAsync(predicate,
                                                                                                                         request.OrderBy, request.Direction, request.PageSize, request.PageIndex, request.Skip, request.Top).ConfigureAwait(false);

                    //if (getData.IsSucceed)
                    //{
                    //    await MixCacheService.SetAsync(cacheKey, getData);
                    //    data = getData.Data.Items;
                    //}
                }
                else
                {
                    var getData = await ODataDefaultRepository <TDbContext, TModel, TView> .Instance.GetModelListAsync(
                        request.OrderBy, request.Direction, request.PageSize, request.PageIndex
                        , null, null).ConfigureAwait(false);

                    //if (getData.IsSucceed)
                    //{
                    //    await MixCacheService.SetAsync(cacheKey, getData);
                    //    data = getData.Data.Items;
                    //}
                }
            }

            return(data);
        }
Beispiel #28
0
        public override RepositoryResponse <bool> SaveSubModels(MixTheme parent, MixCmsContext _context = null, IDbContextTransaction _transaction = null)
        {
            RepositoryResponse <bool> result = new RepositoryResponse <bool>()
            {
                IsSucceed = true
            };

            // Create default template if create new without import template assets
            if (Id == 0 && (TemplateAsset.Content == null && TemplateAsset.FileStream == null))
            {
                string defaultFolder = CommonHelper.GetFullPath(new string[] {
                    MixConstants.Folder.TemplatesFolder,
                    "Default"
                });
                bool   copyResult          = FileRepository.Instance.CopyDirectory(defaultFolder, TemplateFolder);
                string defaultAssetsFolder = CommonHelper.GetFullPath(new string[] {
                    MixConstants.Folder.WebRootPath,
                    MixConstants.Folder.FileFolder,
                    MixConstants.Folder.TemplatesAssetFolder,
                    "Default"
                });
                copyResult = FileRepository.Instance.CopyDirectory(defaultAssetsFolder, CommonHelper.GetFullPath(new string[] {
                    MixConstants.Folder.WebRootPath, AssetFolder
                }));

                var files = FileRepository.Instance.GetFilesWithContent(TemplateFolder);
                //TODO: Create default asset
                foreach (var file in files)
                {
                    string content = file.Content.Replace($"/Content/Templates/Default/",
                                                          $"/Content/Templates/{SeoHelper.GetSEOString(Name)}/");
                    MixTemplates.InitViewModel template = new MixTemplates.InitViewModel(
                        new MixTemplate()
                    {
                        FileFolder      = file.FileFolder,
                        FileName        = file.Filename,
                        Content         = content,
                        Extension       = file.Extension,
                        CreatedDateTime = DateTime.UtcNow,
                        LastModified    = DateTime.UtcNow,
                        ThemeId         = Model.Id,
                        ThemeName       = Model.Name,
                        FolderType      = file.FolderName,
                        ModifiedBy      = CreatedBy
                    }, _context, _transaction);
                    var saveResult = template.SaveModel(true, _context, _transaction);
                    result.IsSucceed = result.IsSucceed && saveResult.IsSucceed;
                    if (!saveResult.IsSucceed)
                    {
                        result.Exception = saveResult.Exception;
                        result.Errors.AddRange(saveResult.Errors);
                        break;
                    }
                }
            }

            return(result);
        }
Beispiel #29
0
        public void TestIndexValidatedSlug()
        {
            var expectedUrl = SeoHelper.ValidateSlug(this.redirectConsumerId, this.expectedUrl);
            var controller  = new AdvisorsController();
            var response    = controller.Index(this.redirectConsumerId);

            Assert.AreEqual(expectedUrl, (response as RedirectResult).Url);
            Assert.IsInstanceOfType(response, typeof(RedirectResult));
        }
Beispiel #30
0
        public static async Task <RepositoryResponse <InitViewModel> > InitTheme(string model, string userName, string culture, IFormFile assets, IFormFile theme)
        {
            var json = JObject.Parse(model);
            var data = json.ToObject <InitViewModel>();

            if (data != null)
            {
                data.CreatedBy = userName;
                data.Status    = MixContentStatus.Published;
                string importFolder = $"{MixFolders.ImportFolder}/" +
                                      $"{DateTime.UtcNow.ToString("dd-MM-yyyy")}";
                if (theme != null)
                {
                    MixFileRepository.Instance.SaveWebFile(theme, $"{importFolder}");
                    data.TemplateAsset = new FileViewModel(theme, importFolder);
                }
                else
                {
                    if (data.IsCreateDefault)
                    {
                        data.TemplateAsset = new FileViewModel()
                        {
                            Filename   = "default",
                            Extension  = MixFileExtensions.Zip,
                            FileFolder = MixFolders.ImportFolder
                        };
                    }
                    else
                    {
                        data.TemplateAsset = new FileViewModel()
                        {
                            Filename   = "default_blank",
                            Extension  = MixFileExtensions.Zip,
                            FileFolder = MixFolders.ImportFolder
                        };
                    }
                }

                data.Title          = MixService.GetConfig <string>(MixAppSettingKeywords.SiteName, culture);
                data.Name           = SeoHelper.GetSEOString(data.Title);
                data.Specificulture = culture;
                var result = await data.SaveModelAsync(true);

                if (result.IsSucceed)
                {
                    // MixService.SetConfig<string>(MixAppSettingKeywords.SiteName, _lang, data.Title);
                    MixService.LoadFromDatabase();
                    MixService.SetConfig("InitStatus", 3);
                    MixService.SetConfig(MixAppSettingKeywords.IsInit, false);
                    MixService.SaveSettings();
                    _ = Mix.Services.MixCacheService.RemoveCacheAsync();
                    MixService.Reload();
                }
                return(result);
            }
            return(new RepositoryResponse <InitViewModel>());
        }
 public void PopulateSeo(SeoHelper seoHelper)
 {
     seoHelper.Title = string.Format("Search: {0}", this.SearchTermFormatted);
 }
        public virtual void PopulateSeo(SeoHelper seoHelper)
        {
            seoHelper.Title = this.PageTitle;

            if (this.ArticlePage.ArticleAccess.CanRead > ArticleAccessLevel.Anonymous)
            {
                seoHelper.MetaNoIndex = true;
            }
        }
 public void PopulateSeo(SeoHelper seoHelper)
 {
     seoHelper.Title = string.Format("Articles tagged with '{0}'", this.TagName);
     seoHelper.CanonicalUrl = this.UrlHelper.ListsTaggedArticles(this.TagName);
 }
        public override void PopulateSeo(SeoHelper seoHelper)
        {
            base.PopulateSeo(seoHelper);

            string canonicalUrl = null;

            if (this.IsWikiIndex)
            {
                canonicalUrl = this.UrlHelper.WikiIndex();
            }
            else if (this.HasContent)
            {
                canonicalUrl = this.UrlHelper.WikiArticle(this.ArticleSlug);
            }

            seoHelper.CanonicalUrl = canonicalUrl;
        }