Esempio n. 1
0
        public void TestSetPositionWrite()
        {
            //Test setting Position durung a write by writing the contents of the file to disk backwards one byte at a time
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestSetPositionWrite");

            byte[]    buffer = new byte[1];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForWriting(filePath);

            Assert.AreEqual(0, wfio.Position);

            for (int i = FILE_CONTENT.Length - 1; i >= 0; i--)
            {
                wfio.Position = i;
                Assert.AreEqual(i, wfio.Position);

                buffer[0] = FILE_CONTENT[i];
                wfio.WriteBlocks(1);
            }
            wfio.Close();

            byte[] actual = readFile(filePath);

            CollectionAssert.AreEqual(FILE_CONTENT, actual);
        }
Esempio n. 2
0
        private void Init()
        {
            // This function initializes the WinFileIO object and reads in a file to be used for testing and verification.
            String DataPath;

            ByteBuf    = new byte[BufSize];
            ByteBufVer = new byte[BufSize];
            WFIO       = new WinFileIO(ByteBuf);
            DataPath   = Application.StartupPath;
            int n = DataPath.LastIndexOf("bin\\");

            DataPath  = DataPath.Substring(0, n);
            DataPath += "data\\";
            if (!Directory.Exists(DataPath))
            {
                String S = "GetDataPath: data Folder can't be found.  Should have been created on install.";
                DispUIMsg(S);
                DataPath = "";
            }
            // Read the test file into the verification buffer.
            TestFileName = DataPath + "All Customers Orders Order Details.txt";
            FileStream FSFile = new FileStream(TestFileName, FileMode.Open, FileAccess.Read,
                                               FileShare.None, BlockSize, FileOptions.SequentialScan);

            VerBytesRead = FSFile.Read(ByteBufVer, 0, BufSize);
            FSFile.Close();
            FSFile.Dispose();
            TestFileName2 = DataPath + "TestWriteFile.txt";
        }
Esempio n. 3
0
        /// <summary>
        /// Read the raw value from file, this method is used by the Metadata Editor
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="path"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public static string ReadRawValue(cmSite domain, string path, string lang = null)
        {
            // fix the path to filesystem path
            path = Regex.Replace(path, @"([^\/]\.(\w|\-|_)+)$"
                                 , new MatchEvaluator(delegate(Match m) { string x = m.ToString(); return(x[0].ToString() + "/" + x.Substring(1)); })
                                 , RegexOptions.Compiled | RegexOptions.ECMAScript
                                 );

            string postfix      = string.IsNullOrWhiteSpace(lang) ? string.Empty : "." + lang;
            string physicalPath = HostingEnvironment.MapPath(
                string.Format("~/Views/{0}/{1}{2}", domain.DistinctName, path.TrimStart('/'), postfix)
                );

            if (!File.Exists(physicalPath) && !string.IsNullOrWhiteSpace(domain.TemplateDomainDistinctName))
            {
                physicalPath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}{2}", domain.TemplateDomainDistinctName, path.TrimStart('/'), postfix)
                    );
            }
            string rawValue = WinFileIO.ReadWithoutLock(physicalPath);

            if (rawValue != null)
            {
                return(rawValue);
            }
            return(string.Empty);
        }
Esempio n. 4
0
        /// <summary>
        /// Get the metadata entries for special languages
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="path"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public static Dictionary <string, string> GetSpecialLanguageEntries(cmSite domain, string path, string lang)
        {
            Dictionary <string, string> entries
                = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            string physicalPath;

            if (!string.IsNullOrWhiteSpace(domain.TemplateDomainDistinctName))
            {
                physicalPath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}", domain.TemplateDomainDistinctName, path.TrimStart('/'))
                    );
                if (Directory.Exists(physicalPath))
                {
                    var files = Directory.EnumerateFiles(physicalPath, ".*", SearchOption.TopDirectoryOnly);
                    foreach (string file in files)
                    {
                        Regex pattern;
                        if (!patterns.TryGetValue(lang, out pattern))
                        {
                            pattern        = new Regex(string.Format(@"^\.(?<name>[^\.]+)\.{0}$", lang.Replace("-", "\\-")), RegexOptions.ECMAScript | RegexOptions.Compiled);
                            patterns[lang] = pattern;
                        }
                        string filename = Path.GetFileName(file);
                        Match  match    = pattern.Match(filename);
                        if (match.Success)
                        {
                            entries[match.Groups["name"].Value] = WinFileIO.ReadWithoutLock(file);
                        }
                    }
                }
            }

            physicalPath = HostingEnvironment.MapPath(
                string.Format("~/Views/{0}/{1}", domain.DistinctName, path.TrimStart('/'))
                );
            if (Directory.Exists(physicalPath))
            {
                var files = Directory.EnumerateFiles(physicalPath, ".*", SearchOption.TopDirectoryOnly);
                foreach (string file in files)
                {
                    Regex pattern;
                    if (!patterns.TryGetValue(lang, out pattern))
                    {
                        pattern        = new Regex(string.Format(@"^\.(?<name>[^\.]+)\.{0}$", lang.Replace("-", "\\-")), RegexOptions.ECMAScript | RegexOptions.Compiled);
                        patterns[lang] = pattern;
                    }
                    string filename = Path.GetFileName(file);
                    Match  match    = pattern.Match(filename);
                    if (match.Success)
                    {
                        entries[match.Groups["name"].Value] = WinFileIO.ReadWithoutLock(file);
                    }
                }
            }

            return(entries);
        }
