Пример #1
0
        private static Dictionary <string, Metadata> GetDirectoryMetadata(string virtualPath)
        {
            var    vpp          = HostingEnvironment.VirtualPathProvider;
            string metadataFile = VirtualPathUtility.AppendTrailingSlash(virtualPath) + MetadataFile;

            var mapping = new Dictionary <string, Metadata>();
            int index   = 0;

            if (vpp.FileExists(metadataFile))
            {
                VirtualFile file   = vpp.GetFile(metadataFile);
                Stream      stream = file.Open();
                using (var reader = new StreamReader(stream))
                {
                    string line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        mapping[Normalize(line)] = new Metadata
                        {
                            Order = index++
                        };
                    }
                }
            }
            return(mapping);
        }
Пример #2
0
        internal static Assembly LoadAssembly(string p)
        {
            Assembly assembly = TryLoadAssembly(p);

            if (assembly != null)
            {
                return(assembly);
            }

            try
            {
                byte[] array;
                using (Stream stream = VirtualFile.Open(p))
                {
                    array = new byte[stream.Length];
                    if (stream.Read(array, 0, array.Length) != array.Length)
                    {
                        throw new Exception();
                    }
                }
                assembly             = AppDomain.CurrentDomain.Load(array);
                loadedAssemblyDic[p] = assembly;
            }
            catch
            {
                Log.Fatal("Load assembly failed \"{0}\".", p);
                return(null);
            }
            return(assembly);
        }
Пример #3
0
        /// <summary>
        /// Gets a text content of the specified file
        /// </summary>
        /// <param name="virtualPath">The path to the virtual file</param>
        /// <returns>Text content</returns>
        public string GetFileTextContent(string virtualPath)
        {
            string        content;
            var           stringBuilderPool = StringBuilderPool.Shared;
            StringBuilder contentBuilder    = stringBuilderPool.Rent();

            try
            {
                VirtualFile virtualFile = BundleTable.VirtualPathProvider.GetFile(virtualPath);

                using (var streamReader = new StreamReader(virtualFile.Open()))
                {
                    // Fixes a single CR/LF
                    while (streamReader.Peek() >= 0)
                    {
                        contentBuilder.AppendLine(streamReader.ReadLine());
                    }
                }

                content = contentBuilder.ToString();
            }
            catch (FileNotFoundException e)
            {
                throw new FileNotFoundException(
                          string.Format(Strings.Common_FileNotExist, virtualPath), virtualPath, e);
            }
            finally
            {
                stringBuilderPool.Return(contentBuilder);
            }

            return(content);
        }
Пример #4
0
        public override Stream Open()
        {
            using (var actualStream = _actualFile.Open()) {
                var reader = new StreamReader(actualStream);

                var memoryStream = new MemoryStream();
                int length;
                using (var writer = new StreamWriter(memoryStream)) {
                    bool assemblyDirectiveAdded = false;
                    for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
                    {
                        if (!string.IsNullOrWhiteSpace(line) && !assemblyDirectiveAdded)
                        {
                            line += _assemblyDirective;
                            assemblyDirectiveAdded = true;
                        }

                        writer.WriteLine(line);
                    }
                    writer.Flush();
                    length = (int)memoryStream.Length;
                }
                return(new MemoryStream(memoryStream.GetBuffer(), 0, length));
            }
        }
Пример #5
0
        /// <summary>
        /// The order mapping is a file named order in the same virtual path.
        /// </summary>
        private static Func <string, Metadata> GetMetadataMapping(string virtualPath)
        {
            var vpp          = HostingEnvironment.VirtualPathProvider;
            var metadataFile = VirtualPathUtility.AppendTrailingSlash(virtualPath) + MetadataFile;

            var mapping = new Dictionary <string, Metadata>();
            var index   = 0;

            if (vpp.FileExists(metadataFile))
            {
                VirtualFile file   = vpp.GetFile(metadataFile);
                Stream      stream = file.Open();
                using (var reader = new StreamReader(stream))
                {
                    string line = null;
                    while ((line = reader.ReadLine()) != null)
                    {
                        mapping[Normalize(line)] = new Metadata
                        {
                            Order = index++
                        };
                    }
                }
            }

            return(title =>
            {
                Metadata metadata;
                if (mapping.TryGetValue(title, out metadata))
                {
                    return metadata;
                }
                return Metadata.Empty;
            });
        }
