Ejemplo n.º 1
0
 public async Task <List <User> > GetAllUsers()
 {
     using (var request = InitRequest())
     {
         return(await CachedFile.TryLoad <List <User> >($"{UrlBase}{UrlUser}", new TimeSpan(0), false, false, request));
     }
 }
Ejemplo n.º 2
0
        private void HandleGETRequest()
        {
            foreach (KeyValuePair <string, CompiledScriptRequestHandler> csrh in this.m_Server.CompiledRequestHandlers)
            {
                if (csrh.Key == this.RequestData.URL)
                {
                    csrh.Value(this);
                    return;
                }
            }

            CachedFile file = null;

            if (this.m_Server.UseCache)
            {
                file = this.m_Server.Cache.GetFile(PathExtensions.Combine(this.m_Server.HomeDirectory, this.RequestData.LocalURL));
            }
            else
            {
                file = new CachedFile()
                {
                    FileName = PathExtensions.Combine(this.m_Server.HomeDirectory, this.RequestData.LocalURL)
                };
                file.ReadFileContents();
            }
            if (file.Valid)
            {
                this.WriteSuccess();
                this.OutputStream.BaseStream.Write(file.Data, 0, file.Data.Length);
            }
            else
            {
                this.WriteFailure();
            }
        }
Ejemplo n.º 3
0
        public static string CacheTextFile(string sprocketPath, bool condenseJavaScript)
        {
            string   path     = HttpContext.Current.Request.PhysicalApplicationPath + '\\' + sprocketPath.Replace('/', '\\').Trim('\\');
            DateTime modified = new FileInfo(path).LastWriteTime;

            HttpContext.Current.Application.Lock();
            if (txtFileCache.ContainsKey(path))
            {
                if (txtFileCache[path].FileDate == modified)
                {
                    HttpContext.Current.Application.UnLock();
                    return(txtFileCache[path].FileText);
                }
                txtFileCache.Remove(path);
            }
            StreamReader sr  = new StreamReader(path, Encoding.Default);
            string       txt = sr.ReadToEnd();

            sr.Close();
            CachedFile file = new CachedFile();

            file.FileDate = modified;
            file.FileText = condenseJavaScript ? JavaScriptCondenser.Condense(txt) : txt;
            txtFileCache.Add(path, file);
            HttpContext.Current.Application.UnLock();
            return(txt);
        }
Ejemplo n.º 4
0
 private string _ReadFromTestSubject()
 {
     using (var testSubject = new CachedFile(_backingFile))
     {
         return(testSubject.Contents);
     }
 }
Ejemplo n.º 5
0
 public async Task <User> GetUser(Guid userID)
 {
     using (var request = InitRequest())
     {
         return(await CachedFile.TryLoad <User>($"{UrlBase}{UrlUser}/{userID}", new TimeSpan(0, 5, 0), false, false, request));
     }
 }
Ejemplo n.º 6
0
 private void _WriteToTestSubject(string valueWritten)
 {
     using (var testSubject = new CachedFile(_backingFile, requireToExistAlready: null))
     {
         testSubject.Contents = valueWritten;
     }
 }
Ejemplo n.º 7
0
 public async Task <Activity> GetActivity(Guid iD)
 {
     using (var request = InitRequest())
     {
         return(await CachedFile.TryLoad <Activity>($"{UrlBase}{UrlGetActivity}/{iD}", new TimeSpan(0), false, true, request));
     }
 }
Ejemplo n.º 8
0
 public async Task <List <UserActivity> > GetActivitySubscribers(Guid iD)
 {
     using (var request = InitRequest())
     {
         return(await CachedFile.TryLoad <List <UserActivity> >($"{UrlBase}{UrlActivitySubscribers}/{iD}", new TimeSpan(0), false, true, request));
     }
 }
