Exemple #1
0
        protected virtual FontFamily LoadFontFamilyFromDisk(string fileName)
        {
            var cache    = MemoryCache.Default;
            var cacheKey = $"geta.fontawesome.disk.fontcollection.{fileName}";

            if (!(cache[cacheKey] is PrivateFontCollection fontCollection))
            {
                var customFontFolder = ConfigurationManager.AppSettings[Constants.AppSettings.CustomFontPath] ?? Constants.DefaultCustomFontPath;
                var fontPath         = $"{customFontFolder}{fileName}";

                var rebased = VirtualPathUtilityEx.RebasePhysicalPath(fontPath);

                try
                {
                    fontCollection = new PrivateFontCollection();
                    fontCollection.AddFontFile(rebased);
                    RemoveFontResourceEx(rebased, 16, IntPtr.Zero);
                    cache.Set(cacheKey, fontCollection, DateTimeOffset.Now.AddMinutes(5));
                }
                catch (Exception ex)
                {
                    throw new Exception($"Unable to load custom font from path {fontPath}", ex);
                }
            }

            return(fontCollection.Families[0]);
        }
        public override string GetFileHash(string virtualPath, IEnumerable virtualPathDependencies)
        {
            if (IsAppResourcePath(virtualPath))
            {
                var pathRelative  = VirtualPathUtilityEx.ToAppRelative(virtualPath);
                var stringBuilder = new StringBuilder();
                stringBuilder.Append(GetLocalFileHash(virtualPath));
                if (virtualPathDependencies != null)
                {
                    foreach (string path in virtualPathDependencies.OfType <string>().OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
                    {
                        if (!IsAppResourcePath(path))
                        {
                            stringBuilder.Append(base.GetFileHash(path, new[] { path }));
                        }
                        else
                        {
                            stringBuilder.Append(GetLocalFileHash(path));
                        }
                    }
                }

                foreach (var module in ModuleAssembly.GetLoadedModules().OrderBy(m => m.Name, StringComparer.OrdinalIgnoreCase))
                {
                    stringBuilder.Append(module.ModuleVersionId.ToString());
                }

                return(stringBuilder.ToString().GetHashCode().ToString("x", CultureInfo.InvariantCulture));
            }
            return(Previous.GetFileHash(virtualPath, virtualPathDependencies));
        }
Exemple #3
0
        private static string CreateFileName(Video video)
        {
            var name      = CleanString(video.Title);
            var extension = VirtualPathUtilityEx.GetExtension(video.OriginalUrl);

            return(string.Format("{0}-{1}{2}", video.VideoId, name, extension));
        }
Exemple #4
0
        public static string GetVideoIdByVirtualPath(string virtualPath)
        {
            var path     = VirtualPathUtilityEx.ToAppRelative(virtualPath);
            var segments = path.Split('/');

            if (segments.Length < 3)
            {
                return(string.Empty);
            }

            var fileName       = segments[2];
            var idxOfSeparator = fileName.IndexOf('-');
            var id             = fileName.Length > idxOfSeparator && idxOfSeparator > 0
                        ? fileName.Substring(0, idxOfSeparator)
                        : string.Empty;

            int x;

            if (int.TryParse(id, out x))
            {
                return(id);
            }

            return(string.Empty);
        }
Exemple #5
0
 /// <summary>
 /// Requires the client resources used in the view.
 /// </summary>
 private void RequireClientResources()
 {
     // jQuery.UI is used in autocomplete example.
     // Add jQuery.UI files to existing client resource bundles or load it from CDN or use any other alternative library.
     // We use local resources for demo purposes without Internet connection.
     requiredClientResourceList.RequireStyle(VirtualPathUtilityEx.ToAbsolute("~/Static/css/jquery-ui.css"));
     requiredClientResourceList.RequireScript(VirtualPathUtilityEx.ToAbsolute("~/Static/js/jquery-ui.js")).AtFooter();
 }
        public GeoLocationResult GetGeoLocation(IPAddress address, NameValueCollection config)
        {
            string text = config["databaseFileName"];

            if (!string.IsNullOrEmpty(text))
            {
                maxMindDatabaseFileName = VirtualPathUtilityEx.RebasePhysicalPath(text);
                config.Remove("databaseFileName");
            }

            if (string.IsNullOrWhiteSpace(maxMindDatabaseFileName))
            {
                throw new ArgumentException("db name is not provided");
            }

            if (!System.IO.File.Exists(maxMindDatabaseFileName))
            {
                throw new ArgumentException(string.Format("db does not exist at location {0}", maxMindDatabaseFileName));
            }

            if (address.AddressFamily != AddressFamily.InterNetwork &&
                address.AddressFamily != AddressFamily.InterNetworkV6)
            {
                return(null);
            }

            try
            {
                using (var reader = new DatabaseReader(maxMindDatabaseFileName))
                {
                    var dbResult = reader.City(address);

                    if (dbResult == null)
                    {
                        return(null);
                    }

                    GeoLocationResult result = new GeoLocationResult();
                    result.CountryCode    = dbResult.Country.IsoCode;
                    result.CountryName    = dbResult.Country.Name;
                    result.Latitude       = dbResult.Location.Latitude ?? 0;
                    result.Longitude      = dbResult.Location.Longitude ?? 0;
                    result.MetroCode      = dbResult.Location.MetroCode ?? 0;
                    result.City           = dbResult.City.Name;
                    result.PostalCode     = dbResult.Postal.Code;
                    result.CountinentCode = dbResult.Continent.Code;
                    result.Region         = dbResult?.MostSpecificSubdivision?.IsoCode;
                    result.RegionName     = dbResult.MostSpecificSubdivision?.Name;
                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #7
0
        /// <summary>
        /// Initialize the provider
        /// </summary>
        /// <param name="name">name of provider</param>
        /// <param name="config">provider settings</param>
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config.Get("path") != null)
            {
                Path = VirtualPathUtilityEx.RebasePhysicalPath(config.Get("path"));
            }

            if (config.Get("Activated") != null)
            {
                Activated = bool.Parse(config.Get("Activated").ToLower());
            }
            else
            {
                Activated = false;
            }


            if (config.Get("UrlResolverUrl") != null)
            {
                UrlResolverUrl = config.Get("UrlResolverUrl");
            }
            else
            {
                UrlResolverUrl = DefaultUrl;
            }

            if (Activated)
            {
                if (config.Get("ProdUrl") != null)
                {
                    ProdUrl = config.Get("ProdUrl");
                }
                else
                {
                    EPiServer.Framework.Validator.ThrowIfNullOrEmpty("ProdUrl", ProdUrl);
                }

                if (config.Get("RestrictedFileExt") != null)
                {
                    RestrictedFileExt = config.Get("RestrictedFileExt");
                }
            }

            //
            base.Initialize(name, config);
        }
        private bool IsAppResourceDir(string virtualPath)
        {
            if (string.IsNullOrEmpty(virtualPath))
            {
                return(false);
            }

            try
            {
                String checkPath = VirtualPathUtilityEx.ToAppRelative(virtualPath);
                return(checkPath.EndsWith("/") && checkPath.StartsWith(ModuleRootPath, StringComparison.OrdinalIgnoreCase));
            }
            catch (HttpException)
            {
                return(false);
            }
        }
Exemple #9
0
        public ActionResult DumpMemory(MemoryDumpModel memoryDumpModel)
        {
            if (String.IsNullOrEmpty(memoryDumpModel.FilePath))
            {
                memoryDumpModel.FilePath = VirtualPathUtilityEx.RebasePhysicalPath("[appDataPath]\\Dumps");
            }
            if (!Directory.Exists(memoryDumpModel.FilePath))
            {
                Directory.CreateDirectory(memoryDumpModel.FilePath);
            }

            string timeforfileName = DateTime.Now.ToString().Replace('/', '_').Replace(':', '_');
            string name            = string.Concat(memoryDumpModel.FilePath.LastIndexOf('/') == -1 ? memoryDumpModel.FilePath + '\\':memoryDumpModel.FilePath, Process.GetCurrentProcess().ProcessName + "_" + timeforfileName, ".dmp");

            MiniDump.WriteDump(name, memoryDumpModel.SelectedDumpType);
            memoryDumpModel.Name = name;
            return(View(memoryDumpModel));
        }
        public static string GetResourcePath(string path)
        {
            string checkPath = VirtualPathUtilityEx.ToAppRelative(path);

            if (checkPath.StartsWith(AssemblyResourceProvider.ModuleRootPath, StringComparison.OrdinalIgnoreCase))
            {
                var relative = checkPath.Substring(AssemblyResourceProvider.ModuleRootPath.Length);

                if (relative.StartsWith("Scripts/", StringComparison.OrdinalIgnoreCase) ||
                    relative.Equals("module.config", StringComparison.OrdinalIgnoreCase))
                {
                    var resourcePath = ModuleAssembly.GetName().Name + "." + relative.Replace('/', '.');

                    return(resourcePath);
                }
            }
            return(null);
        }
Exemple #11
0
        protected virtual FontFamily LoadFontFamilyFromDisk(string fileName, out PrivateFontCollection fontCollection)
        {
            string customFontFolder = ConfigurationManager.AppSettings["FontThumbnail.CustomFontPath"] ?? Constants.DefaultCustomFontPath;
            string fontPath         = $"{customFontFolder}{fileName}";

            var rebased = VirtualPathUtilityEx.RebasePhysicalPath(fontPath);

            try
            {
                fontCollection = new PrivateFontCollection();
                fontCollection.AddFontFile(rebased);
                RemoveFontResourceEx(rebased, 16, IntPtr.Zero);
                return(fontCollection.Families[0]);
            }
            catch (Exception ex)
            {
                throw (new Exception($"Unable to load custom font from path {fontPath}", ex));
            }
        }
Exemple #12
0
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config.Get(PathKey) != null)
            {
                Path = VirtualPathUtilityEx.RebasePhysicalPath(config.Get(PathKey));
            }
            Validator.ThrowIfNullOrEmpty(PathKey, this.Path);
            if (config.Get(LoadFromDiskKey) != null)
            {
                LoadFromDisk = bool.Parse((config.Get(LoadFromDiskKey)));
            }
            var events = ServiceLocator.Current.GetInstance <IContentEvents>();

            if (LoadFromDisk)
            {
                events.DeletingContent += DeleteSqlBlobProviderFiles;
            }
            base.Initialize(name, config);
        }
        public void Initialize(InitializationEngine context)
        {
            if (_initialized || context.HostType != HostType.WebApplication)
            {
                return;
            }

            // the route for the controller responsible for generating or loading the image from disk
            RouteTable.Routes.MapRoute("ThumbnailIcon", Constants.UrlFragment, new { controller = "ThumbnailIcon", action = "GenerateThumbnail" });

            // verify cache directory exists
            string fullPath = VirtualPathUtilityEx.RebasePhysicalPath(Constants.DefaultCachePath);

            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
            }

            _initialized = true;
        }
