Пример #1
0
        /**
         * Creates a Workbook from the given NPOIFSFileSystem, which may
         *  be password protected
         */
        private static IWorkbook Create(NPOIFSFileSystem fs, string password)
        {
            DirectoryNode root = fs.Root;

            // Encrypted OOXML files go inside OLE2 containers, is this one?
            if (root.HasEntry(Decryptor.DEFAULT_POIFS_ENTRY))
            {
                InputStream stream = DocumentFactoryHelper.GetDecryptedStream(fs, password);

                OPCPackage pkg = OPCPackage.Open(stream);
                return(Create(pkg));
            }

            // If we get here, it isn't an encrypted XLSX file
            // So, treat it as a regular HSSF XLS one
            if (password != null)
            {
                Biff8EncryptionKey.CurrentUserPassword = (password);
            }
            try
            {
                return(new HSSFWorkbook(root, true));
            }
            finally
            {
                Biff8EncryptionKey.CurrentUserPassword = (null);
            }
        }
Пример #2
0
        public void TestWriteFailsOnLoop()
        {
            NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));

            // Hack the FAT so that it goes 0->1->2->0
            fs.SetNextBlock(0, 1);
            fs.SetNextBlock(1, 2);
            fs.SetNextBlock(2, 0);

            // Try to write a large amount, should fail on the write
            byte[]       data   = new byte[512 * 4];
            NPOIFSStream stream = new NPOIFSStream(fs, 0);

            try
            {
                stream.UpdateContents(data);
                Assert.Fail("Loop should have been detected but wasn't!");
            }
            catch (Exception) { }

            // Now reset, and try on a small bit
            // Should fail during the freeing set
            fs.SetNextBlock(0, 1);
            fs.SetNextBlock(1, 2);
            fs.SetNextBlock(2, 0);

            data   = new byte[512];
            stream = new NPOIFSStream(fs, 0);
            try
            {
                stream.UpdateContents(data);
                Assert.Fail("Loop should have been detected but wasn't!");
            }
            catch (Exception) { }
        }
Пример #3
0
        /**
         * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
         *  the given File, which must exist and be readable.
         */
        public static IWorkbook Create(string file)
        {
            if (!File.Exists(file))
            {
                throw new FileNotFoundException(file);
            }
            FileStream fStream = null;

            try
            {
                fStream = new FileStream(file, FileMode.Open, FileAccess.Read);
                NPOIFSFileSystem fs = new NPOIFSFileSystem(fStream);
                IWorkbook        wb = new HSSFWorkbook(fs.Root, true);
                return(wb);
            }
            catch (OfficeXmlFileException e)
            {
                OPCPackage pkg = OPCPackage.Open(file);
                return(new XSSFWorkbook(pkg));
            }
            finally
            {
                if (fStream != null)
                {
                    fStream.Close();
                }
            }
        }
Пример #4
0
        public void TestReplaceStream()
        {
            NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize512.zvi"));

            byte[] data = new byte[512];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(i % 256);
            }

            // 98 is actually the last block in a two block stream...
            NPOIFSStream stream = new NPOIFSStream(fs, 98);

            stream.UpdateContents(data);

            // Check the reading of blocks
            IEnumerator <ByteBuffer> it = stream.GetBlockIterator();

            Assert.AreEqual(true, it.MoveNext());

            //  it.MoveNext();
            ByteBuffer b = it.Current;

            Assert.AreEqual(false, it.MoveNext());

            // Now check the contents
            data = new byte[512];
            b.Read(data);
            for (int i = 0; i < data.Length; i++)
            {
                byte exp = (byte)(i % 256);
                Assert.AreEqual(exp, data[i]);
            }
        }