Esempio n. 5
0
        public static bool Copy(string sourceFileName, string destFileName, bool overwrite, IFileCopyCallout callout,
                                Action <ProgressMessage> report = null, Func <bool> cancel = null
                                )
        {
            byte[] buf = new byte[BUFSIZ];

            DateTime dt0    = DateTime.Now;
            long     ivlcnt = 0;

            long total = new System.IO.FileInfo(sourceFileName).Length;
            long count = 0;

            using (var threadProgress = new ThreadProgress(report)) {
                using (WinFileIO wfioRd = new WinFileIO(buf), wfioWr = new WinFileIO(buf)) {
                    wfioRd.OpenForReading(sourceFileName);
                    wfioWr.OpenForWriting(destFileName, overwrite);

                    int read = 0;
                    while (true)
                    {
                        if (cancel?.Invoke() ?? false)
                        {
                            return(false);
                        }

                        read = wfioRd.ReadBlocks(BUFSIZ);
                        if (read <= 0)
                        {
                            break;
                        }

                        callout?.ProcessBuffer(buf, read, count);

                        wfioWr.Write(read);

                        count += read;
                        DateTime dt     = DateTime.Now;
                        long     tot_ms = (int)(dt - dt0).TotalMilliseconds;
                        long     q      = tot_ms / IVL_MS;
                        if (q <= ivlcnt)
                        {
                            continue;
                        }

                        ivlcnt = q;
                        threadProgress.Report((double)count / total);
                    }
                    ;
                }
            }
            return(true);
        }
Esempio n. 6
0
        public void TestSetPositionReadWrite()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestSetPositionReadWrite");

            byte[]    buffer = new byte[1];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForReadingWriting(filePath);

            Assert.AreEqual(0, wfio.Position);

            //Write stuff, move about writing more, then come back in & read it in etc...
            buffer[0] = 1;
            wfio.WriteBlocks(1);
            buffer[0] = 3;
            wfio.WriteBlocks(1);
            buffer[0] = 3;
            wfio.WriteBlocks(1);
            buffer[0] = 7;
            wfio.WriteBlocks(1);

            wfio.Position = 0;
            wfio.ReadBlocks(1);
            Assert.AreEqual(1, buffer[0]);
            wfio.ReadBlocks(1);
            Assert.AreEqual(3, buffer[0]);
            wfio.ReadBlocks(1);
            Assert.AreEqual(3, buffer[0]);
            wfio.ReadBlocks(1);
            Assert.AreEqual(7, buffer[0]);

            wfio.Position = 2;
            buffer[0]     = 24;
            wfio.WriteBlocks(1);
            wfio.Position = 0;
            buffer[0]     = 10;
            wfio.WriteBlocks(1);
            wfio.Position = 2;
            wfio.ReadBlocks(1);
            Assert.AreEqual(24, buffer[0]);
            wfio.Position = 0;
            wfio.ReadBlocks(1);
            Assert.AreEqual(10, buffer[0]);

            wfio.Close();

            //Now check that the final file is what we expected it to be
            byte[] expected = new byte[] { 10, 3, 24, 7 };
            byte[] actual   = readFile(filePath);

            CollectionAssert.AreEqual(expected, actual);
        }
 public FileEfficientTests()
 {
     _charBuf        = new char[BufSizeM1M];
     _byteBuf        = new byte[BufSizeM1M];
     _byteBufVer     = new byte[BufSizeM1M];
     _wfio           = new WinFileIO(_byteBuf);
     _waitReadAsync  = new ManualResetEvent(false);
     _waitSignal     = new ManualResetEvent(true);
     _utf8           = new UTF8Encoding();
     StringsContents = new Dictionary <string, string[]>();
     StringContents  = new Dictionary <string, string>();
     BytesInFiles    = new Dictionary <string, int>();
 }
