Ejemplo n.º 1
0
        public static void AddToCache(string md5, FileInfo path, FileCacheOperation operation)
        {
            var fileDict = GetFileCacheItems(operation);
            var dir      = GetTempDirectoryInfo(operation);

            if (IsInCache(path, md5, operation))
            {
                var curItem = GetCacheFileItemHelper(path, md5, operation);
                var curPath = Path.Combine(dir.FullName, curItem.path);
                File.Delete(curPath);
                mFileCache.items.Remove(curItem);
                fileDict.Remove(path.Name);
            }

            RemoveCacheWithoutMd5(path, operation);

            FileCacheItem item = new FileCacheItem {
                path = path.Name, Operation = (uint)operation, OriginalName = path.Name
            };

            item.md5 = md5;

            mFileCache.items.Add(item);
            fileDict.Add(item.OriginalName, item);

            string newPath = Path.Combine(dir.FullName, path.Name);

            File.Copy(path.FullName, newPath, true);
            Save();
        }
        public void Save(OnlineMapsCache cache)
        {
#if ALLOW_FILECACHE
            StringBuilder builder = cache.GetFileCacheFolder();
            builder.Append("/").Append(atlasFilename);
            string filename = builder.ToString();

            FileInfo fileInfo = new FileInfo(filename);
            if (!Directory.Exists(fileInfo.DirectoryName))
            {
                Directory.CreateDirectory(fileInfo.DirectoryName);
            }

            FileStream   stream = new FileStream(filename, FileMode.Create);
            BinaryWriter writer = new BinaryWriter(stream);

            writer.Write((byte)'T');
            writer.Write((byte)'C');
            writer.Write(ATLAS_VERSION);

            writer.Write(_size);

            for (int i = 0; i < count; i++)
            {
                FileCacheItem item = items[i];
                writer.Write(item.filename);
                writer.Write(item.size);
                writer.Write(item.time);
            }

            (writer as IDisposable).Dispose();
#endif
        }
Ejemplo n.º 3
0
 public void Add(string path, FileCacheItem item)
 {
     lock (_syncRoot)
     {
         AddItemCore(path, item);
     }
 }
Ejemplo n.º 4
0
            // Moves an item to most recently used.
            private void RefreshItemCore(string path, FileCacheItem item)
            {
                item.LastUsedAt = TimeBase.ElapsedTicks;

                if (_newestKey == path)
                {
                    return;
                }

                if (_oldestKey == path)
                {
                    _oldestKey = item.NextKey;
                }

                if (item.PreviousKey != null)
                {
                    _items[item.PreviousKey].NextKey = item.NextKey;
                }

                if (item.NextKey != null)
                {
                    _items[item.NextKey].PreviousKey = item.PreviousKey;
                }

                item.PreviousKey = _newestKey;
                item.NextKey     = null;

                _items[_newestKey].NextKey = path;
                _newestKey = path;
            }
Ejemplo n.º 5
0
        private void RemoveFirst()
        {
            FileCacheItem leastRecentlyUsedFileCacheItem = lruList.First.Value;

            File.Delete(leastRecentlyUsedFileCacheItem.LocalFilePath);
            lruList.RemoveFirst();
            cacheMap.Remove(leastRecentlyUsedFileCacheItem.FileName);
        }
        private void AddItem(string filename, int size)
        {
            FileCacheItem item = new FileCacheItem(filename, size);

            if (capacity <= count)
            {
                capacity += 100;
                Array.Resize(ref items, capacity);
            }
            items[count++] = item;
        }
        public void Load(OnlineMapsCache cache)
        {
#if ALLOW_FILECACHE
            StringBuilder builder = cache.GetFileCacheFolder();
            builder.Append("/").Append(atlasFilename);
            string filename = builder.ToString();

            if (!File.Exists(filename))
            {
                return;
            }

            FileStream   stream = new FileStream(filename, FileMode.Open);
            BinaryReader reader = new BinaryReader(stream);

            byte c1 = reader.ReadByte();
            byte c2 = reader.ReadByte();

            int cacheVersion = 0;

            if (c1 == 'T' && c2 == 'C')
            {
                cacheVersion = reader.ReadInt16();
                if (cacheVersion > 0)
                {
                }
            }
            else
            {
                stream.Position = 0;
            }

            _size = reader.ReadInt32();

            long l = stream.Length;
            while (stream.Position < l)
            {
                filename = reader.ReadString();
                int           s    = reader.ReadInt32();
                long          time = reader.ReadInt64();
                FileCacheItem item = new FileCacheItem(filename, s, time);
                if (capacity <= count)
                {
                    capacity += 100;
                    Array.Resize(ref items, capacity);
                }
                items[count++] = item;
            }

            (reader as IDisposable).Dispose();
#endif
        }