Ejemplo n.º 9
0
        public static string CacheWebFile(string sprocketRequestPath, string sprocketHtmlFilePath)
        {
            string path    = HttpContext.Current.Request.PhysicalApplicationPath + '\\' + sprocketHtmlFilePath.Replace('/', '\\').Trim('\\');
            string refpath = MakeReferencePath(sprocketRequestPath, sprocketHtmlFilePath);

            DateTime modified = new FileInfo(path).LastWriteTime;

            if (htmlFileCache.ContainsKey(path))
            {
                if (htmlFileCache[path].FileDate == modified)
                {
                    return(htmlFileCache[path].FileText.Replace("[~]", refpath));
                }
                htmlFileCache.Remove(path);
            }
            StreamReader sr  = new StreamReader(path);
            string       txt = sr.ReadToEnd();

            sr.Close();
            string       replace  = "${1}[~]";
            string       pattern1 = "(?<1>(?:(?:src=)|(?:href=)|(?:background=))(?:'|\"))(?!#|/|([a-zA-Z]+://))";
            string       pattern2 = "(?<1>@(?:(?:import)|(?:url)) *(?:'|\"|\\())(?!#|/|([a-zA-Z]+://))";
            RegexOptions options  = RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;

            txt = Regex.Replace(txt, pattern1, replace, options);
            txt = Regex.Replace(txt, pattern2, replace, options);

            CachedFile file = new CachedFile();

            file.FileDate = modified;
            file.FileText = txt;
            htmlFileCache.Add(path, file);
            return(txt.Replace("[~]", refpath));
        }
Ejemplo n.º 10
0
 public async Task <User> GetCurrentUser()
 {
     using (var request = InitRequest())
     {
         return(await CachedFile.TryLoad <User>(UrlBase + UrlUser + "/me", new TimeSpan(0), false, false, request));
     }
 }
Ejemplo n.º 11
0
        static public CachedFile CreateFile(string in_file_name, UInt32 in_unique_device_id)
        {
            string     full_path   = Path.Combine(GetFileCachePath(), in_file_name);
            CachedFile cached_file = new CachedFile();

            cached_file.Create(full_path);

            return(cached_file);
        }