Пример #5
0
        public void TestCreateWriteRead()
        {
            NPOIFSFileSystem fs = new NPOIFSFileSystem();

            // Initially has a BAT but not SBAT
            Assert.AreEqual(POIFSConstants.FAT_SECTOR_BLOCK, fs.GetNextBlock(0));
            Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(1));
            Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, fs.GetNextBlock(2));

            // Check that the SBAT is empty
            Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.Root.Property.StartBlock);

            // Write and read it
            MemoryStream baos = new MemoryStream();

            fs.WriteFilesystem(baos);
            byte[] temp = baos.ToArray();
            fs = new NPOIFSFileSystem(new MemoryStream(temp));
            //fs = new NPOIFSFileSystem(new MemoryStream(baos.ToArray()));

            // Check it's still like that
            Assert.AreEqual(POIFSConstants.FAT_SECTOR_BLOCK, fs.GetNextBlock(0));
            Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(1));
            Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, fs.GetNextBlock(2));
            Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.Root.Property.StartBlock);

            // Now add a normal stream and a mini stream
            // TODO

            // TODO The rest of the test
        }
Пример #6
0
        public void TestGetDocumentEntry()
        {
            NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));
            NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize512.zvi"));
            NPOIFSFileSystem fsC = new NPOIFSFileSystem(_inst.GetFile("BlockSize4096.zvi"));
            NPOIFSFileSystem fsD = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize4096.zvi"));


            foreach (NPOIFSFileSystem fs in new NPOIFSFileSystem[] { fsA, fsB, fsC, fsD })
            {
                DirectoryEntry root = fs.Root;
                Entry          si   = root.GetEntry("\x0005SummaryInformation");

                Assert.AreEqual(true, si.IsDocumentEntry);
                DocumentNode doc = (DocumentNode)si;

                // Check we can read it
                NDocumentInputStream inp = new NDocumentInputStream(doc);
                byte[] contents          = new byte[doc.Size];
                Assert.AreEqual(doc.Size, inp.Read(contents));

                // Now try to build the property set
                //  ByteBuffer temp = inp.GetCurrentBuffer();
                inp = new NDocumentInputStream(doc);

                PropertySet        ps  = PropertySetFactory.Create(inp);
                SummaryInformation inf = (SummaryInformation)ps;

                // Check some bits in it
                Assert.AreEqual(null, inf.ApplicationName);
                Assert.AreEqual(null, inf.Author);
                Assert.AreEqual(null, inf.Subject);
            }
        }
Пример #7
0
        public List <DataTable> Load(MemoryStream stream)
        {
            var tables = new List <DataTable>();
            var copy   = new MemoryStream();

            stream.CopyTo(copy);

            try
            {
                HSSFWorkbook workbook = null;
                if (!string.IsNullOrWhiteSpace(_password))
                {
                    // only XOR/RC4 supported, not CryptoAPI
                    Biff8EncryptionKey.CurrentUserPassword = _password;
                    switch (_format)
                    {
                    case XLSFormat.NPOI:
                    {
                        var infs = new NPOIFSFileSystem(stream);
                        workbook = new HSSFWorkbook(infs.Root, true);
                    }
                    break;

                    case XLSFormat.POI:
                    {
                        var fs = new POIFSFileSystem(stream);
                        workbook = new HSSFWorkbook(fs);
                    }
                    break;

                    default:
                        throw new RFSystemException(this, "Unsupported XLS Format {0}", _format);
                    }
                }
                else
                {
                    workbook = new HSSFWorkbook(stream);
                }
                if (workbook != null)
                {
                    for (int i = 0; i < workbook.NumberOfSheets; ++i)
                    {
                        try
                        {
                            tables.Add(ConvertToDataTable(workbook.GetSheetAt(i)));
                        }
                        catch (Exception ex)
                        {
                            throw new RFSystemException(Caller(), ex, "Error extracting XLS sheet number {0}", i);
                        }
                    }
                }
            }
            catch (OldExcelFormatException)
            {
                // congrats to ppl using 1993 formats in 2016
                tables.Add(LoadIntoDataTableExcel95(copy));
            }
            return(tables);
        }