Ejemplo n.º 8
0
            public bool TryGet(string path, out FileCacheItem item)
            {
                lock (_syncRoot)
                {
                    if (!_items.TryGetValue(path, out item))
                    {
                        return(false);
                    }

                    RefreshItemCore(path, item);
                    return(true);
                }
            }
Ejemplo n.º 9
0
            // Adds an item as most recently used.
            private void AddItemCore(string path, FileCacheItem item)
            {
                item.PreviousKey = _newestKey;
                item.NextKey     = null;
                item.LastUsedAt  = TimeBase.ElapsedTicks;

                if (_newestKey != null)
                {
                    _items[_newestKey].NextKey = path;
                }

                _newestKey = path;

                _items[path] = item;
                _totalSize  += item.SizeInCache;
            }
Ejemplo n.º 10
0
        private FileCacheItem UpdateFileCache(ContentGroupNode content_group, string cache_key)
        {
            CacheDependency cd;
            StringBuilder   merged       = new StringBuilder();
            List <string>   merged_files = new List <string>(content_group.Files.Count);

            // the embedded resource must be readed from the resource assembly.
            Assembly assembly = Assembly.GetExecutingAssembly();

            foreach (string file_name in content_group.Files)
            {
                string file_path = Path.Combine(content_group.BasePath, file_name);

                // sanity check file existence
                if (File.Exists(file_path))
                {
                    using (StreamReader stream = new StreamReader(file_path)) {
                        string content = stream.ReadToEnd().Trim();
                        if (content.Length > 0)
                        {
                            merged.Append(content).Append("\r\n");
                            merged_files.Add(file_path);
                        }
                        stream.Close();
                    }
                }
            }

            if (merged.Length > 0)
            {
                FileCacheItem ci = new FileCacheItem(merged.ToString());

                // add the the application configuration file to the CacheDependency
                merged_files.Add(Utility.BaseDirectory + "web.config");
                cd = new CacheDependency(merged_files.ToArray());

                // Store the FileCacheItem in cache w/ a dependency on the merged files changing
                context_.Cache.Insert(cache_key, ci, cd);

                return(ci);
            }

            return(null);
        }
Ejemplo n.º 11
0
        public void Add(FileName fileName, LocalFilePath localFilePath)
        {
            if (cacheMap.ContainsKey(fileName))
            {
                SetMostRecentlyUsed(cacheMap[fileName]);
                return;
            }

            if (cacheMap.Count >= capacity)
            {
                RemoveFirst();
            }
            var fileCacheItem = new FileCacheItem(fileName, localFilePath);

            lruList.AddLast(fileCacheItem);
            cacheMap.Add(fileName, fileCacheItem);

            Logger.Log("cache", $"Cache updated with ({fileName})", ConsoleColor.DarkYellow);
        }