Пример #6
0
        internal void TransmitFile(VirtualFile vf, bool final_flush)
        {
            if (vf == null)
            {
                throw new ArgumentNullException("vf");
            }

            if (vf is DefaultVirtualFile)
            {
                TransmitFile(HostingEnvironment.MapPath(vf.VirtualPath), final_flush);
                return;
            }

            byte[] buf = new byte [bufLen];
            using (Stream s = vf.Open()) {
                int readBytes;
                while ((readBytes = s.Read(buf, 0, bufLen)) > 0)
                {
                    output_stream.Write(buf, 0, readBytes);
                    output_stream.ApplyFilter(final_flush);
                    Flush(false);
                }
                if (final_flush)
                {
                    Flush(true);
                }
            }
        }
Пример #7
0
 /// <summary>
 /// 从指定虚拟文件中读取文本内容
 /// </summary>
 /// <param name="file">虚拟文件</param>
 /// <returns></returns>
 public static string LoadContent(VirtualFile file)
 {
     using (var reader = new StreamReader(file.Open(), true))
     {
         return(reader.ReadToEnd());
     }
 }
Пример #8
0
        public static Dictionary <string, List <Deal> > GetTopDealsDictionary()
        {
            string cacheKey = "topdealsdictionary";
            Dictionary <string, List <Deal> > dictionary = HttpRuntime.Cache.Get(cacheKey) as Dictionary <string, List <Deal> >;

            if (dictionary != null)
            {
                return(dictionary);
            }

            try
            {
                VirtualFile file = HostingEnvironment.VirtualPathProvider.GetFile("~/topplaces.json");
                using (Stream stream = file.Open())
                {
                    string data = new StreamReader(stream).ReadToEnd();
                    dictionary = JsonConvert.DeserializeObject <Dictionary <string, List <Deal> > >(data);
                    if (dictionary != null)
                    {
                        HttpRuntime.Cache.Insert(cacheKey, dictionary, null, Cache.NoAbsoluteExpiration, TimeSpan.FromDays(10));
                    }

                    return(dictionary);
                }
            }
            catch
            {
                return(null);
            }
        }
Пример #9
0
        public string RenderResourceFile(string resourcePath)
        {
            string      text;
            VirtualFile file = VirtualPathProvider.GetFile(resourcePath);

            using (Stream stream = file.Open())
                using (StreamReader reader = new StreamReader(stream))
                {
                    text = reader.ReadToEnd();
                }

            Regex regex = new Regex("\\(=makeFileUrl\\(\"(.+?)\"\\)\\)");

            text = regex.Replace(text, match =>
                                 UrlHelper.Content(match.Groups[1].Value));

            regex = new Regex("\\(=makeurl\\(\"(.*?)\"\\)\\)");
            text  = regex.Replace(text, match =>
                                  UrlHelper.Content(match.Groups[1].Value.Length > 0 ? match.Groups[1].Value : "/"));

            regex = new Regex("\\(@(.*?)\\)");
            text  = regex.Replace(text, match =>
                                  LocalizationManager.Instance.Translate(resourcePath /*TODO*/, match.Groups[1].Value));

            return(text);
        }
        public CachedFileResult(VirtualFile file, DateTime?lastModifiedUtc = null, string contentType = null)
        {
            Guard.NotNull(file, nameof(file));

            try
            {
                var fi = GetFileInfo(file.VirtualPath);
                if (fi.Exists)
                {
                    ContentType     = contentType.NullEmpty() ?? MimeTypes.MapNameToMimeType(fi.Name);
                    FileLength      = fi.Length;
                    LastModifiedUtc = fi.LastWriteTimeUtc;
                }
            }
            finally
            {
                if (lastModifiedUtc == null)
                {
                    throw new ArgumentNullException(nameof(lastModifiedUtc), "A modification date must be provided if the VirtualFile cannot be mapped to a physical path.");
                }

                if (FileLength == null)
                {
                    ContentType = contentType.NullEmpty() ?? MimeTypes.MapNameToMimeType(file.Name);
                    using (var stream = file.Open())
                    {
                        FileLength = stream.Length;
                    }
                }
            }

            Transmitter     = new FileStreamTransmitter(file.Open);
            LastModifiedUtc = lastModifiedUtc.Value;
        }