Esempio n. 8
0
        public static void Extract(string FileName, Action <int, int> processedEvent, bool is64 = false)
        {
            using (FileStream fs = new FileStream(FileName, FileMode.Open))
            {
                BinaryReader br = new BinaryReader(fs);

                BPKG pkg = new BPKG(fs, is64);

                for (var i = 0; i < pkg.Files.Length; i++)
                {
                    BPKG_FTE fte = pkg.Files[i];
                    // Seek to location of binary file data
                    fs.Position = fte.FileDataOffset;

                    byte[] packedFileData   = br.ReadBytes(fte.FileDataSizeStored);
                    byte[] unpackedFileData = Unpack(packedFileData, fte.FileDataSizeStored,
                                                     fte.FileDataSizeSheared, fte.FileDataSizeUnpacked,
                                                     fte.IsEncrypted, fte.IsCompressed);

                    string extractedPath = $"{FileName}.files\\{fte.FilePath}";
                    string extractedDir  = new FileInfo(extractedPath).DirectoryName;
                    if (!Directory.Exists(extractedDir))
                    {
                        ;
                    }
                    Directory.CreateDirectory(extractedDir);

                    if (extractedPath.EndsWith("xml") || extractedPath.EndsWith("x16"))
                    {
                        // decode bxml
                        MemoryStream output = new MemoryStream();
                        MemoryStream input  = new MemoryStream(unpackedFileData);

                        Convert(input, BXML.DetectType(input), output, BXML_TYPE.BXML_PLAIN);

                        using (WinFileIO writer = new WinFileIO(output.ToArray()))
                        {
                            writer.OpenForWriting(extractedPath);
                            writer.WriteBlocks((int)output.Length);
                        }
                    }
                    else
                    {
                        // extract raw
                        File.WriteAllBytes(extractedPath, unpackedFileData);
                    }
                    processedEvent(i + 1, pkg.Files.Length);
                }
            }
        }
Esempio n. 9
0
        public void TestReadWholeFile()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestReadWholeFile");

            createFile(filePath);

            byte[]    buffer = new byte[FILE_CONTENT.Length];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForReading(filePath);
            wfio.ReadBlocks(buffer.Length);
            wfio.Close();

            CollectionAssert.AreEqual(FILE_CONTENT, buffer);
        }
Esempio n. 10
0
        public void TestInitialPositionWrite()
        {
            const string FILE_NAME = "WinFileIOTests.TestInitialPositionWrite";

            byte[]    buffer = new byte[1];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForWriting(FILE_NAME);

            Assert.AreEqual(0, wfio.Position);

            wfio.Close();

            fileNames.Add(FILE_NAME);
        }
Esempio n. 11
0
 private WinFileIO WFIO;                        // The object that implements the windows readfile and writefile system functions.
 //
 public FileEfficientTests(MainForm theForm)
 {
     TheForm        = theForm;
     FilesInit      = false;
     FileNames      = new String[3];
     FileNamesW     = new String[3];
     CharBuf        = new char[BufSizeM1M];
     ByteBuf        = new byte[BufSizeM1M];
     ByteBufVer     = new byte[BufSizeM1M];
     WFIO           = new WinFileIO(ByteBuf);
     WaitReadAsync  = new ManualResetEvent(false);
     WaitSignal     = new ManualResetEvent(true);
     UTF8           = new UTF8Encoding();
     StringContents = new ArrayList(3);
 }
Esempio n. 12
0
        public void TestLengthRead()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestLengthRead");

            createFile(filePath);

            byte[]    buffer = new byte[1];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForReading(filePath);

            Assert.AreEqual((long)FILE_CONTENT.Length, wfio.Length);

            wfio.Close();
        }