Ejemplo n.º 12
0
        public static void TryUpdate(FileCacheItem item)
        {
            if (mFileSystem == null)
            {
                return;
            }
            var resourceName  = FileListFile.GetResourceName(item.path);
            var resourceOrder = FileListFile.GetResourceOrder(item.path);

            FileSystemOrderItem orderItem = null;

            foreach (var tagItems in mFileSystem.TagItems)
            {
                foreach (var fileSystemNameItem in tagItems.NameItems)
                {
                    if (fileSystemNameItem.Name == resourceName)
                    {
                        foreach (var fileSystemOrderItem in fileSystemNameItem.OrderItems)
                        {
                            if (fileSystemOrderItem.Order == resourceOrder)
                            {
                                if (orderItem == null)
                                {
                                    orderItem = fileSystemOrderItem;
                                }
                                else
                                {
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            if (orderItem != null)
            {
                item.TextureRect = orderItem.TextureRect;
                item.Offset      = orderItem.Offset;
                Logger.LogInfoLine("FileCache FileSystem Hit:{0}", item.path);
            }
        }
Ejemplo n.º 13
0
        public static void AddToCacheWithoutCopy(string md5, FileInfo path, FileCacheOperation operation)
        {
            var fileDict = GetFileCacheItems(operation);

            FileCacheItem item = new FileCacheItem {
                md5 = md5, path = path.Name, Operation = (uint)operation, OriginalName = path.Name
            };

            if (IsInCache(path, md5, operation))
            {
                fileDict.Remove(item.OriginalName);
                var curItem = GetCacheFileItemHelper(path, md5, operation);
                mFileCache.items.Remove(curItem);
            }

            mFileCache.items.Add(item);
            RemoveCacheWithoutMd5(path, operation);
            fileDict.Add(item.OriginalName, item);

            Save();
        }
Ejemplo n.º 14
0
        private FileCacheItem UpdateFileCache(ContentGroupNode content_group, string cache_key)
        {
            CacheDependency cd;
            StringBuilder merged = new StringBuilder();
            List<string> merged_files = new List<string>(content_group.Files.Count);

			// the embedded resource must be readed from the resource assembly.
			Assembly assembly = Assembly.GetExecutingAssembly();

            foreach (string file_name in content_group.Files) {
                string file_path = Path.Combine(content_group.BasePath, file_name);

                // sanity check file existence
                if (File.Exists(file_path)) {
                    using (StreamReader stream = new StreamReader(file_path)) {
                        string content = stream.ReadToEnd().Trim();
                        if (content.Length > 0) {
                            merged.Append(content).Append("\r\n");
                            merged_files.Add(file_path);
                        }
                        stream.Close();
                    }
                }
            }

            if (merged.Length > 0) {
                FileCacheItem ci = new FileCacheItem(merged.ToString());

                // add the the application configuration file to the CacheDependency
                merged_files.Add(Utility.BaseDirectory + "web.config");
                cd = new CacheDependency(merged_files.ToArray());

                // Store the FileCacheItem in cache w/ a dependency on the merged files changing
                context_.Cache.Insert(cache_key, ci, cd);

                return ci;
            }

            return null;
        }
Ejemplo n.º 15
0
        public static void AddToCacheWithoutCopy(string md5, FileInfo path, Rectangle?textureRect, Point?offset, FileCacheOperation operation)
        {
            var fileDict = GetFileCacheItems(operation);

            FileCacheItem item = new FileCacheItem {
                md5 = md5, path = path.Name, Operation = (uint)operation, OriginalName = path.Name
            };

            if (textureRect.HasValue)
            {
                item.TextureRect          = new RectU();
                item.TextureRect.Origin   = new PointU();
                item.TextureRect.Origin.X = (uint)textureRect.Value.X;
                item.TextureRect.Origin.Y = (uint)textureRect.Value.Y;

                item.TextureRect.Size        = new SizeU();
                item.TextureRect.Size.Width  = (uint)textureRect.Value.Size.Width;
                item.TextureRect.Size.Height = (uint)textureRect.Value.Size.Height;
            }

            if (offset.HasValue)
            {
                item.Offset   = new PointU();
                item.Offset.X = (uint)offset.Value.X;
                item.Offset.Y = (uint)offset.Value.Y;
            }

            if (IsInCache(path, md5, operation))
            {
                fileDict.Remove(item.OriginalName);
                var curItem = GetCacheFileItemHelper(path, md5, operation);
                mFileCache.items.Remove(curItem);
            }

            mFileCache.items.Add(item);
            RemoveCacheWithoutMd5(path, operation);
            fileDict.Add(item.OriginalName, item);

            Save();
        }
Ejemplo n.º 16
0
        private FileCacheItem UpdateFileCache(HttpContext context, string filePath)
        {
            string content = null;

            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
            using (StreamReader sr = new StreamReader(fs))
            {
                content = sr.ReadToEnd();
                sr.Close();
            }

            fs.Close();
            }

            //Get absolute application path
            string relAppPath = HttpRuntime.AppDomainAppVirtualPath;
            if (!(relAppPath.EndsWith("/")))
            {
            relAppPath += "/";
            }

            //Replace virtual paths w/ absolute path
            content = content.Replace("~/", relAppPath);

            FileCacheItem ci = new FileCacheItem(content);

            //Store the FileCacheItem in cache w/ a dependency on the file changing
            CacheDependency cd = new CacheDependency(filePath);
            context.Cache.Insert(filePath, ci, cd);
            return ci;
        }
Ejemplo n.º 17
0
 private void SetMostRecentlyUsed(FileCacheItem cacheItem)
 {
     lruList.Remove(cacheItem);
     lruList.AddLast(cacheItem);
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Merges a collection of files into a single one and output its content to the requestor.
        /// </summary>
        /// <param name="files_to_merge">The files</param>
        /// <param name="content_group_name">The name of the content group.</param>
        /// <param name="content_type">The MIME type of content that will be merged.</param>
        void GetMergedContent(string content_group_name, string mime_type)
        {
            string modified_since = context_.Request.Headers["If-Modified-Since"];
            string cache_key      = string.Concat(kKeyPrefix,
                                                  content_group_name, ".",
                                                  mime_type, ".",
                                                  kBuildVersion);

            // check if this group is defined
            ContentGroupNode content_group = settings_.WebNode.GetContentGroup(content_group_name, kBuildVersion, mime_type);

            if (content_group == null)
            {
                context_.Response.StatusCode = kResourceNotFoundCode;
                context_.Response.End();
                return;
            }

            // attempt to retrieve the merged content from the cache
            FileCacheItem cached_file = (FileCacheItem)context_.Cache[cache_key];

            if (cached_file != null)
            {
                if (modified_since != null)
                {
                    DateTime last_client_update;
                    DateTime.TryParseExact(context_.Request.Headers["If-Modified-Since"], "yyyyMMdd HH:mm:ss", null, System.Globalization.DateTimeStyles.None, out last_client_update);

                    if (cached_file.DateEntered <= last_client_update)
                    {
                        // don't do anything, nothing has changed since last request.
                        context_.Response.StatusCode        = 304;
                        context_.Response.StatusDescription = "Not Modified";
                        context_.Response.End();
                        return;
                    }
                }
                else
                {
                    // In the event that the browser does not automatically have this header, add it
                    context_.Response.AddHeader("If-Modified-Since", cached_file.DateEntered.ToString("yyyyMMdd HH:mm:ss"));
                }
            }
            else
            {
                // cache item not found, update cache
                cached_file = UpdateFileCache(content_group, cache_key);
                if (cached_file == null)
                {
                    // the files to merge are not found
                    FileLogger.ForCurrentProcess.Logger.Error("[GetMergedContent   Nohros.Net.MergeHttpHandler]   The files to merge are not found.");
                    context_.Response.StatusCode = kResourceNotFoundCode;
                    context_.Response.End();
                }
            }

            context_.Response.Cache.SetLastModified(cached_file.DateEntered);
            context_.Response.ContentType = mime_type;
            context_.Response.Write(cached_file.Content);
            context_.Response.End();
        }