Пример #8
0
        public void InPlaceReWrite()
        {
            FileInfo f = TempFile.CreateTempFile("protected_agile", ".docx");
            // File f = new File("protected_agile.docx");
            FileStream fos = f.Create();
            Stream     fis = POIDataSamples.GetPOIFSInstance().OpenResourceAsStream("protected_agile.docx");

            IOUtils.Copy(fis, fos);
            fis.Close();
            fos.Close();

            NPOIFSFileSystem fs = new NPOIFSFileSystem(f, false);

            // decrypt the protected file - in this case it was encrypted with the default password
            EncryptionInfo encInfo = new EncryptionInfo(fs);
            Decryptor      d       = encInfo.Decryptor;
            bool           b       = d.VerifyPassword(Decryptor.DEFAULT_PASSWORD);

            Assert.IsTrue(b);

            // do some strange things with it ;)
            XWPFDocument docx = new XWPFDocument(d.GetDataStream(fs));

            docx.GetParagraphArray(0).InsertNewRun(0).SetText("POI was here! All your base are belong to us!");
            docx.GetParagraphArray(0).InsertNewRun(1).AddBreak();

            // and encrypt it again
            Encryptor e = encInfo.Encryptor;

            e.ConfirmPassword("AYBABTU");
            docx.Write(e.GetDataStream(fs));

            fs.Close();
        }
Пример #9
0
        private void Open(Stream biffStream)
        {
            BufferedStream bis = (biffStream is BufferedStream)
            ? (BufferedStream)biffStream
            : new BufferedStream(biffStream, 8);

            if (NPOIFSFileSystem.HasPOIFSHeader(bis))
            {
                NPOIFSFileSystem poifs = new NPOIFSFileSystem(bis);
                try
                {
                    Open(poifs);
                }
                finally
                {
                    poifs.Close();
                }
            }
            else
            {
                ris           = new RecordInputStream(bis);
                toCloseStream = bis;
                Prepare();
            }
        }
Пример #10
0
        private void OpenOOXML(Stream zipFile)
        {
            ZipInputStream zis = new ZipInputStream(zipFile);
            ZipEntry       zipEntry;

            while ((zipEntry = zis.GetNextEntry()) != null)
            {
                if (zipEntry.Name.EndsWith(VBA_PROJECT_OOXML, StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        // Make a NPOIFS from the contents, and close the stream
                        this.fs = new NPOIFSFileSystem(zis);
                        return;
                    }
                    catch (IOException e)
                    {
                        // Tidy up
                        zis.Close();

                        // Pass on
                        throw e;
                    }
                }
            }
            zis.Close();
            throw new ArgumentException("No VBA project found");
        }
Пример #11
0
        protected DirectoryNode[] openSamples(Stream[] inps, bool oldFails)
        {
            NPOIFSFileSystem nfs = new NPOIFSFileSystem(inps[0]);

            if (openedFSs == null)
            {
                openedFSs = new List <NPOIFSFileSystem>();
            }
            openedFSs.Add(nfs);

            POIFSFileSystem ofs = null;

            try
            {
                ofs = new POIFSFileSystem(inps[1]);
                if (oldFails)
                {
                    Assert.Fail("POIFSFileSystem should have failed but didn't");
                }
            }
            catch (Exception e)
            {
                if (!oldFails)
                {
                    throw e;
                }
            }

            if (ofs == null)
            {
                return new DirectoryNode[] { nfs.Root }
            }
            ;
            return(new DirectoryNode[] { ofs.Root, nfs.Root });
        }
Пример #12
0
 public NPropertyTable(HeaderBlock headerBlock, NPOIFSFileSystem fileSystem)
     : base(headerBlock,
            BuildProperties((new NPOIFSStream(fileSystem, headerBlock.PropertyStart)).GetEnumerator(), headerBlock.BigBlockSize)
            )
 {
     _bigBigBlockSize = headerBlock.BigBlockSize;
 }
Пример #13
0
        public void TestReadTinyStream()
        {
            NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));

            // 98 is actually the last block in a two block stream...
            NPOIFSStream             stream = new NPOIFSStream(fs, 98);
            IEnumerator <ByteBuffer> i      = stream.GetBlockIterator();

            Assert.AreEqual(true, i.MoveNext());
            ByteBuffer b = i.Current;

            Assert.AreEqual(false, i.MoveNext());

            // Check the contents
            Assert.AreEqual((byte)0x81, b[0]);
            Assert.AreEqual((byte)0x00, b[1]);
            Assert.AreEqual((byte)0x00, b[2]);
            Assert.AreEqual((byte)0x00, b[3]);
            Assert.AreEqual((byte)0x82, b[4]);
            Assert.AreEqual((byte)0x00, b[5]);
            Assert.AreEqual((byte)0x00, b[6]);
            Assert.AreEqual((byte)0x00, b[7]);

            fs.Close();
        }