Esempio n. 13
0
        public void TestPositionIncrementsWrite()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestPositionIncrementsWrite");

            byte[]    buffer = new byte[] { 7, 3 };
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForWriting(filePath);
            wfio.WriteBlocks(buffer.Length);

            Assert.AreEqual(2, wfio.Position);

            wfio.Close();

            fileNames.Add(filePath);
        }
Esempio n. 14
0
        public void TestPositionIncrementsRead()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestPositionIncrementsRead");

            createFile(filePath);

            byte[]    buffer = new byte[5];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForReading(filePath);
            wfio.ReadBlocks(buffer.Length);

            Assert.AreEqual(5, wfio.Position);

            wfio.Close();
        }
Esempio n. 15
0
        public void TestLengthWrite()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestLengthWrite");

            byte[]    buffer = new byte[FILE_CONTENT.Length];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForWriting(filePath);
            Array.Copy(FILE_CONTENT, buffer, buffer.Length);
            wfio.WriteBlocks(buffer.Length);

            Assert.AreEqual((long)FILE_CONTENT.Length, wfio.Length);
            wfio.Close();

            fileNames.Add(filePath);
        }
Esempio n. 16
0
        public void TestReadFirst8Bytes()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestReadFirst8Bytes");

            createFile(filePath);

            byte[]    buffer = new byte[8];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForReading(filePath);
            wfio.ReadBlocks(buffer.Length);
            wfio.Close();

            byte[] expected = FILE_CONTENT.Take(buffer.Length).ToArray();
            CollectionAssert.AreEqual(expected, buffer);
        }
Esempio n. 17
0
        /// <summary>
        /// Read first available entry in given path
        /// </summary>
        /// <param name="paths"></param>
        /// <returns></returns>
        private static string ReadFirstAvailableEntry(List <string> paths)
        {
            foreach (string path in paths)
            {
                string   physicalPath;
                FileInfo fileInfo;
                try
                {
                    physicalPath = HostingEnvironment.MapPath(path);
                    fileInfo     = new FileInfo(physicalPath);
                    if (!fileInfo.Exists)
                    {
                        continue;
                    }
                }
                catch
                {
                    continue;
                }

                // verify the metadata is not disabled
                try
                {
                    string    propertiesXml = Path.Combine(Path.GetDirectoryName(physicalPath), ".properties.xml");
                    XDocument doc           = PropertyFileHelper.OpenReadWithoutLock(propertiesXml);
                    if (string.Compare(doc.Root.GetElementValue("IsDisabled", "false"), "true", true) == 0)
                    {
                        continue;
                    }
                }
                catch
                {
                }

                // if value is empty, then continue
                if (fileInfo.Length == 0L)
                {
                    continue;
                }
                string ret = WinFileIO.ReadWithoutLock(physicalPath);
                if (!string.IsNullOrWhiteSpace(ret))
                {
                    return(ret);
                }
            }
            return(string.Empty);
        }
Esempio n. 18
0
        public void WritePointArray(byte[] points_buffer)
        {
            if (File.Exists(_FullName))
            {
                Close();
                File.Delete(_FullName);
            }
            _WFIO = new WinFileIO();
            _WFIO.OpenForWriting(_FullName);
            byte[] header_bytes = _Header.ToByteArray();
            _WFIO.PinBuffer(header_bytes);
            _WFIO.WriteBlocks(header_bytes.Length);

            _WFIO.PinBuffer(points_buffer);
            _WFIO.WriteBlocks(points_buffer.Length);

            _WFIO.Close();
        }
Esempio n. 19
0
        public void TestWriteFirstByte()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestWriteFirstByte");

            byte[]    buffer = new byte[1];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForWriting(filePath);

            buffer[0] = FILE_CONTENT[0];
            wfio.WriteBlocks(buffer.Length);
            wfio.Close();

            byte[] expected = FILE_CONTENT.Take(1).ToArray();
            byte[] actual   = readFile(filePath);

            CollectionAssert.AreEqual(expected, actual);
        }
Esempio n. 20
0
        public void TestWriteWholeFile()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestWriteWholeFile");

            byte[]    buffer = new byte[FILE_CONTENT.Length];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForWriting(filePath);

            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = FILE_CONTENT[i];
            }
            wfio.WriteBlocks(buffer.Length);
            wfio.Close();

            byte[] expected = FILE_CONTENT;
            byte[] actual   = readFile(filePath);

            CollectionAssert.AreEqual(expected, actual);
        }