Ejemplo n.º 12
0
        public async Task <bool> CheckCredentials()
        {
            using (var request = InitRequest())
            {
                return(await CachedFile.TryLoad <bool>(UrlBase + UrlLogin, new TimeSpan(0), false, false, request));

                //var content = await request.GetStringAsync(UrlBase + UrlLogin);
                //return JsonConvert.DeserializeObject<bool>(content);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Get the list of all public activities
        /// </summary>
        /// <returns></returns>
        public async Task <List <Activity> > GetAllPublicActivities()
        {
            using (var request = InitRequest())
            {
                return(await CachedFile.TryLoad <List <Activity> >(UrlBase + UrlActivities, new TimeSpan(0), false, false, request));

                //var content = await request.GetStringAsync(UrlBase + UrlActivities);
                //return JsonConvert.DeserializeObject<List<Activity>>(content);
            }
        }
Ejemplo n.º 14
0
        public static string CacheTextFile(string sprocketPath, bool condenseJavaScript)
        {
            string   path     = HttpContext.Current.Request.PhysicalApplicationPath + '\\' + sprocketPath.Replace('/', '\\').Trim('\\');
            DateTime modified = new FileInfo(path).LastWriteTime;

            HttpContext.Current.Application.Lock();
            if (txtFileCache.ContainsKey(path))
            {
                if (txtFileCache[path].FileDate == modified)
                {
                    HttpContext.Current.Application.UnLock();
                    return(txtFileCache[path].FileText);
                }
                txtFileCache.Remove(path);
            }
            StreamReader sr  = new StreamReader(path, Encoding.Default);
            string       txt = sr.ReadToEnd();

            sr.Close();
            CachedFile file = new CachedFile();

            file.FileDate = modified;
            if (condenseJavaScript)
            {
                if (sprocketPath.EndsWith(".js"))
                {
                    file.FileText = JavaScriptCondenser.Condense(txt);
                }
                else if (sprocketPath.EndsWith(".htm"))
                {
                    foreach (Match match in Regex.Matches(txt, @"\<script\>(?<js>([\s\S](?!\/script\>))*)\</script\>",
                                                          RegexOptions.IgnoreCase | RegexOptions.Multiline))
                    {
                        txt = txt.Replace(match.Value, "<script>" + JavaScriptCondenser.Condense(match.Groups["js"].Value) + "</script>");
                    }
                    file.FileText = txt;
                }
                else
                {
                    file.FileText = txt;
                }
            }
            else
            {
                file.FileText = txt;
            }
            //file.FileText = condenseJavaScript ? JavaScriptCondenser.Condense(txt) : txt;
            txtFileCache.Add(path, file);
            HttpContext.Current.Application.UnLock();
            return(txt);
        }
        public HttpResponse Handle(IHttpRequest req)
        {
            var requestedFilename = HttpUtility.UrlDecode(req.Path.Substring(reqPathFilenameStartIndex));
            var absFilename       = Path.GetFullPath(Path.Combine(directory, requestedFilename));

            if (!absFilename.StartsWith(directory))
            {
                return(Forbidden);
            }

            var fileInfo = new FileInfo(absFilename);

            if (!fileInfo.Exists) // cached but deleted
            {
                return(NotFound);
            }

            DateTime     ifModifiedSince;
            CachedFile   cachedFile;
            HttpResponse response;

            if (req.TryGetIfLastModifiedSince(out ifModifiedSince) && fileInfo.LastWriteTimeUtc <= ifModifiedSince)
            {
                // Remote client (browser) has a valid cached copy (we may not have it in cache yet though eg. server restarted)
                response = new HttpResponse(HttpStatusCode.NotModified, MimeMapping.GetMimeMapping(fileInfo.Name));
            }
            else if (cache.TryGetValue(absFilename, out cachedFile) && fileInfo.LastWriteTimeUtc <= cachedFile.LastModified)
            {
                // Dictionary cached copy is still valid
                response = req.IsAcceptGZip() ? cachedFile.GZippedResponse : cachedFile.Response;
            }
            else
            {
                // Load fresh from disk
                if (fileInfo.Length <= maxFileLengthToCache)
                {
                    var fileResponse        = new FileResponse.Buffered(fileInfo);
                    var gzippedFileResponse = gzipFunc(fileResponse);
                    cache[absFilename] = new CachedFile(fileResponse, gzippedFileResponse);
                    response           = req.IsAcceptGZip() ? gzippedFileResponse : fileResponse;
                }
                else
                {
                    response = new FileResponse.Stream(fileInfo);
                }
            }

            return(response);
        }
Ejemplo n.º 16
0
        public void FileDataTest()
        {
            CachedChunk chunk = new CachedChunk(TestArchive.Chunks[0], cache);
            CachedFile  file  = chunk.Files[0];

            using (MemoryStream mem = new MemoryStream())
                using (Stream decomp = file.GetStream())
                {
                    decomp.CopyTo(mem);

                    byte[] LoadedData = mem.ToArray();

                    Assert.IsTrue(PPeX.Utility.CompareBytes(LoadedData, TestData), "File data is not consistent.");
                }
        }
Ejemplo n.º 17
0
        public void TestSaveAndLoad()
        {
            CachedFile<DummyData> test = new CachedFile<DummyData>();
            test.Key = "test";
            test.Expires = DateTime.Now.AddMinutes(1);
            test.DataCollection = new System.Collections.Generic.Dictionary<string, DummyData>()
            {
                {"test1",new DummyData(){ Key="test1", JunkString="test1s"}},
                {"test2",new DummyData(){ Key="test2", JunkString="test2s"}},
            };

            CachedFileAccess.WriteCache<DummyData>(test, "");

            CachedFile<DummyData> readed = CachedFileAccess.ReadCache<DummyData>("test");
        }
Ejemplo n.º 18
0
        public HttpResponse Handle(IHttpRequest req)
        {
            var requestedFilename = HttpUtility.UrlDecode(req.Path.Substring(reqPathFilenameStartIndex));
            var absFilename = Path.GetFullPath(Path.Combine(directory, requestedFilename));
            if (!absFilename.StartsWith(directory))
            {
                return Forbidden;
            }

            var fileInfo = new FileInfo(absFilename);
            if (!fileInfo.Exists) // cached but deleted
            {
                return NotFound;
            }

            DateTime ifModifiedSince;
            CachedFile cachedFile;
            HttpResponse response;

            if (req.TryGetIfLastModifiedSince(out ifModifiedSince) && fileInfo.LastWriteTimeUtc <= ifModifiedSince)
            {
                // Remote client (browser) has a valid cached copy (we may not have it in cache yet though eg. server restarted)
                response = new HttpResponse(HttpStatusCode.NotModified, MimeMapping.GetMimeMapping(fileInfo.Name));
            }
            else if (cache.TryGetValue(absFilename, out cachedFile) && fileInfo.LastWriteTimeUtc <= cachedFile.LastModified)
            {
                // Dictionary cached copy is still valid
                response = req.IsAcceptGZip() ? cachedFile.GZippedResponse : cachedFile.Response;
            }
            else
            {
                // Load fresh from disk
                if (fileInfo.Length <= maxFileLengthToCache)
                {
                    var fileResponse = new FileResponse.Buffered(fileInfo);
                    var gzippedFileResponse = gzipFunc(fileResponse);
                    cache[absFilename] = new CachedFile(fileResponse, gzippedFileResponse);
                    response = req.IsAcceptGZip() ? gzippedFileResponse : fileResponse;
                }
                else
                {
                    response = new FileResponse.Stream(fileInfo);
                }
            }

            return response;
        }
Ejemplo n.º 19
0
 /// <summary>
 ///     Renders the ecs file at the given path
 /// </summary>
 /// <param name="filepath">ecs file path</param>
 /// <param name="parameters">Rendering parameter</param>
 /// <returns></returns>
 public string Render(string filepath, RenderParams parameters)
 {
     if (Path.GetExtension(filepath) != ".ecs")
     {
         throw new ArgumentException("Please use .ecs files for rendering");
     }
     if (_cachePages)
     {
         if (!_renderCache.TryGetValue(filepath, out var cached))
         {
             cached = new CachedFile(filepath);
             _renderCache.TryAdd(filepath, cached);
         }
         var sb = new StringBuilder(cached.Get());
         return(InternalRenderLite(sb, parameters));
     }
     return(InternalRenderNoCache(new StringBuilder(File.ReadAllText(filepath)), parameters));
 }
Ejemplo n.º 20
0
 public string CacheFile(string file)
 {
     RemoveUsedFiles();
     lock (this)
     {
         file = Path.GetFullPath(file);
         string extension = Path.GetExtension(file);
         if (CachedFiles.ContainsKey(file))
         {
             CachedFile cached = CachedFiles[file];
             cached.CreationTime = DateTime.Now;
             return("/Cache/" + cached.AssociatedID + extension);
         }
         else
         {
             CachedFile cached = CachedFiles[file] = new CachedFile();
             File.Copy(file, Constants.ExecutionPath + "/wwwroot/Cache/" + cached.AssociatedID + extension);
             return("/Cache/" + cached.AssociatedID + extension);
         }
     }
 }
Ejemplo n.º 21
0
        private static void PrefetchSave(string mlvFileName, string content, eFileType type, int frame, byte[] stream)
        {
            MLVCachedReader cache = GetReader(mlvFileName);

            CleanCache();

            lock (cache.cachedFiles)
            {
                if (!cache.cachedFiles.ContainsKey(content))
                {
                    CachedFile cachedFile = new CachedFile();

                    cachedFile.lastUseTime  = DateTime.Now;
                    cachedFile.name         = content;
                    cachedFile.bufferedData = stream;
                    cachedFile.type         = type;
                    cachedFile.frameNum     = frame;

                    cache.cachedFiles.Add(content, cachedFile);
                }
            }
        }
Ejemplo n.º 22
0
        private static void CleanCache()
        {
            /* if memory usage is higher than 800MiB, remove until we use less */
            while (CacheUsage > 500 * 1024 * 1024)
            {
                lock (MLVCache)
                {
                    CachedFile oldestFile = new CachedFile();
                    MLVCachedReader oldestReader = null;
                    oldestFile.lastUseTime = DateTime.MaxValue;

                    foreach (MLVCachedReader reader in MLVCache.Values)
                    {
                        foreach (var file in reader.cachedFiles.Values)
                        {
                            if (file.lastUseTime < oldestFile.lastUseTime)
                            {
                                oldestFile = file;
                                oldestReader = reader;
                            }
                        }
                    }

                    oldestFile.bufferedData = null;
                    oldestReader.cachedFiles.Remove(oldestFile.name);
                }
            }

            ArrayList cachedMlvFiles = new ArrayList();
            foreach (var entry in MLVCache.Values)
            {
                cachedMlvFiles.Add(entry);
            }

            foreach (MLVCachedReader entry in cachedMlvFiles)
            {
                /* too old, remove */
                if ((DateTime.Now - entry.lastUseTime).TotalSeconds >= Program.Instance.Server.Settings.CacheTime)
                {
                    MLVCache.Remove(entry.file);

                    /* remove all files separately */
                    lock (entry.cachedFiles)
                    {
                        ArrayList fileRemoves = new ArrayList();

                        foreach (var file in entry.cachedFiles.Values)
                        {
                            fileRemoves.Add(file);
                        }

                        foreach (CachedFile file in fileRemoves)
                        {
                            entry.cachedFiles.Remove(file.name);
                            file.bufferedData = null;
                        }
                    }
                }
                else
                {
                    /* cleanup cached files every minute */
                    lock (entry.cachedFiles)
                    {
                        ArrayList fileRemoves = new ArrayList();

                        foreach (var file in entry.cachedFiles.Values)
                        {
                            if ((DateTime.Now - file.lastUseTime).TotalSeconds >= Program.Instance.Server.Settings.CacheTime)
                            {
                                fileRemoves.Add(file);
                            }
                        }

                        foreach (CachedFile file in fileRemoves)
                        {
                            entry.cachedFiles.Remove(file.name);
                            file.bufferedData = null;
                        }
                    }
                }
            }

            GC.Collect(2);
        }
Ejemplo n.º 23
0
        public HttpResponse Handle(IHttpRequest req)
        {
            var fullName = GetFileFullName(req);
            var fileInfo = new FileInfo(fullName);

            if (!fileInfo.Exists) // cached but deleted
            {
                return NotFound;
            }

            DateTime ifModifiedSince;
            CachedFile cachedFile;

            var checkLastModified = req.TryGetIfLastModifiedSince(out ifModifiedSince); // remote client has a cached version
            var hasCachedResponse = checkLastModified ? TryGetCachedFileResponse(fullName, ifModifiedSince, out cachedFile) : TryGetCachedFileResponse(fullName, out cachedFile);

            if (hasCachedResponse && fileInfo.LastWriteTimeUtc <= cachedFile.LastModified)
            {
                if (checkLastModified)
                {
                    return NotChanged(cachedFile.ContentType);
                }
                else
                {
                    return req.IsAcceptGZip() && cachedFile.GZippedResponse != null ? cachedFile.GZippedResponse : cachedFile.Response;
                }
            }
            else
            {
                var fileResponse = new FileResponse(fileInfo);

                cachedFile = new CachedFile(fileResponse, gzipFunc != null ? fileResponse.GZip(gzipFunc) : null);
                cache[fullName] = cachedFile;

                return req.IsAcceptGZip() && cachedFile.GZippedResponse != null ? cachedFile.GZippedResponse : cachedFile.Response;
            }
        }
Ejemplo n.º 24
0
 bool TryGetCachedFileResponse(string filename, DateTime ifModifiedSince, out CachedFile cached)
 {
     return cache.TryGetValue(filename, out cached) && cached.LastModified <= ifModifiedSince;
 }
Ejemplo n.º 25
0
 bool TryGetCachedFileResponse(string fullName, out CachedFile cached) => cache.TryGetValue(fullName, out cached);
Ejemplo n.º 26
0
 /// <summary>
 /// Конструктор.
 /// </summary>
 /// <param name="services">Сервисы.</param>
 /// <param name="folderName">Имя директории.</param>
 /// <param name="cacheDescription">Описание.</param>
 public ArchiveStore(IServiceProvider services, string folderName, string cacheDescription) : base(services, folderName, CacheRecycleConfig.MaxValue, cacheDescription)
 {
     CachedDb = new CachedFile<ArchiveCollection>(services, this, GetArchivesBaseFile, GetDataFolder, false);
 }
		public static string CacheTextFile(string sprocketPath, bool condenseJavaScript)
		{
			string path = HttpContext.Current.Request.PhysicalApplicationPath + '\\' + sprocketPath.Replace('/', '\\').Trim('\\');
			DateTime modified = new FileInfo(path).LastWriteTime;
			HttpContext.Current.Application.Lock();
			if (txtFileCache.ContainsKey(path))
			{
				if (txtFileCache[path].FileDate == modified)
				{
					HttpContext.Current.Application.UnLock();
					return txtFileCache[path].FileText;
				}
				txtFileCache.Remove(path);
			}
			StreamReader sr = new StreamReader(path, Encoding.Default);
			string txt = sr.ReadToEnd();
			sr.Close();
			CachedFile file = new CachedFile();
			file.FileDate = modified;
			file.FileText = condenseJavaScript ? JavaScriptCondenser.Condense(txt) : txt;
			txtFileCache.Add(path, file);
			HttpContext.Current.Application.UnLock();
			return txt;
		}
		public static string CacheWebFile(string sprocketRequestPath, string sprocketHtmlFilePath)
		{
			string path = HttpContext.Current.Request.PhysicalApplicationPath + '\\' + sprocketHtmlFilePath.Replace('/', '\\').Trim('\\');
			string refpath = MakeReferencePath(sprocketRequestPath, sprocketHtmlFilePath);

			DateTime modified = new FileInfo(path).LastWriteTime;
			if (htmlFileCache.ContainsKey(path))
			{
				if (htmlFileCache[path].FileDate == modified)
					return htmlFileCache[path].FileText.Replace("[~]", refpath);
				htmlFileCache.Remove(path);
			}
			StreamReader sr = new StreamReader(path);
			string txt = sr.ReadToEnd();
			sr.Close();
			string replace = "${1}[~]";
			string pattern1 = "(?<1>(?:(?:src=)|(?:href=)|(?:background=))(?:'|\"))(?!#|/|([a-zA-Z]+://))";
			string pattern2 = "(?<1>@(?:(?:import)|(?:url)) *(?:'|\"|\\())(?!#|/|([a-zA-Z]+://))";
			RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture;
			txt = Regex.Replace(txt, pattern1, replace, options);
			txt = Regex.Replace(txt, pattern2, replace, options);
								   
			CachedFile file = new CachedFile();
			file.FileDate = modified;
			file.FileText = txt;
			htmlFileCache.Add(path, file);
			return txt.Replace("[~]", refpath);
		}
Ejemplo n.º 29
0
 public static string CacheTextFile(string sprocketPath, bool condenseJavaScript)
 {
     string path = HttpContext.Current.Request.PhysicalApplicationPath + '\\' + sprocketPath.Replace('/', '\\').Trim('\\');
     DateTime modified = new FileInfo(path).LastWriteTime;
     HttpContext.Current.Application.Lock();
     if (txtFileCache.ContainsKey(path))
     {
         if (txtFileCache[path].FileDate == modified)
         {
             HttpContext.Current.Application.UnLock();
             return txtFileCache[path].FileText;
         }
         txtFileCache.Remove(path);
     }
     StreamReader sr = new StreamReader(path, Encoding.Default);
     string txt = sr.ReadToEnd();
     sr.Close();
     CachedFile file = new CachedFile();
     file.FileDate = modified;
     if (condenseJavaScript)
         if (sprocketPath.EndsWith(".js"))
             file.FileText = JavaScriptCondenser.Condense(txt);
         else if (sprocketPath.EndsWith(".htm"))
         {
             foreach (Match match in Regex.Matches(txt, @"\<script\>(?<js>([\s\S](?!\/script\>))*)\</script\>",
                 RegexOptions.IgnoreCase | RegexOptions.Multiline))
                 txt = txt.Replace(match.Value, "<script>" + JavaScriptCondenser.Condense(match.Groups["js"].Value) + "</script>");
             file.FileText = txt;
         }
         else
             file.FileText = txt;
     else
         file.FileText = txt;
     //file.FileText = condenseJavaScript ? JavaScriptCondenser.Condense(txt) : txt;
     txtFileCache.Add(path, file);
     HttpContext.Current.Application.UnLock();
     return txt;
 }
Ejemplo n.º 30
0
        private static void CleanCache()
        {
            /* if memory usage is higher than 800MiB, remove until we use less */
            while (CacheUsage > 500 * 1024 * 1024)
            {
                lock (MLVCache)
                {
                    CachedFile      oldestFile   = new CachedFile();
                    MLVCachedReader oldestReader = null;
                    oldestFile.lastUseTime = DateTime.MaxValue;

                    foreach (MLVCachedReader reader in MLVCache.Values)
                    {
                        foreach (var file in reader.cachedFiles.Values)
                        {
                            if (file.lastUseTime < oldestFile.lastUseTime)
                            {
                                oldestFile   = file;
                                oldestReader = reader;
                            }
                        }
                    }

                    oldestFile.bufferedData = null;
                    oldestReader.cachedFiles.Remove(oldestFile.name);
                }
            }

            ArrayList cachedMlvFiles = new ArrayList();

            foreach (var entry in MLVCache.Values)
            {
                cachedMlvFiles.Add(entry);
            }

            foreach (MLVCachedReader entry in cachedMlvFiles)
            {
                /* too old, remove */
                if ((DateTime.Now - entry.lastUseTime).TotalSeconds >= Program.Instance.Server.Settings.CacheTime)
                {
                    MLVCache.Remove(entry.file);

                    /* remove all files separately */
                    lock (entry.cachedFiles)
                    {
                        ArrayList fileRemoves = new ArrayList();

                        foreach (var file in entry.cachedFiles.Values)
                        {
                            fileRemoves.Add(file);
                        }

                        foreach (CachedFile file in fileRemoves)
                        {
                            entry.cachedFiles.Remove(file.name);
                            file.bufferedData = null;
                        }
                    }
                }
                else
                {
                    /* cleanup cached files every minute */
                    lock (entry.cachedFiles)
                    {
                        ArrayList fileRemoves = new ArrayList();

                        foreach (var file in entry.cachedFiles.Values)
                        {
                            if ((DateTime.Now - file.lastUseTime).TotalSeconds >= Program.Instance.Server.Settings.CacheTime)
                            {
                                fileRemoves.Add(file);
                            }
                        }

                        foreach (CachedFile file in fileRemoves)
                        {
                            entry.cachedFiles.Remove(file.name);
                            file.bufferedData = null;
                        }
                    }
                }
            }

            GC.Collect(2);
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Конструктор.
 /// </summary>
 /// <param name="services">Сервисы.</param>
 /// <param name="folderName">Имя директории.</param>
 /// <param name="cacheDescription">Описание.</param>
 /// <param name="mediaStorage">Хранилище медиа файлов.</param>
 public DraftDataStorage(IServiceProvider services, string folderName, string cacheDescription, IPostingMediaStore mediaStorage) : base(services, folderName, CacheRecycleConfig.MaxValue, cacheDescription)
 {
     MediaStorage = mediaStorage;
     CachedDb = new CachedFile<DraftCollection>(services, this, GetDraftBaseFile, GetDataFolder, false);
 }
Ejemplo n.º 32
0
        private static void PrefetchSave(string mlvFileName, string content, eFileType type, int frame, byte[] stream)
        {
            MLVCachedReader cache = GetReader(mlvFileName);

            CleanCache();

            lock (cache.cachedFiles)
            {
                if (!cache.cachedFiles.ContainsKey(content))
                {
                    CachedFile cachedFile = new CachedFile();

                    cachedFile.lastUseTime = DateTime.Now;
                    cachedFile.name = content;
                    cachedFile.bufferedData = stream;
                    cachedFile.type = type;
                    cachedFile.frameNum = frame;

                    cache.cachedFiles.Add(content, cachedFile);
                }
            }
        }