Пример #14
0
        public void WriteWorkbookFromNPOIFS()
        {
            Stream is1 = HSSFTestDataSamples.OpenSampleFileStream("WithEmbeddedObjects.xls");

            try
            {
                NPOIFSFileSystem fs = new NPOIFSFileSystem(is1);
                try
                {
                    // Start as NPOIFS
                    HSSFWorkbook wb = new HSSFWorkbook(fs.Root, true);
                    Assert.AreEqual(3, wb.NumberOfSheets);
                    Assert.AreEqual("Root xls", wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue);

                    // Will switch to POIFS
                    wb = HSSFTestDataSamples.WriteOutAndReadBack(wb);
                    Assert.AreEqual(3, wb.NumberOfSheets);
                    Assert.AreEqual("Root xls", wb.GetSheetAt(0).GetRow(0).GetCell(0).StringCellValue);
                }
                finally
                {
                    fs.Close();
                }
            }
            finally
            {
                is1.Close();
            }
        }
Пример #15
0
        public void TestGetFreeBlockWithSpare()
        {
            NPOIFSFileSystem fs        = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));
            NPOIFSMiniStore  ministore = fs.GetMiniStore();

            // Our 2nd SBAT block has spares
            Assert.AreEqual(false, ministore.GetBATBlockAndIndex(0).Block.HasFreeSectors);
            Assert.AreEqual(true, ministore.GetBATBlockAndIndex(128).Block.HasFreeSectors);

            // First free one at 181
            Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(181));
            Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(182));
            Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(183));
            Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, ministore.GetNextBlock(184));

            // Ask, will get 181
            Assert.AreEqual(181, ministore.GetFreeBlock());

            // Ask again, will still get 181 as not written to
            Assert.AreEqual(181, ministore.GetFreeBlock());

            // Allocate it, then ask again
            ministore.SetNextBlock(181, POIFSConstants.END_OF_CHAIN);
            Assert.AreEqual(182, ministore.GetFreeBlock());

            fs.Close();
        }
Пример #16
0
        public void Bug57080()
        {
            // the test file Contains a wrong ole entry size, produced by extenxls
            // the fix limits the available size and tries to read all entries
            FileStream       f    = POIDataSamples.GetPOIFSInstance().GetFile("extenxls_pwd123.xlsx");
            NPOIFSFileSystem fs   = new NPOIFSFileSystem(f, true);
            EncryptionInfo   info = new EncryptionInfo(fs);
            Decryptor        d    = Decryptor.GetInstance(info);

            d.VerifyPassword("pwd123");
            MemoryStream   bos = new MemoryStream();
            ZipInputStream zis = new ZipInputStream(d.GetDataStream(fs));
            ZipEntry       ze;

            while ((ze = zis.GetNextEntry()) != null)
            {
                //bos.Reset();
                bos.Seek(0, SeekOrigin.Begin);
                bos.SetLength(0);
                IOUtils.Copy(zis, bos);
                Assert.AreEqual(ze.Size, bos.Length);
            }

            zis.Close();
            fs.Close();
        }