Esempio n. 21
0
        public void TestSetPositionRead()
        {
            string filePath = Path.Combine(TestContext.CurrentContext.TestDirectory, "WinFileIOTests.TestSetPositionRead");

            createFile(filePath);

            byte[]    buffer = new byte[4];
            WinFileIO wfio   = new WinFileIO(buffer);

            wfio.OpenForReading(filePath);

            Assert.AreEqual(0, wfio.Position);
            wfio.Position = 5;
            Assert.AreEqual(5, wfio.Position);
            wfio.ReadBlocks(buffer.Length);
            Assert.AreEqual(5 + buffer.Length, wfio.Position);

            byte[] expected = FILE_CONTENT.Skip(5).Take(buffer.Length).ToArray();
            CollectionAssert.AreEqual(expected, buffer);

            wfio.Close();
        }
Esempio n. 22
0
        private static PreparsedContent GetPreparsedContent(cmSite site, string path)
        {
            string           cacheKey         = string.Format("snippet_{0}_preparsed_{1}", site.DistinctName, path);
            PreparsedContent preparsedContent = HttpRuntime.Cache[cacheKey] as PreparsedContent;

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

            preparsedContent = new PreparsedContent();

            List <string> paths = new List <string>();

            paths.Add(string.Format(CultureInfo.InvariantCulture, "~/Views/{0}/{1}", site.DistinctName, path.TrimStart('/')));
            if (!string.IsNullOrEmpty(site.TemplateDomainDistinctName))
            {
                paths.Add(string.Format(CultureInfo.InvariantCulture, "~/Views/{0}/{1}", site.TemplateDomainDistinctName, path.TrimStart('/')));
            }

            string content = null;

            foreach (string relativePath in paths)
            {
                string physicalPath = HostingEnvironment.MapPath(relativePath);
                preparsedContent.DependedFiles.Add(physicalPath);
                content = WinFileIO.ReadWithoutLock(physicalPath);
                if (content == null)
                {
                    continue;
                }
                break;
            }

            if (!string.IsNullOrEmpty(content))
            {
                // remove comments
                content = Regex.Replace(content
                                        , @"(\<\!\-\-)(.*?)(\-\-\>)"
                                        , string.Empty
                                        , RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline
                                        );
                preparsedContent.Content = content;

                // parse tags
                string currentMetadataPath = Regex.Replace(path
                                                           , @"(\/[^\/]+)$"
                                                           , delegate(Match m) { return(string.Format(CultureInfo.InvariantCulture, "/_{0}", Regex.Replace(m.ToString().TrimStart('/'), @"[^\w\-_]", "_", RegexOptions.Compiled))); }
                                                           , RegexOptions.Compiled);

                MatchCollection matches = Regex.Matches(content
                                                        , @"\[(\s*)metadata(\s*)\:(\s*)(?<method>((htmlencode)|(scriptencode)|(value)))(\s*)\((\s*)(?<path>(\w|\/|\-|\_|\.)+)(\s*)\)(\s*)\]"
                                                        , RegexOptions.Multiline | RegexOptions.ECMAScript | RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant
                                                        );
                foreach (Match match in matches)
                {
                    PreparsedContentTag tag = new PreparsedContentTag()
                    {
                        StartIndex   = match.Index,
                        Length       = match.Length,
                        Method       = match.Groups["method"].Value.ToLowerInvariant(),
                        MetadataPath = Metadata.ResolvePath(currentMetadataPath, match.Groups["path"].Value)
                    };
                    preparsedContent.Tags.Add(tag);
                }
                preparsedContent.Tags.Sort((a, b) =>
                {
                    if (a.StartIndex > b.StartIndex)
                    {
                        return(1);
                    }
                    else if (a.StartIndex < b.StartIndex)
                    {
                        return(-1);
                    }
                    else
                    {
                        return(0);
                    }
                });
            }

            HttpRuntime.Cache.Insert(cacheKey
                                     , preparsedContent
                                     , new CacheDependencyEx(preparsedContent.DependedFiles.ToArray(), false)
                                     , Cache.NoAbsoluteExpiration
                                     , Cache.NoSlidingExpiration
                                     , CacheItemPriority.NotRemovable
                                     , null
                                     );

            return(preparsedContent);
        }