Exemple #14
0
        public ThumbnailIconControllerFixture()
        {
            var partialDirectory = $"[appDataPath]\\thumb_cache\\{Guid.NewGuid()}\\";

            ConfigurationManager.AppSettings["FontThumbnail.CachePath"] = partialDirectory;
            _temporaryDirectory = VirtualPathUtilityEx.RebasePhysicalPath(partialDirectory);

            Directory.CreateDirectory(_temporaryDirectory);

            var service = new FontThumbnailService();

            Controller = new ThumbnailIconController(service);
            Settings   = new ThumbnailSettings
            {
                FontSize        = Constants.DefaultFontSize,
                BackgroundColor = Constants.DefaultBackgroundColor,
                ForegroundColor = Constants.DefaultForegroundColor,
                Height          = Constants.DefaultHeight,
                Width           = Constants.DefaultWidth
            };
        }
Exemple #15
0
        protected virtual string GetFileFullPath(string fileName)
        {
            string rootPath = ConfigurationManager.AppSettings["FontThumbnail.CachePath"] ?? Constants.DefaultCachePath;

            return(VirtualPathUtilityEx.RebasePhysicalPath(rootPath + fileName));
        }
 public MemoryDumpModel()
 {
     SelectedDumpValue = Enum.GetName(typeof(DumpType), DumpType.MiniDumpWithFullMemory);
     FilePath          = VirtualPathUtilityEx.RebasePhysicalPath("[appDataPath]\\Dumps");
 }