Пример #17
0
        public void TestReadLongerStream()
        {
            NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));

            ByteBuffer b0  = null;
            ByteBuffer b1  = null;
            ByteBuffer b22 = null;

            // The stream at 0 has 23 blocks in it
            NPOIFSStream             stream = new NPOIFSStream(fs, 0);
            IEnumerator <ByteBuffer> i      = stream.GetBlockIterator();

            int count = 0;

            while (i.MoveNext())
            {
                ByteBuffer b = i.Current;
                if (count == 0)
                {
                    b0 = b;
                }
                if (count == 1)
                {
                    b1 = b;
                }
                if (count == 22)
                {
                    b22 = b;
                }

                count++;
            }
            Assert.AreEqual(23, count);

            // Check the contents
            //  1st block is at 0
            Assert.AreEqual((byte)0x9e, b0[0]);
            Assert.AreEqual((byte)0x75, b0[1]);
            Assert.AreEqual((byte)0x97, b0[2]);
            Assert.AreEqual((byte)0xf6, b0[3]);

            //  2nd block is at 1
            Assert.AreEqual((byte)0x86, b1[0]);
            Assert.AreEqual((byte)0x09, b1[1]);
            Assert.AreEqual((byte)0x22, b1[2]);
            Assert.AreEqual((byte)0xfb, b1[3]);

            //  last block is at 89
            Assert.AreEqual((byte)0xfe, b22[0]);
            Assert.AreEqual((byte)0xff, b22[1]);
            Assert.AreEqual((byte)0x00, b22[2]);
            Assert.AreEqual((byte)0x00, b22[3]);
            Assert.AreEqual((byte)0x05, b22[4]);
            Assert.AreEqual((byte)0x01, b22[5]);
            Assert.AreEqual((byte)0x02, b22[6]);
            Assert.AreEqual((byte)0x00, b22[7]);

            fs.Close();
        }
Пример #18
0
        public static NPOIFSFileSystem WriteOutAndReadBack(NPOIFSFileSystem original)
        {
            MemoryStream baos = new MemoryStream();

            original.WriteFileSystem(baos);
            original.Close();
            return(new NPOIFSFileSystem(new ByteArrayInputStream(baos.ToArray())));
        }
Пример #19
0
        /**
         * Write out to the currently open file the properties changes, but nothing else
         */
        public override void Write()
        {
            NPOIFSFileSystem fs = directory.FileSystem;

            ValidateInPlaceWritePossible();
            WriteProperties(fs, null);
            fs.WriteFileSystem();
        }
Пример #20
0
        public void TestWriteStream4096()
        {
            NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize4096.zvi"));

            // 0 -> 1 -> 2 -> end
            Assert.AreEqual(1, fs.GetNextBlock(0));
            Assert.AreEqual(2, fs.GetNextBlock(1));
            Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(2));
            Assert.AreEqual(4, fs.GetNextBlock(3));

            // First free one is at 15
            Assert.AreEqual(POIFSConstants.FAT_SECTOR_BLOCK, fs.GetNextBlock(14));
            Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, fs.GetNextBlock(15));


            // Write a 5 block file
            byte[] data = new byte[4096 * 5];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)(i % 256);
            }
            NPOIFSStream stream = new NPOIFSStream(fs, 0);

            stream.UpdateContents(data);


            // Check it
            Assert.AreEqual(1, fs.GetNextBlock(0));
            Assert.AreEqual(2, fs.GetNextBlock(1));
            Assert.AreEqual(15, fs.GetNextBlock(2));                           // Jumps
            Assert.AreEqual(4, fs.GetNextBlock(3));                            // Next stream
            Assert.AreEqual(POIFSConstants.FAT_SECTOR_BLOCK, fs.GetNextBlock(14));
            Assert.AreEqual(16, fs.GetNextBlock(15));                          // Continues
            Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(16)); // Ends
            Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, fs.GetNextBlock(17)); // Free

            // Check the contents too
            IEnumerator <ByteBuffer> it = stream.GetBlockIterator();
            int count = 0;

            while (it.MoveNext())
            {
                ByteBuffer b = it.Current;
                data = new byte[512];
                // b.get(data);
                //  Array.Copy(b, 0, data, 0, b.Length);
                b.Read(data);
                for (int i = 0; i < data.Length; i++)
                {
                    byte exp = (byte)(i % 256);
                    Assert.AreEqual(exp, data[i]);
                }
                count++;
            }
            Assert.AreEqual(5, count);

            fs.Close();
        }