Esempio n. 23
0
        public static void Compress(string Folder, Action <int, int> reportProgress, bool is64 = false, int compression = 1)
        {
            string[] files = Directory.EnumerateFiles(Folder, "*", SearchOption.AllDirectories).ToArray();

            MemoryStream fileTableEntriesStream = new MemoryStream();
            MemoryStream fileTableStream        = new MemoryStream();

            for (var i = 0; i < files.Length; i++)
            {
                reportProgress(i + 1, files.Length);

                string path = files[i].Replace(Folder, "").TrimStart('\\');

                byte[] unpackedFileBuffer;
                using (FileStream fis = new FileStream(files[i], FileMode.Open, FileAccess.ReadWrite, FileShare.Read, 2 << 15))
                    using (MemoryStream buf = new MemoryStream())
                    {
                        if (path.EndsWith(".xml") || path.EndsWith(".x16"))
                        {
                            // encode bxml
                            Convert(fis, BXML.DetectType(fis), buf, BXML_TYPE.BXML_BINARY);
                        }
                        else
                        {
                            // compress raw
                            fis.CopyTo(buf);
                        }

                        unpackedFileBuffer = buf.ToArray();
                    }

                BPKG_FTE entry = new BPKG_FTE
                {
                    FilePathLength       = path.Length,
                    FilePath             = path,
                    IsCompressed         = true,
                    IsEncrypted          = true,
                    FileDataOffset       = (int)fileTableStream.Position,
                    FileDataSizeUnpacked = unpackedFileBuffer.Length
                };

                byte[] packedFileBuffer = Pack(unpackedFileBuffer, out entry.FileDataSizeSheared, out entry.FileDataSizeStored, entry.IsEncrypted, entry.IsCompressed, compression);
                fileTableStream.Write(packedFileBuffer, 0, packedFileBuffer.Length);

                entry.WriteTo(fileTableEntriesStream, is64);
            }

            MemoryStream packageStream = new MemoryStream();
            BinaryWriter package       = new BinaryWriter(packageStream);

            package.Write(new[]
            {
                (byte)'U', (byte)'O', (byte)'S', (byte)'E', (byte)'D', (byte)'A', (byte)'L', (byte)'B'
            });                                          // Signature
            package.Write(2);                            // Version
            package.Write(new byte[] { 0, 0, 0, 0, 0 }); // Unknown 1

            if (is64)
            {
                package.Write(fileTableStream.Length);
                package.Write((long)files.Length);
            }
            else
            {
                package.Write((int)fileTableStream.Length);
                package.Write(files.Length);
            }

            package.Write(true);         // Is compressed
            package.Write(true);         // Is encrypted
            package.Write(new byte[62]); // Unknown 2

            int FTESizePacked;

            byte[] packedFTEBuffer = Pack(fileTableEntriesStream.ToArray(), out _, out FTESizePacked, true, true, compression);

            if (is64)
            {
                package.Write((long)FTESizePacked);
                package.Write(fileTableEntriesStream.Length);
            }
            else
            {
                package.Write(FTESizePacked);
                package.Write((int)fileTableEntriesStream.Length);
            }

            package.Write(packedFTEBuffer);

            int globalOffset = (int)packageStream.Position + (is64 ? 8 : 4);

            if (is64)
            {
                package.Write((long)globalOffset);
            }
            else
            {
                package.Write(globalOffset);
            }

            // Write the packed file data
            package.Write(fileTableStream.ToArray());

            WinFileIO writer = new WinFileIO(packageStream.ToArray());

            writer.OpenForWriting(Folder.Replace(".files", ""));
            writer.WriteBlocks((int)packageStream.Length);
            writer.Close();
        }