Пример #11
0
        private static string GenerateCodeFromRazorTemplate(WebPageRazorHost host, string virtualPath)
        {
            // Create Razor engine and use it to generate a CodeCompileUnit
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results = null;
            VirtualFile      file    = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath);

            using (var stream = file.Open())
            {
                using (TextReader reader = new StreamReader(stream))
                {
                    results = engine.GenerateCode(reader, className: null, rootNamespace: null, sourceFileName: host.PhysicalPath);
                }
            }

            if (!results.Success)
            {
                throw CreateExceptionFromParserError(results.ParserErrors.Last(), virtualPath);
            }

            // Use CodeDom to generate source code from the CodeCompileUnit
            var codeDomProvider = new CSharpCodeProvider();
            var srcFileWriter   = new StringWriter();

            codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, srcFileWriter, new CodeGeneratorOptions());

            return(srcFileWriter.ToString());
        }
 public static void WriteAllText(this VirtualFile file, string text, Encoding encoding)
 {
     using (var stream = file.Open(FileMode.Truncate, FileAccess.Write))
     {
         var bytes = encoding.GetBytes(text);
         stream.Write(bytes, 0, bytes.Length);
     }
 }
Пример #13
0
        public override void Update()
        {
            var stream = VirtualFile.Open(VirtualFile.PathToMemInfo);

            byte       flag             = 0b0000000;
            const byte flagMemTotal     = 0b0000001,
                       flagMemFree      = 0b0000010,
                       flagMemAvailable = 0b0000100,
                       flagSwapTotal    = 0b0001000,
                       flagSwapFree     = 0b0010000;
            const byte flagAll          = flagMemTotal | flagMemFree | flagMemAvailable | flagSwapTotal | flagSwapFree;

            do
            {
                string[] items = stream.ReadLine().Split(':');
                if (items.Length < 2)
                {
                    continue;
                }
                string value = items[1].SplitSpaces()[0];

                Log.Debug($"Mem: {items[0]} = {value}");

                switch (items[0])
                {
                // all in KiB
                case "MemTotal":
                    Json.Total = int.Parse(value);
                    flag      |= flagMemTotal;
                    break;

                case "MemFree":
                    Json.Free = int.Parse(value);
                    flag     |= flagMemFree;
                    break;

                case "MemAvailable":
                    Json.Available = int.Parse(value);
                    flag          |= flagMemAvailable;
                    break;

                case "SwapTotal":
                    Json.SwapTotal = int.Parse(value);
                    flag          |= flagSwapTotal;
                    break;

                case "SwapFree":
                    Json.SwapFree = int.Parse(value);
                    flag         |= flagSwapFree;
                    break;
                }
            } while ((flag ^ flagAll) > 0 && !stream.EndOfStream);

            Json.Used = Json.Total - Json.Free;

            stream.Close();
        }
Пример #14
0
 internal static bool CheckPassword(string password)
 {
     return(CheckPassword(password, () =>
     {
         VirtualFile passwordFile = HostingEnvironment.VirtualPathProvider.GetFile(AdminPasswordFile);
         Debug.Assert(passwordFile != null, "password file should not be null");
         return passwordFile.Open();
     }));
 }
Пример #15
0
        /// <summary>
        /// Returns the markdown content within this page
        /// </summary>
        private string GetMarkdownContent()
        {
            VirtualFile file   = HostingEnvironment.VirtualPathProvider.GetFile(VirtualPath);
            Stream      stream = file.Open();

            using (var reader = new StreamReader(stream)) {
                return(reader.ReadToEnd());
            }
        }
Пример #16
0
 public virtual Stream OpenFile(string virtualPath)
 {
     if (FileExists(virtualPath))
     {
         VirtualFile file = PathProvider.GetFile(virtualPath);
         return(file.Open());
     }
     return(File.Open(MapPath(virtualPath), FileMode.OpenOrCreate));
 }
Пример #17
0
        private static IEnumerable <SkinTemplate> GetSkinTemplates(VirtualPathProvider virtualPathProvider, string path)
        {
            VirtualFile virtualConfigFile = virtualPathProvider.GetFile(path);

            using (Stream configStream = virtualConfigFile.Open())
            {
                var templates = SerializationHelper.Load <SkinTemplates>(configStream);
                return(templates.Templates);
            }
        }
 public static string ReadAllText(this VirtualFile file, Encoding encoding)
 {
     using (var stream = file.Open(FileMode.Open, FileAccess.Read))
     {
         var buffer = new byte[stream.Length];
         stream.Read(buffer, 0, buffer.Length);
         var retv = encoding.GetString(buffer);
         return(retv);
     }
 }