Пример #21
0
        /**
         * Returns test files with 512 byte and 4k block sizes, loaded
         *  both from InputStreams and Files
         */
        protected NPOIFSFileSystem[] get512and4kFileAndInput()
        {
            NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));
            NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize512.zvi"));
            NPOIFSFileSystem fsC = new NPOIFSFileSystem(_inst.GetFile("BlockSize4096.zvi"));
            NPOIFSFileSystem fsD = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize4096.zvi"));

            return(new NPOIFSFileSystem[] { fsA, fsB, fsC, fsD });
        }
Пример #22
0
        public void TestNextBlock()
        {
            NPOIFSFileSystem fsA = new NPOIFSFileSystem(_inst.GetFile("BlockSize512.zvi"));
            NPOIFSFileSystem fsB = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize512.zvi"));

            foreach (NPOIFSFileSystem fs in new NPOIFSFileSystem[] { fsA, fsB })
            {
                for (int i = 0; i < 21; i++)
                {
                    Assert.AreEqual(i + 1, fs.GetNextBlock(i));
                }

                // 21 jumps to 89, then ends
                Assert.AreEqual(89, fs.GetNextBlock(21));
                Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(89));

                for (int i = 22; i < 88; i++)
                {
                    Assert.AreEqual(i + 1, fs.GetNextBlock(i));
                }
                Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(88));

                for (int i = 90; i < 96; i++)
                {
                    Assert.AreEqual(i + 1, fs.GetNextBlock(i));
                }
                Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(96));

                Assert.AreEqual(98, fs.GetNextBlock(97));
                Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(98));

                Assert.AreEqual(POIFSConstants.FAT_SECTOR_BLOCK, fs.GetNextBlock(99));

                //Leon i = 100
                for (int i = 100; i < fs.GetBigBlockSizeDetails().GetBATEntriesPerBlock(); i++)
                {
                    Assert.AreEqual(POIFSConstants.UNUSED_BLOCK, fs.GetNextBlock(i));
                }
            }

            fsA = new NPOIFSFileSystem(_inst.GetFile("BlockSize4096.zvi"));
            fsB = new NPOIFSFileSystem(_inst.OpenResourceAsStream("BlockSize4096.zvi"));

            foreach (NPOIFSFileSystem fs in new NPOIFSFileSystem[] { fsA, fsB })
            {
                Assert.AreEqual(1, fs.GetNextBlock(0));
                Assert.AreEqual(2, fs.GetNextBlock(1));
                Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(2));

                for (int i = 4; i < 11; i++)
                {
                    Assert.AreEqual(i + 1, fs.GetNextBlock(i));
                }

                Assert.AreEqual(POIFSConstants.END_OF_CHAIN, fs.GetNextBlock(11));
            }
        }
Пример #23
0
        public void TestReadStream4096()
        {
            NPOIFSFileSystem fs = new NPOIFSFileSystem(_inst.GetFile("BlockSize4096.zvi"));

            // 0 -> 1 -> 2 -> end
            NPOIFSStream             stream = new NPOIFSStream(fs, 0);
            IEnumerator <ByteBuffer> i      = stream.GetBlockIterator();

            Assert.AreEqual(true, i.MoveNext());

            // i.MoveNext();
            ByteBuffer b0 = i.Current;

            Assert.AreEqual(true, i.MoveNext());

            // i.MoveNext();
            ByteBuffer b1 = i.Current;

            Assert.AreEqual(true, i.MoveNext());

            // i.MoveNext();
            ByteBuffer b2 = i.Current;

            Assert.AreEqual(false, i.MoveNext());

            // Check the contents of the 1st block
            Assert.AreEqual((byte)0x9E, b0[0]);
            Assert.AreEqual((byte)0x75, b0[1]);
            Assert.AreEqual((byte)0x97, b0[2]);
            Assert.AreEqual((byte)0xF6, b0[3]);
            Assert.AreEqual((byte)0xFF, b0[4]);
            Assert.AreEqual((byte)0x21, b0[5]);
            Assert.AreEqual((byte)0xD2, b0[6]);
            Assert.AreEqual((byte)0x11, b0[7]);

            // Check the contents of the 2nd block
            Assert.AreEqual((byte)0x00, b1[0]);
            Assert.AreEqual((byte)0x00, b1[1]);
            Assert.AreEqual((byte)0x03, b1[2]);
            Assert.AreEqual((byte)0x00, b1[3]);
            Assert.AreEqual((byte)0x00, b1[4]);
            Assert.AreEqual((byte)0x00, b1[5]);
            Assert.AreEqual((byte)0x00, b1[6]);
            Assert.AreEqual((byte)0x00, b1[7]);

            // Check the contents of the 3rd block
            Assert.AreEqual((byte)0x6D, b2[0]);
            Assert.AreEqual((byte)0x00, b2[1]);
            Assert.AreEqual((byte)0x00, b2[2]);
            Assert.AreEqual((byte)0x00, b2[3]);
            Assert.AreEqual((byte)0x03, b2[4]);
            Assert.AreEqual((byte)0x00, b2[5]);
            Assert.AreEqual((byte)0x46, b2[6]);
            Assert.AreEqual((byte)0x00, b2[7]);

            fs.Close();
        }