Esempio n. 24
0
        public static string[] GetChildrenPaths(cmSite domain, string path, bool useCache = true, bool ignoreUKLicense = false)
        {
            string cacheKey = string.Format("metadata_children_{0}_{1}_{2}", domain.ID, path, IsUKLicense);

            string[] paths = HttpRuntime.Cache[cacheKey] as string[];
            if (useCache && paths != null)
            {
                return(paths);
            }

            // sort
            List <string> dependedFiles = new List <string>();
            List <string> priority      = new List <string>();
            {
                string orderList    = null;
                string physicalPath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}", domain.DistinctName, path.TrimStart('/'))
                    );
                dependedFiles.Add(physicalPath);
                physicalPath = Path.Combine(physicalPath, "_orderlist");
                if (!File.Exists(physicalPath))
                {
                    if (!string.IsNullOrEmpty(domain.TemplateDomainDistinctName))
                    {
                        physicalPath = HostingEnvironment.MapPath(
                            string.Format("~/Views/{0}/{1}", domain.TemplateDomainDistinctName, path.TrimStart('/'))
                            );
                        dependedFiles.Add(physicalPath);
                        physicalPath = Path.Combine(physicalPath, "_orderlist");
                    }
                }
                orderList = WinFileIO.ReadWithoutLock(physicalPath);
                if (orderList != null)
                {
                    priority = orderList.Split(',').Where(i => !string.IsNullOrEmpty(i)).ToList();
                }
            }

            Dictionary <string, bool> ret     = GetChildren(domain, path);
            Dictionary <string, bool> tempDic = new Dictionary <string, bool>();

            {
                foreach (var item in priority)
                {
                    string key = string.Format("{0}/{1}", path.TrimEnd('/'), item);
                    if (ret.ContainsKey(key))
                    {
                        tempDic.Add(key, ret[key]);
                        ret.Remove(key);
                    }
                }
            }
            foreach (KeyValuePair <string, bool> item in ret)
            {
                tempDic.Add(item.Key, item.Value);
            }

            DateTime      now             = DateTime.Now;
            DateTime      cacheExpiryTime = now.AddHours(1);
            List <string> temp            = new List <string>();

            {
                foreach (KeyValuePair <string, bool> item in tempDic)
                {
                    DateTime validFrom;
                    DateTime expiryTime;
                    bool     availableForUKLicense;
                    bool     availableForNonUKLicense;

                    string physicalPath = HostingEnvironment.MapPath(
                        string.Format("~/Views/{0}/{1}"
                                      , item.Value ? domain.TemplateDomainDistinctName : domain.DistinctName
                                      , item.Key.TrimStart('/'))
                        );
                    if (IsInherited(physicalPath))
                    {
                        physicalPath = HostingEnvironment.MapPath(string.Format("~/Views/{0}/{1}", domain.TemplateDomainDistinctName, item.Key.TrimStart('/')));
                    }

                    Metadata.GetProperties(physicalPath, out validFrom, out expiryTime, out availableForUKLicense, out availableForNonUKLicense);

                    if (ignoreUKLicense ||
                        (IsUKLicense && availableForUKLicense) ||
                        (!IsUKLicense && availableForNonUKLicense))
                    {
                        if (now >= validFrom && now <= expiryTime)
                        {
                            temp.Add(item.Key);
                        }

                        if (cacheExpiryTime > validFrom && validFrom > now)
                        {
                            cacheExpiryTime = validFrom;
                        }

                        if (cacheExpiryTime > expiryTime && expiryTime > now)
                        {
                            cacheExpiryTime = expiryTime;
                        }
                    }
                }
            }

            HttpRuntime.Cache.Insert(cacheKey
                                     , temp.ToArray()
                                     , new CacheDependencyEx(dependedFiles.ToArray(), false)
                                     , cacheExpiryTime//, DateTime.Now.AddHours(1)
                                     , Cache.NoSlidingExpiration
                                     , CacheItemPriority.NotRemovable
                                     , null
                                     );

            return(temp.ToArray());
        }