Пример #19
0
        public void ProcessRequest(HttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            VirtualFile vf       = null;
            var         filePath = request.FilePath;

            // Cross-Origin Resource Sharing (CORS)
            if (!HttpHeaderTools.IsOriginHeaderAllowed())
            {
                AuthenticationHelper.ThrowForbidden(filePath);
            }

            if (HostingEnvironment.VirtualPathProvider.FileExists(filePath))
            {
                vf = HostingEnvironment.VirtualPathProvider.GetFile(filePath);
            }

            if (vf == null)
            {
                throw new HttpException(404, "File does not exist");
            }

            response.ClearContent();

            // Set content type only if this is not a RepositoryFile, because the
            // Open method of RepositoryFile will set the content type itself.
            if (!(vf is RepositoryFile))
            {
                var extension = System.IO.Path.GetExtension(filePath);
                context.Response.ContentType = MimeTable.GetMimeType(extension);

                // add the necessary header for the css font-face rule
                if (MimeTable.IsFontType(extension))
                {
                    HttpHeaderTools.SetAccessControlHeaders();
                }
            }

            // The bytes we write into the output stream will NOT be buffered and will be sent
            // to the client immediately. This makes sure that the whole (potentially large)
            // file is not loaded into the memory on the server.
            response.BufferOutput = false;

            using (var stream = vf.Open())
            {
                response.AppendHeader("Content-Length", stream.Length.ToString());
                response.Clear();

                // Let ASP.NET handle sending bytes to the client (avoid Flush).
                stream.CopyTo(response.OutputStream);
            }
        }
Пример #20
0
        protected override bool Load(string virtualFileName, Mesh mesh)
        {
            currentFileName     = virtualFileName;
            currentMesh         = mesh;
            globalScale         = 1;
            yAxisUp             = true;
            generatedMaterials  = new Dictionary <string, MySceneMaterial>();
            generatedGeometries = new Dictionary <string, GeometryItem>();
            generatedSubMeshes  = new List <MySceneSubMesh>();

            //load file
            XmlNode colladaNode;

            {
                try
                {
                    using (Stream stream = VirtualFile.Open(virtualFileName))
                    {
                        string fileText = new StreamReader(stream).ReadToEnd();
                        colladaNode = XmlUtils.LoadFromText(fileText);
                    }
                }
                catch (Exception ex)
                {
                    Error(ex.Message);
                    return(false);
                }
            }

            //parse
            if (!ParseColladaNode(colladaNode))
            {
                ClearTemporaryFields();
                return(false);
            }

            //generate mesh
            const bool      tangents            = true;
            const bool      edgeList            = true;
            const bool      allowMergeSubMeshes = true;
            MeshConstructor meshConstructor     = new MeshConstructor(tangents, edgeList, allowMergeSubMeshes);

            MyMeshSceneObject meshSceneObject = new MyMeshSceneObject(generatedSubMeshes.ToArray());

            if (!meshConstructor.DoExport(meshSceneObject, mesh))
            {
                ClearTemporaryFields();
                return(false);
            }

            ClearTemporaryFields();

            return(true);
        }
Пример #21
0
 private static void AddFile(CDBuilder isoBuilder, string name, VirtualFile file)
 {
     if (file.StoredInMemory)
     {
         isoBuilder.AddFile(name, file.Open());
     }
     else
     {
         isoBuilder.AddFile(name, file.HostPath);
     }
 }
Пример #22
0
 private IEnumerable <string> ReadLines(VirtualFile file)
 {
     using (var s = file.Open())
         using (var sr = new StreamReader(s))
         {
             while (sr.Peek() >= 0)
             {
                 yield return(sr.ReadLine());
             }
         }
 }
Пример #23
0
 static IEnumerable <string> ReadLinesImpl(this VirtualFile file, Encoding encoding)
 {
     using (var stream = file.Open())
         using (var reader = encoding == null
                       ? new StreamReader(stream)
                       : new StreamReader(stream, encoding))
             using (var e = reader.ReadLines())
                 while (e.MoveNext())
                 {
                     yield return(e.Current);
                 }
 }