Пример #24
0
        public static HeaderBlock WriteOutAndReadHeader(NPOIFSFileSystem fs)
        {
            MemoryStream baos = new MemoryStream();

            fs.WriteFileSystem(baos);

            HeaderBlock header = new HeaderBlock(new MemoryStream(baos.ToArray()));

            return(header);
        }
Пример #25
0
        /**
         * Decrypt the Document-/SummaryInformation and other optionally streams.
         * Opposed to other crypto modes, cryptoapi is record based and can't be used
         * to stream-decrypt a whole file
         *
         * @see <a href="http://msdn.microsoft.com/en-us/library/dd943321(v=office.12).aspx">2.3.5.4 RC4 CryptoAPI Encrypted Summary Stream</a>
         */

        public override InputStream GetDataStream(DirectoryNode dir)
        {
            NPOIFSFileSystem    fsOut = new NPOIFSFileSystem();
            DocumentNode        es    = (DocumentNode)dir.GetEntry("EncryptedSummary");
            DocumentInputStream dis   = dir.CreateDocumentInputStream(es);
            MemoryStream        bos   = new MemoryStream();

            IOUtils.Copy(dis, bos);
            dis.Close();
            SeekableMemoryStream    sbis    = new SeekableMemoryStream(bos.ToArray());
            LittleEndianInputStream leis    = new LittleEndianInputStream(sbis);
            int streamDescriptorArrayOffset = (int)leis.ReadUInt();
            int streamDescriptorArraySize   = (int)leis.ReadUInt();

            sbis.Seek(streamDescriptorArrayOffset - 8, SeekOrigin.Current);// sbis.Skip(streamDescriptorArrayOffset - 8);

            sbis.SetBlock(0);
            int encryptedStreamDescriptorCount = (int)leis.ReadUInt();

            StreamDescriptorEntry[] entries = new StreamDescriptorEntry[encryptedStreamDescriptorCount];
            for (int i = 0; i < encryptedStreamDescriptorCount; i++)
            {
                StreamDescriptorEntry entry = new StreamDescriptorEntry();
                entries[i]         = entry;
                entry.streamOffset = (int)leis.ReadUInt();
                entry.streamSize   = (int)leis.ReadUInt();
                entry.block        = leis.ReadUShort();
                int nameSize = leis.ReadUByte();
                entry.flags = leis.ReadUByte();
                bool IsStream = StreamDescriptorEntry.flagStream.IsSet(entry.flags);
                entry.reserved2  = leis.ReadInt();
                entry.streamName = StringUtil.ReadUnicodeLE(leis, nameSize);
                leis.ReadShort();
                Debug.Assert(entry.streamName.Length == nameSize);
            }

            foreach (StreamDescriptorEntry entry in entries)
            {
                sbis.Seek(entry.streamOffset);
                sbis.SetBlock(entry.block);
                Stream is1 = new BufferedStream(sbis, entry.streamSize);
                fsOut.CreateDocument(is1, entry.streamName);
            }

            leis.Close();
            sbis = null;

            bos.Seek(0, SeekOrigin.Begin); //bos.Reset();
            fsOut.WriteFileSystem(bos);
            fsOut.Close();
            _length = bos.Length;
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.ToArray());

            throw new NotImplementedException("ByteArrayInputStream should be derived from InputStream");
        }