Esempio n. 25
0
        /// <summary>
        /// Write the metadata entry
        /// </summary>
        /// <param name="site"></param>
        /// <param name="path"></param>
        /// <param name="lang">If language is null, then default value is written</param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool Save(cmSite site, string path, string lang, string name, string value)
        {
            string postfix      = string.IsNullOrWhiteSpace(lang) ? string.Empty : "." + lang;
            string physicalPath = HostingEnvironment.MapPath(
                string.Format("~/Views/{0}/{1}/.{2}{3}", site.DistinctName, path.TrimStart('/').TrimEnd('/'), name, postfix)
                );

            ContentTree.EnsureDirectoryExistsForFile(site, physicalPath);

            SqlQuery <cmRevision> query = new SqlQuery <cmRevision>();
            string filePath;
            string localFile;
            string metadataPath = path.TrimEnd('/') + "/." + name + postfix;

            if (File.Exists(physicalPath))
            {
                // nothing changed
                if (WinFileIO.ReadWithoutLock(physicalPath) == value)
                {
                    return(false);
                }

                // if last revision not exist, backup first
                {
                    RevisionAccessor ra       = DataAccessor.CreateInstance <RevisionAccessor>();
                    cmRevision       revision = ra.GetLastRevision(site.ID, metadataPath);
                    if (revision == null || !File.Exists(Revisions.GetLocalPath(revision.FilePath)))
                    {
                        localFile = Revisions.GetNewFilePath(out filePath);
                        File.Copy(physicalPath, localFile);

                        revision              = new cmRevision();
                        revision.Comments     = string.Format("No revision found for [{0}], language=[{1}], make a backup.", name, lang.DefaultIfNullOrEmpty("default"));
                        revision.SiteID       = site.ID;
                        revision.FilePath     = filePath;
                        revision.Ins          = DateTime.Now;
                        revision.RelativePath = metadataPath;
                        revision.UserID       = CustomProfile.Current.UserID;
                        query.Insert(revision);
                    }
                }
            }
            else if (!string.IsNullOrWhiteSpace(site.TemplateDomainDistinctName))
            {
                string inheritedPath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}/.{2}{3}", site.TemplateDomainDistinctName, path.TrimStart('/').TrimEnd('/'), name, postfix)
                    );
                if (File.Exists(inheritedPath))
                {
                    // nothing changed
                    if (WinFileIO.ReadWithoutLock(inheritedPath) == value)
                    {
                        return(false);
                    }
                }
                else if (string.IsNullOrWhiteSpace(value))
                {
                    return(false);
                }
            }
            else if (string.IsNullOrWhiteSpace(value))
            {
                return(false);
            }

            using (FileStream fs = new FileStream(physicalPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite))
            {
                fs.SetLength(0);
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                {
                    sw.Write(value);
                }
            }

            // copy the file to backup
            localFile = Revisions.GetNewFilePath(out filePath);
            File.Copy(physicalPath, localFile);

            // save to cmRevision
            {
                cmRevision revision = new cmRevision();
                revision.Comments     = string.Format("update the entry [{0}], language=[{1}].", name, lang.DefaultIfNullOrEmpty("default"));
                revision.SiteID       = site.ID;
                revision.FilePath     = filePath;
                revision.Ins          = DateTime.Now;
                revision.RelativePath = metadataPath;
                revision.UserID       = CustomProfile.Current.UserID;
                query.Insert(revision);
            }


            return(true);
        }
Esempio n. 26
0
 public string GetFileContent()
 {
     return(WinFileIO.ReadWithoutLock(this.PhysicalPath));
 }
Esempio n. 27
0
        private static string GetFileContent(string appRelativeVirtualPath, string path)
        {
            try
            {
                appRelativeVirtualPath = VirtualPathUtility.GetDirectory(appRelativeVirtualPath.TrimStart('~'));

                Match match = pathRegex.Match(appRelativeVirtualPath);
                if (match.Success)
                {
                    appRelativeVirtualPath = match.Groups["path"].Value;
                }

                if (!path.StartsWith("/"))
                {
                    path = VirtualPathUtility.Combine(appRelativeVirtualPath, path);
                }


                cmSite site      = SiteManager.Current;
                string cachePath = string.Format("ContentHelper.GetFileContent.{0}.{1}"
                                                 , site.DistinctName
                                                 , path
                                                 );

                string content = HttpRuntime.Cache[cachePath] as string;
                if (content != null)
                {
                    return(content);
                }

                List <string> dependedFiles = new List <string>();

                string filePath = HostingEnvironment.MapPath(
                    string.Format("~/Views/{0}/{1}", site.DistinctName, (path ?? string.Empty).TrimStart('/'))
                    );
                dependedFiles.Add(filePath);
                content = WinFileIO.ReadWithoutLock(filePath);
                if ((content == null) && (!string.IsNullOrWhiteSpace(site.TemplateDomainDistinctName)))
                {
                    filePath = HostingEnvironment.MapPath(
                        string.Format("~/Views/{0}/{1}", site.TemplateDomainDistinctName, (path ?? string.Empty).TrimStart('/'))
                        );
                    dependedFiles.Add(filePath);
                    content = WinFileIO.ReadWithoutLock(filePath);
                }

                if (content == null)
                {
                    content = string.Empty;
                }

                HttpRuntime.Cache.Insert(cachePath
                                         , content
                                         , new CacheDependencyEx(dependedFiles.ToArray(), false)
                                         , Cache.NoAbsoluteExpiration
                                         , Cache.NoSlidingExpiration
                                         );
                return(content);
            }
            catch
            {
                return(string.Empty);
            }
        }