Exemple #17
0
 public SqlBlobProvider(string path, bool loadFromDisk)
 {
     LoadFromDisk = loadFromDisk;
     Path         = VirtualPathUtilityEx.RebasePhysicalPath(path);
 }
        /// <summary>
        /// Initialize the provider
        /// </summary>
        /// <param name="name">name of provider</param>
        /// <param name="config">provider settings</param>
        public override void Initialize(string name, NameValueCollection config)
        {
            if (config.Get("path") != null)
            {
                Path = VirtualPathUtilityEx.RebasePhysicalPath(config.Get("path"));
            }

            if (config.Get("Activated") != null)
            {
                Activated = bool.Parse(config.Get("Activated").ToLower());
            }
            else
            {
                Activated = false;
            }


            if (config.Get("UrlResolverUrl") != null)
            {
                UrlResolverUrl = config.Get("UrlResolverUrl");
            }
            else
            {
                UrlResolverUrl = DefaultUrl;
            }

            if (Activated)
            {
                if (config.Get("ProdUrl") != null)
                {
                    ProdUrl = config.Get("ProdUrl");
                }
                else
                {
                    EPiServer.Framework.Validator.ThrowIfNullOrEmpty("ProdUrl", ProdUrl);
                }

                if (config.Get("RestrictedFileExt") != null)
                {
                    RestrictedFileExt = config.Get("RestrictedFileExt");
                }
            }

            // Setup the shared httpClient
            var cookieContainer = new CookieContainer();
            var handler         = new HttpClientHandler()
            {
                CookieContainer = cookieContainer
            };

            _httpClient = new HttpClient(handler);

            if (config.Get("Cookies") != null)
            {
                var cookies = config.Get("Cookies").Split(';');

                foreach (var cookie in cookies)
                {
                    var splitCookie = cookie.Split('=');
                    if (splitCookie.Length == 2)
                    {
                        cookieContainer.Add(new Uri(ProdUrl), new Cookie(splitCookie[0], splitCookie[1]));
                        Logger.Debug($"Added Cookie {splitCookie[0]} with value {splitCookie[1]} to requests");
                    }
                }
            }

            base.Initialize(name, config);
        }
 public AssemblyResourceVirtualFile(string virtualPath)
     : base(virtualPath)
 {
     path = VirtualPathUtilityEx.ToAppRelative(virtualPath);
 }