Пример #24
0
        public void ProcessRequest(HttpContext context)
        {
            var request  = context.Request;
            var response = context.Response;

            VirtualFile vf       = null;
            var         filePath = request.FilePath;

            if (HostingEnvironment.VirtualPathProvider.FileExists(filePath))
            {
                vf = HostingEnvironment.VirtualPathProvider.GetFile(filePath);
            }

            if (vf == null)
            {
                throw new HttpException(404, "File does not exist");
            }

            response.ClearContent();

            //Set content type only if this is not a RepositoryFile, because the
            //Open method of RepositoryFile will set the content type itself.
            if (!(vf is RepositoryFile))
            {
                var extension = System.IO.Path.GetExtension(filePath);
                context.Response.ContentType = MimeTable.GetMimeType(extension);

                //add the necessary header for the css font-face rule
                if (MimeTable.IsFontType(extension))
                {
                    HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", HttpContext.Current.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
                }
            }

            using (var stream = vf.Open())
            {
                response.AppendHeader("Content-Length", stream.Length.ToString());

                //We need to Flush the headers before
                //we start to stream the actual binary.
                response.Flush();

                var buffer = new byte[Math.Min(stream.Length, RepositoryConfiguration.BinaryChunkSize)];
                int readed;

                while ((readed = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    response.OutputStream.Write(buffer, 0, readed);
                    response.Flush();
                }
            }
        }
Пример #25
0
        private VirtualDirectory ConvertCvmToVirtualDirectory(VirtualFile cvmFile)
        {
            using (var stream = cvmFile.Open())
            {
                var streamView       = new StreamView(stream, 0x1800, stream.Length - 0x1800);
                var cvmIsoFilesystem = new CDReader(streamView, false);

                var directory = cvmIsoFilesystem.ToVirtualDirectory();
                directory.Name = Path.GetFileNameWithoutExtension(cvmFile.Name);

                return(directory);
            }
        }
Пример #26
0
        public virtual Stream OpenFile(string virtualPath, bool readOnly = false)
        {
            if (FileExists(virtualPath))
            {
                VirtualFile file = PathProvider.GetFile(virtualPath);
                return(file.Open());
            }

            FileAccess access = readOnly ? FileAccess.Read : FileAccess.ReadWrite;
            FileShare  share  = readOnly ? FileShare.Read : FileShare.None;

            return(File.Open(MapPath(virtualPath), FileMode.OpenOrCreate, access, share));
        }
Пример #27
0
        public ActionResult Resource(string fileid)
        {
            var provider = new EmbeddedResourceVirtualPathProvider();

            VirtualFile file = provider.GetFile("/scarfresources/" + fileid);

            using (Stream stream = file.Open())
            {
                var contents = new byte[stream.Length];
                stream.Read(contents, 0, contents.Length);
                return(new FileContentResult(contents, GetContentType(fileid)));
            }
        }
Пример #28
0
 public static IEnumerable <string> ReadLines(this VirtualFile file)
 {
     if (file == null)
     {
         throw new ArgumentNullException(nameof(file));
     }
     using (var stream = file.Open())
         using (var reader = new StreamReader(stream))
             using (var e = reader.ReadLines())
                 while (e.MoveNext())
                 {
                     yield return(e.Current);
                 }
 }
Пример #29
0
 static string ReadAllTextImpl(this VirtualFile file, Encoding encoding)
 {
     if (file == null)
     {
         throw new ArgumentNullException("file");
     }
     using (var stream = file.Open())
         using (var reader = encoding == null
                       ? new StreamReader(stream)
                       : new StreamReader(stream, encoding))
         {
             return(reader.ReadToEnd());
         }
 }
        private string[] _GetDependencies(VirtualFile virtualFile)
        {
            var dir = VirtualPathUtility.GetDirectory(virtualFile.VirtualPath);

            string content;

            using (var stream = virtualFile.Open())
                using (var reader = new StreamReader(stream))
                    content = reader.ReadToEnd();

            return(_ReferenceRegex.Matches(content).Cast <Match>().Select(m => {
                var relativePath = m.Groups["path"].Value;
                return VirtualPathUtility.Combine(dir, relativePath);
            }).Where(m => this.ExcludedDependencies.All(e => !m.Contains(@"/" + e))).ToArray());
        }
Пример #31
0
 protected static string ReadToEnd(VirtualFile file)
 {
     using (var fs = file.Open())
     {
         var reader = new StreamReader(fs, Encoding.UTF8, true, (int) VirtualFileSystem.DefaultBlockSize, true);
         return reader.ReadToEnd();
     }
 }