Пример #26
0
 public VBAMacroReader(FileInfo file)
 {
     try
     {
         this.fs = new NPOIFSFileSystem(file);
     }
     catch (OfficeXmlFileException)
     {
         OpenOOXML(file.OpenRead());
     }
 }
Пример #27
0
        public void TestReadMultipleTreeLevels()
        {
            POIDataSamples _samples = POIDataSamples.GetPublisherInstance();
            FileStream     sample   = _samples.GetFile("Sample.pub");

            DocumentInputStream stream;

            NPOIFSFileSystem npoifs = new NPOIFSFileSystem(sample);

            try
            {
                sample = _samples.GetFile("Sample.pub");
                OPOIFSFileSystem opoifs = new OPOIFSFileSystem(sample);

                // Ensure we have what we expect on the root
                Assert.AreEqual(npoifs, npoifs.Root.NFileSystem);
                Assert.AreEqual(npoifs, npoifs.Root.FileSystem);
                Assert.AreEqual(null, npoifs.Root.OFileSystem);
                Assert.AreEqual(null, opoifs.Root.FileSystem);
                Assert.AreEqual(opoifs, opoifs.Root.OFileSystem);
                Assert.AreEqual(null, opoifs.Root.NFileSystem);

                // Check inside
                foreach (DirectoryNode root in new DirectoryNode[] { opoifs.Root, npoifs.Root })
                {
                    // Top Level
                    Entry top = root.GetEntry("Contents");
                    Assert.AreEqual(true, top.IsDocumentEntry);
                    stream = root.CreateDocumentInputStream(top);
                    stream.Read();

                    // One Level Down
                    DirectoryNode escher = (DirectoryNode)root.GetEntry("Escher");
                    Entry         one    = escher.GetEntry("EscherStm");
                    Assert.AreEqual(true, one.IsDocumentEntry);
                    stream = escher.CreateDocumentInputStream(one);
                    stream.Read();

                    // Two Levels Down
                    DirectoryNode quill    = (DirectoryNode)root.GetEntry("Quill");
                    DirectoryNode quillSub = (DirectoryNode)quill.GetEntry("QuillSub");
                    Entry         two      = quillSub.GetEntry("CONTENTS");
                    Assert.AreEqual(true, two.IsDocumentEntry);
                    stream = quillSub.CreateDocumentInputStream(two);
                    stream.Read();
                }
            }
            finally
            {
                npoifs.Close();
            }
        }
Пример #28
0
        /**
         * @deprecated use {@link #EncryptionInfo(EncryptionMode, CipherAlgorithm, HashAlgorithm, int, int, ChainingMode)}
         */

        public EncryptionInfo(
            NPOIFSFileSystem fs
            , EncryptionMode encryptionMode
            , CipherAlgorithm cipherAlgorithm
            , HashAlgorithm hashAlgorithm
            , int keyBits
            , int blockSize
            , ChainingMode chainingMode
            )
            : this(encryptionMode, cipherAlgorithm, hashAlgorithm, keyBits, blockSize, chainingMode)
        {
            ;
        }
Пример #29
0
        private void Write(NPOIFSFileSystem fs)
        {
            // For tracking what we've written out, so far
            List <String> excepts = new List <String>(1);

            // Write out our HPFS properties, with any changes
            WriteProperties(fs, excepts);

            // Copy over everything else unchanged
            EntryUtils.CopyNodes(directory, fs.Root, excepts);

            // Caller will save the resultant POIFSFileSystem to the stream/file
        }
Пример #30
0
        public OldExcelExtractor(Stream input)
        {
            BufferedStream bstream = new BufferedStream(input, 8);

            if (NPOIFSFileSystem.HasPOIFSHeader(bstream))
            {
                Open(new NPOIFSFileSystem(bstream));
            }
            else
            {
                Open(bstream);
            }
        }