public void TestSaveToOutputStream() { String originalFile = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCommon.docx"); FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageOpenSaveTMP.docx"); OPCPackage p = OPCPackage.Open(originalFile, PackageAccess.READ_WRITE); FileStream fs = targetFile.OpenWrite(); p.Save(fs); fs.Close(); // Compare the original and newly saved document Assert.IsTrue(File.Exists(targetFile.FullName)); ZipFileAssert.AssertEqual(new FileInfo(originalFile), targetFile); File.Delete(targetFile.FullName); }
/** * TODO: fix and enable */ //[Test] public void disabled_testRemovePartRecursive() { String originalFile = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCommon.docx"); FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageRemovePartRecursiveOUTPUT.docx"); FileInfo tempFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageRemovePartRecursiveTMP.docx"); OPCPackage p = OPCPackage.Open(originalFile, PackageAccess.READ_WRITE); p.RemovePartRecursive(PackagingUriHelper.CreatePartName(new Uri( "/word/document.xml", UriKind.Relative))); p.Save(tempFile.FullName); // Compare the original and newly saved document Assert.IsTrue(File.Exists(targetFile.FullName)); ZipFileAssert.AssertEqual(targetFile, tempFile); File.Delete(targetFile.FullName); }
public void TestCreatePackageAddPart() { FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestCreatePackageTMP.docx"); FileInfo expectedFile = OpenXml4NetTestDataSamples.GetSampleFile("TestCreatePackageOUTPUT.docx"); // Zap the target file, in case of an earlier run if (targetFile.Exists) { targetFile.Delete(); } // Create a namespace OPCPackage pkg = OPCPackage.Create(targetFile.FullName); PackagePartName corePartName = PackagingUriHelper .CreatePartName("/word/document.xml"); pkg.AddRelationship(corePartName, TargetMode.Internal, PackageRelationshipTypes.CORE_DOCUMENT, "rId1"); PackagePart corePart = pkg .CreatePart( corePartName, "application/vnd.openxmlformats-officedocument.wordProcessingml.document.main+xml"); //Document doc = DocumentHelper.CreateDocument(); //Namespace nsWordProcessinML = new Namespace("w", // "http://schemas.openxmlformats.org/wordProcessingml/2006/main"); //Element elDocument = doc.AddElement(new QName("document", // nsWordProcessinML)); //Element elBody = elDocument.AddElement(new QName("body", // nsWordProcessinML)); //Element elParagraph = elBody.AddElement(new QName("p", // nsWordProcessinML)); //Element elRun = elParagraph // .AddElement(new QName("r", nsWordProcessinML)); //Element elText = elRun.AddElement(new QName("t", nsWordProcessinML)); //elText.SetText("Hello Open XML !"); //StreamHelper.SaveXmlInStream(doc, corePart.GetOutputStream()); //pkg.Close(); //ZipFileAssert.AssertEqual(expectedFile, targetFile); //File.Delete(targetFile.FullName); }
public void TestSetProperties() { String inputPath = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageThumbnail.docx"); String imagePath = OpenXml4NetTestDataSamples.GetSampleFileName("thumbnail.jpg"); FileInfo outputFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageThumbnailOUTPUT.docx"); // Open namespace using (Stream inputfile = File.OpenRead(inputPath)) { OPCPackage p = OPCPackage.Open(inputfile); try { using (FileStream fs = outputFile.OpenWrite()) { p.AddThumbnail(imagePath); // Save the namespace in the output directory p.Save(fs); p.Close(); } // Open the newly created file to check core properties saved values. OPCPackage p2 = OPCPackage.Open(outputFile.FullName, PackageAccess.READ); try { if (p2.GetRelationshipsByType(PackageRelationshipTypes.THUMBNAIL) .Size == 0) { Assert.Fail("Thumbnail not added to the namespace !"); } p2.Revert(); } finally { p2.Revert(); p2.Close(); } } finally { File.Delete(outputFile.Name); } } }
public void TestGetPropertiesLO() { // Open the namespace OPCPackage pkg1 = OPCPackage.Open(OpenXml4NetTestDataSamples.OpenSampleStream("51444.xlsx")); PackageProperties props1 = pkg1.GetPackageProperties(); Assert.AreEqual(null, props1.GetTitleProperty()); props1.SetTitleProperty("Bug 51444 fixed"); MemoryStream out1 = new MemoryStream(); pkg1.Save(out1); out1.Close(); OPCPackage pkg2 = OPCPackage.Open(new MemoryStream(out1.ToArray())); PackageProperties props2 = pkg2.GetPackageProperties(); props2.SetTitleProperty("Bug 51444 fixed"); }
public void TestTargetWithSpecialChars() { OPCPackage pkg; String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("50154.xlsx"); pkg = OPCPackage.Open(filepath); Assert_50154(pkg); MemoryStream baos = new MemoryStream(); pkg.Save(baos); MemoryStream bais = new MemoryStream(baos.ToArray()); pkg = OPCPackage.Open(bais); Assert_50154(pkg); }
private static String ExtractInvalidFormatMessage(String sampleNameSuffix) { Stream is1 = OpenXml4NetTestDataSamples.OpenComplianceSampleStream("OPCCompliance_CoreProperties_" + sampleNameSuffix); OPCPackage pkg; try { pkg = OPCPackage.Open(is1); } catch (InvalidFormatException e) { // no longer required for successful test return(e.Message); } pkg.Revert(); throw new AssertionException("expected OPC compliance exception was not thrown"); }
public void TestSetProperties() { String inputPath = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCoreProperiesSetters.docx"); FileInfo outputFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); // Open namespace OPCPackage p = OPCPackage.Open(inputPath, PackageAccess.READ_WRITE); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); DateTime dateToInsert = DateTime.Parse("2007-05-12T08:00:00Z").ToUniversalTime(); PackageProperties props = p.GetPackageProperties(); props.SetCategoryProperty("MyCategory"); props.SetContentStatusProperty("MyContentStatus"); props.SetContentTypeProperty("MyContentType"); props.SetCreatedProperty(new DateTime?(dateToInsert)); props.SetCreatorProperty("MyCreator"); props.SetDescriptionProperty("MyDescription"); props.SetIdentifierProperty("MyIdentifier"); props.SetKeywordsProperty("MyKeywords"); props.SetLanguageProperty("MyLanguage"); props.SetLastModifiedByProperty("Julien Chable"); props.SetLastPrintedProperty(new Nullable <DateTime>(dateToInsert)); props.SetModifiedProperty(new Nullable <DateTime>(dateToInsert)); props.SetRevisionProperty("2"); props.SetTitleProperty("MyTitle"); props.SetSubjectProperty("MySubject"); props.SetVersionProperty("2"); FileStream fs = outputFile.OpenWrite(); // Save the namespace in the output directory p.Save(fs); fs.Close(); // Open the newly Created file to check core properties saved values. OPCPackage p2 = OPCPackage.Open(outputFile.Name, PackageAccess.READ); CompareProperties(p2); p2.Revert(); File.Delete(outputFile.Name); }
public void TestReplaceContentType() { Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("sample.xlsx"); OPCPackage p = OPCPackage.Open(is1); ContentTypeManager mgr = GetContentTypeManager(p); Assert.True(mgr.IsContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml")); Assert.False(mgr.IsContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml")); Assert.True( p.ReplaceContentType( "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", "application/vnd.ms-excel.sheet.macroEnabled.main+xml") ); Assert.False(mgr.IsContentTypeRegister("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml")); Assert.True(mgr.IsContentTypeRegister("application/vnd.ms-excel.sheet.macroEnabled.main+xml")); }
public void TestOpenFileThenSaveDelete() { string tempFile = TempFile.GetTempFilePath("poiTesting", "tmp"); string tempFile2 = TempFile.GetTempFilePath("poiTesting", "tmp"); FileInfo origFile = OpenXml4NetTestDataSamples.GetSampleFile("TestPackageCommon.docx"); FileHelper.CopyFile(origFile.FullName, tempFile); // Open the temp file OPCPackage p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE); // Save it to a different file p.Save(tempFile2); p.Close(); // Delete both the files File.Delete(tempFile); File.Delete(tempFile2); }
public void TestOpenSave() { string originalFile = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCommon.docx"); FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageOpenSaveTMP.docx"); OPCPackage p = OPCPackage.Open(originalFile, PackageAccess.READ_WRITE); try { p.Save(targetFile.FullName); // Compare the original and newly saved document Assert.IsTrue(File.Exists(targetFile.FullName)); ZipFileAssert.AssertEqual(new FileInfo(originalFile), targetFile); File.Delete(targetFile.FullName); } finally { // use revert to not re-write the input file p.Revert(); } }
public void TestLoadRelationships() { Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("sample.xlsx"); OPCPackage pkg = OPCPackage.Open(is1); logger.Log(POILogger.DEBUG, "1: " + pkg); PackageRelationshipCollection rels = pkg.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT); PackageRelationship coreDocRelationship = rels.GetRelationship(0); PackagePart corePart = pkg.GetPart(coreDocRelationship); String[] relIds = { "rId1", "rId2", "rId3" }; foreach (String relId in relIds) { PackageRelationship rel = corePart.GetRelationship(relId); Assert.IsNotNull(rel); PackagePartName relName = PackagingUriHelper.CreatePartName(rel.TargetUri); PackagePart sheetPart = pkg.GetPart(relName); Assert.AreEqual(1, sheetPart.Relationships.Size, "Number of relationships1 for " + sheetPart.PartName); } }
public void TestDeletePartRecursive() { Dictionary <PackagePartName, String> expectedValues; Dictionary <PackagePartName, String> values; values = new Dictionary <PackagePartName, String>(); // Expected values expectedValues = new Dictionary <PackagePartName, String>(); expectedValues.Add(PackagingUriHelper.CreatePartName("/_rels/.rels"), "application/vnd.openxmlformats-package.relationships+xml"); expectedValues .Add(PackagingUriHelper.CreatePartName("/docProps/app.xml"), "application/vnd.openxmlformats-officedocument.extended-properties+xml"); expectedValues.Add(PackagingUriHelper .CreatePartName("/docProps/core.xml"), "application/vnd.openxmlformats-package.core-properties+xml"); String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("sample.docx"); OPCPackage p = OPCPackage.Open(filepath, PackageAccess.READ_WRITE); // Remove the core part p.DeletePartRecursive(PackagingUriHelper.CreatePartName("/word/document.xml")); foreach (PackagePart part in p.GetParts()) { values.Add(part.PartName, part.ContentType); logger.Log(POILogger.DEBUG, part.PartName); } // Compare expected values with values return by the namespace foreach (PackagePartName partName in expectedValues.Keys) { Assert.IsNotNull(values[partName]); Assert.AreEqual(expectedValues[partName], values[partName]); } // Don't save modifications p.Revert(); }
public void TestListParts1() { Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("sample.docx"); OPCPackage p; p = OPCPackage.Open(is1); foreach (PackagePart part in p.GetParts()) { values.Add(part.PartName, part.ContentType); logger.Log(POILogger.DEBUG, part.PartName); } // Compare expected values with values return by the namespace foreach (PackagePartName partName in expectedValues.Keys) { Assert.IsNotNull(values[partName]); Assert.AreEqual(expectedValues[partName], values[partName]); } }
public void TestGetPartsByName() { String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("sample.docx"); OPCPackage pkg = OPCPackage.Open(filepath, PackageAccess.READ_WRITE); List <PackagePart> rs = pkg.GetPartsByName(new Regex("^/word/.*?\\.xml$")); Dictionary <String, PackagePart> selected = new Dictionary <String, PackagePart>(); foreach (PackagePart p in rs) { selected.Add(p.PartName.Name, p); } Assert.AreEqual(6, selected.Count); Assert.IsTrue(selected.ContainsKey("/word/document.xml")); Assert.IsTrue(selected.ContainsKey("/word/fontTable.xml")); Assert.IsTrue(selected.ContainsKey("/word/settings.xml")); Assert.IsTrue(selected.ContainsKey("/word/styles.xml")); Assert.IsTrue(selected.ContainsKey("/word/theme/theme1.xml")); Assert.IsTrue(selected.ContainsKey("/word/webSettings.xml")); }
public void TestOpenFileThenSaveDelete() { string tempFile = TempFile.GetTempFilePath("poiTesting", "tmp"); string tempFile2 = TempFile.GetTempFilePath("poiTesting", "tmp"); FileInfo origFile = OpenXml4NetTestDataSamples.GetSampleFile("TestPackageCommon.docx"); FileHelper.CopyFile(origFile.FullName, tempFile); // Open the temp file OPCPackage p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE); // Save it to a different file p.Save(tempFile2); p.Close(); // Delete both the files File.Delete(tempFile); File.Delete(tempFile2); Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files."); }
public void TestGetPartSize() { String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("sample.docx"); OPCPackage pkg = OPCPackage.Open(filepath, PackageAccess.READ); try { int checked1 = 0; foreach (PackagePart part in pkg.GetParts()) { // Can get the size of zip parts if (part.PartName.Name.Equals("/word/document.xml")) { checked1++; Assert.AreEqual(typeof(ZipPackagePart), part.GetType()); Assert.AreEqual(6031L, part.Size); } if (part.PartName.Name.Equals("/word/fontTable.xml")) { checked1++; Assert.AreEqual(typeof(ZipPackagePart), part.GetType()); Assert.AreEqual(1312L, part.Size); } // But not from the others if (part.PartName.Name.Equals("/docProps/core.xml")) { checked1++; Assert.AreEqual(typeof(PackagePropertiesPart), part.GetType()); Assert.AreEqual(-1, part.Size); } } // Ensure we actually found the parts we want to check Assert.AreEqual(3, checked1); } finally { pkg.Revert(); } }
public void TestOpenFileThenOverWrite() { string tempFile = TempFile.GetTempFilePath("poiTesting", "tmp"); FileInfo origFile = OpenXml4NetTestDataSamples.GetSampleFile("TestPackageCommon.docx"); FileHelper.CopyFile(origFile.FullName, tempFile); // Open the temp file OPCPackage p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE); // Close it p.Close(); // Delete it File.Delete(tempFile); // Reset FileHelper.CopyFile(origFile.FullName, tempFile); p = OPCPackage.Open(tempFile, PackageAccess.READ_WRITE); // Save it to the same file - not allowed try { p.Save(tempFile); Assert.Fail("You shouldn't be able to call save(File) to overwrite the current file"); } catch (IOException) { } p.Close(); // Delete it File.Delete(tempFile); // Open it read only, then close and delete - allowed FileHelper.CopyFile(origFile.FullName, tempFile); p = OPCPackage.Open(tempFile, PackageAccess.READ); p.Close(); File.Delete(tempFile); Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files."); }
public void TestFetchFromCollection() { Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("ExcelWithHyperlinks.xlsx"); OPCPackage pkg = OPCPackage.Open(is1); PackagePart sheet = pkg.GetPart( PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS)); Assert.IsNotNull(sheet); Assert.IsTrue(sheet.HasRelationships); Assert.AreEqual(6, sheet.Relationships.Size); // Should have three hyperlinks, and one comment PackageRelationshipCollection hyperlinks = sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE); PackageRelationshipCollection comments = sheet.GetRelationshipsByType(COMMENTS_REL_TYPE); Assert.AreEqual(3, hyperlinks.Size); Assert.AreEqual(1, comments.Size); // Check we can Get bits out by id // Hyperlinks are rId1, rId2 and rId3 // Comment is rId6 Assert.IsNotNull(hyperlinks.GetRelationshipByID("rId1")); Assert.IsNotNull(hyperlinks.GetRelationshipByID("rId2")); Assert.IsNotNull(hyperlinks.GetRelationshipByID("rId3")); Assert.IsNull(hyperlinks.GetRelationshipByID("rId6")); Assert.IsNull(comments.GetRelationshipByID("rId1")); Assert.IsNull(comments.GetRelationshipByID("rId2")); Assert.IsNull(comments.GetRelationshipByID("rId3")); Assert.IsNotNull(comments.GetRelationshipByID("rId6")); Assert.IsNotNull(sheet.GetRelationship("rId1")); Assert.IsNotNull(sheet.GetRelationship("rId2")); Assert.IsNotNull(sheet.GetRelationship("rId3")); Assert.IsNotNull(sheet.GetRelationship("rId6")); }
public void TestOnlyOneCorePropertiesPart() { // We have relaxed this check, so we can read the file anyway try { ExtractInvalidFormatMessage("OnlyOneCorePropertiesPartFAIL.docx"); Assert.Fail("M4.1 should be being relaxed"); } catch (AssertionException e) { } // We will use the first core properties, and ignore the others Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("MultipleCoreProperties.docx"); OPCPackage pkg = OPCPackage.Open(is1); // We can see 2 by type Assert.AreEqual(2, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count); // But only the first one by relationship Assert.AreEqual(1, pkg.GetPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES).Count); // It should be core.xml not the older core1.xml Assert.AreEqual( "/docProps/core.xml", pkg.GetPartsByRelationshipType(PackageRelationshipTypes.CORE_PROPERTIES)[0].PartName.ToString() ); }
public void TestCorruptFile() { OPCPackage pkg = null; FileInfo file = OpenXml4NetTestDataSamples.GetSampleFile("invalid.xlsx"); try { pkg = OPCPackage.Open(file, PackageAccess.READ); } catch (Exception e) { //System.out.println(e.GetClass().getName()); //System.out.println(e.GetMessage()); //e.printStackTrace(); } finally { if (pkg != null) { pkg.Close(); } } }
public void TestEntitiesInCoreProps_56164() { Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("CorePropertiesHasEntities.ooxml"); OPCPackage p = OPCPackage.Open(is1); is1.Close(); // Should have 3 root relationships bool foundDocRel = false, foundCorePropRel = false, foundExtPropRel = false; foreach (PackageRelationship pr in p.Relationships) { if (pr.RelationshipType.Equals(PackageRelationshipTypes.CORE_DOCUMENT)) { foundDocRel = true; } if (pr.RelationshipType.Equals(PackageRelationshipTypes.CORE_PROPERTIES)) { foundCorePropRel = true; } if (pr.RelationshipType.Equals(PackageRelationshipTypes.EXTENDED_PROPERTIES)) { foundExtPropRel = true; } } Assert.IsTrue(foundDocRel, "Core/Doc Relationship not found in " + p.Relationships); Assert.IsTrue(foundCorePropRel, "Core Props Relationship not found in " + p.Relationships); Assert.IsTrue(foundExtPropRel, "Ext Props Relationship not found in " + p.Relationships); // Get the Core Properties PackagePropertiesPart props = (PackagePropertiesPart)p.GetPackageProperties(); // Check Assert.AreEqual("Stefan Kopf", props.GetCreatorProperty()); p.Close(); }
public void TestOnlyOneCorePropertiesPart_AddRelationship() { Stream is1 = OpenXml4NetTestDataSamples.OpenComplianceSampleStream("OPCCompliance_CoreProperties_OnlyOneCorePropertiesPart.docx"); OPCPackage pkg; pkg = OPCPackage.Open(is1); Uri partUri = CreateURI("/docProps/core2.xml"); try { pkg.AddRelationship(PackagingUriHelper.CreatePartName(partUri), TargetMode.Internal, PackageRelationshipTypes.CORE_PROPERTIES); // no longer fail on compliance error //fail("expected OPC compliance exception was not thrown"); } catch (InvalidFormatException e) { throw; } catch (InvalidOperationException e) { // expected during successful test Assert.AreEqual("OPC Compliance error [M4.1]: can't add another core properties part ! Use the built-in package method instead.", e.Message); } pkg.Revert(); }
public void TestTrailingSpacesInURI_53282() { OPCPackage pkg = null; using (Stream stream = OpenXml4NetTestDataSamples.OpenSampleStream("53282.xlsx")) { pkg = OPCPackage.Open(stream); } PackageRelationshipCollection sheetRels = pkg.GetPartsByName(new Regex("/xl/worksheets/sheet1.xml"))[0].Relationships; Assert.AreEqual(3, sheetRels.Size); PackageRelationship rId1 = sheetRels.GetRelationshipByID("rId1"); Assert.AreEqual(TargetMode.External, rId1.TargetMode); Uri targetUri = rId1.TargetUri; Assert.AreEqual("mailto:[email protected]%C2%A0", targetUri.OriginalString); //Assert.AreEqual("[email protected]\u00A0", targetUri.OriginalString); Console.WriteLine("how to get string \"[email protected]\\u00A0\""); MemoryStream out1 = new MemoryStream(); pkg.Save(out1); pkg = OPCPackage.Open(new ByteArrayInputStream(out1.ToArray())); out1.Close(); sheetRels = pkg.GetPartsByName(new Regex("/xl/worksheets/sheet1.xml"))[(0)].Relationships; Assert.AreEqual(3, sheetRels.Size); rId1 = sheetRels.GetRelationshipByID("rId1"); Assert.AreEqual(TargetMode.External, rId1.TargetMode); targetUri = rId1.TargetUri; Assert.AreEqual("mailto:[email protected]%C2%A0", targetUri.OriginalString); //Assert.AreEqual("[email protected]\u00A0", targetUri.Scheme); }
public void UnparseableCentralDirectory() { FileInfo f = OpenXml4NetTestDataSamples.GetSampleFile("at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx"); //SlideShow<?,?> ppt = SlideShowFactory.create(f, null, true); //ppt.close(); }
public void TestCreateExcelHyperlinkRelations() { String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("ExcelWithHyperlinks.xlsx"); OPCPackage pkg = OPCPackage.Open(filepath, PackageAccess.READ_WRITE); PackagePart sheet = pkg.GetPart( PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS)); Assert.IsNotNull(sheet); Assert.AreEqual(3, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size); // Add three new ones PackageRelationship openxml4j = sheet.AddExternalRelationship("http://www.Openxml4j.org/", HYPERLINK_REL_TYPE); PackageRelationship sf = sheet.AddExternalRelationship("http://openxml4j.sf.net/", HYPERLINK_REL_TYPE); PackageRelationship file = sheet.AddExternalRelationship("MyDocument.docx", HYPERLINK_REL_TYPE); // Check they were Added properly Assert.IsNotNull(openxml4j); Assert.IsNotNull(sf); Assert.IsNotNull(file); Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size); Assert.AreEqual("http://www.openxml4j.org/", openxml4j.TargetUri.ToString()); Assert.AreEqual("/xl/worksheets/sheet1.xml", openxml4j.SourceUri.ToString()); Assert.AreEqual(HYPERLINK_REL_TYPE, openxml4j.RelationshipType); Assert.AreEqual("http://openxml4j.sf.net/", sf.TargetUri.ToString()); Assert.AreEqual("/xl/worksheets/sheet1.xml", sf.SourceUri.ToString()); Assert.AreEqual(HYPERLINK_REL_TYPE, sf.RelationshipType); Assert.AreEqual("MyDocument.docx", file.TargetUri.ToString()); Assert.AreEqual("/xl/worksheets/sheet1.xml", file.SourceUri.ToString()); Assert.AreEqual(HYPERLINK_REL_TYPE, file.RelationshipType); // Will Get ids 7, 8 and 9, as we already have 1-6 Assert.AreEqual("rId7", openxml4j.Id); Assert.AreEqual("rId8", sf.Id); Assert.AreEqual("rId9", file.Id); // Write out and re-load MemoryStream baos = new MemoryStream(); pkg.Save(baos); MemoryStream bais = new MemoryStream(baos.ToArray()); pkg = OPCPackage.Open(bais); // use revert to not re-write the input file pkg.Revert(); // Check again sheet = pkg.GetPart( PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS)); Assert.AreEqual(6, sheet.GetRelationshipsByType(HYPERLINK_REL_TYPE).Size); Assert.AreEqual("http://poi.apache.org/", sheet.GetRelationship("rId1").TargetUri.ToString()); Assert.AreEqual("mailto:[email protected]?subject=XSSF Hyperlinks", sheet.GetRelationship("rId3").TargetUri.ToString()); Assert.AreEqual("http://www.openxml4j.org/", sheet.GetRelationship("rId7").TargetUri.ToString()); Assert.AreEqual("http://openxml4j.sf.net/", sheet.GetRelationship("rId8").TargetUri.ToString()); Assert.AreEqual("MyDocument.docx", sheet.GetRelationship("rId9").TargetUri.ToString()); }
public void TestFileWithContentTypeParams() { Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("ContentTypeHasParameters.ooxml"); OPCPackage p = OPCPackage.Open(is1); String typeResqml = "application/x-resqml+xml"; // Check the types on everything foreach (PackagePart part in p.GetParts()) { // _rels type doesn't have any params if (part.IsRelationshipPart) { Assert.AreEqual(ContentTypes.RELATIONSHIPS_PART, part.ContentType); Assert.AreEqual(ContentTypes.RELATIONSHIPS_PART, part.ContentTypeDetails.ToString()); Assert.AreEqual(false, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(0, part.ContentTypeDetails.GetParameterKeys().Length); } // Core type doesn't have any params else if (part.PartName.ToString().Equals("/docProps/core.xml")) { Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentType); Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentTypeDetails.ToString()); Assert.AreEqual(false, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(0, part.ContentTypeDetails.GetParameterKeys().Length); } // Global Crs types do have params else if (part.PartName.ToString().Equals("/global1dCrs.xml")) { Assert.AreEqual(typeResqml, part.ContentType.Substring(0, typeResqml.Length)); Assert.AreEqual(typeResqml, part.ContentTypeDetails.ToString(false)); Assert.AreEqual(true, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(typeResqml + ";version=2.0;type=obj_global1dCrs", part.ContentTypeDetails.ToString()); Assert.AreEqual(2, part.ContentTypeDetails.GetParameterKeys().Length); Assert.AreEqual("2.0", part.ContentTypeDetails.GetParameter("version")); Assert.AreEqual("obj_global1dCrs", part.ContentTypeDetails.GetParameter("type")); } else if (part.PartName.ToString().Equals("/global2dCrs.xml")) { Assert.AreEqual(typeResqml, part.ContentType.Substring(0, typeResqml.Length)); Assert.AreEqual(typeResqml, part.ContentTypeDetails.ToString(false)); Assert.AreEqual(true, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(typeResqml + ";version=2.0;type=obj_global2dCrs", part.ContentTypeDetails.ToString()); Assert.AreEqual(2, part.ContentTypeDetails.GetParameterKeys().Length); Assert.AreEqual("2.0", part.ContentTypeDetails.GetParameter("version")); Assert.AreEqual("obj_global2dCrs", part.ContentTypeDetails.GetParameter("type")); } // Other thingy else if (part.PartName.ToString().Equals("/myTestingGuid.xml")) { Assert.AreEqual(typeResqml, part.ContentType.Substring(0, typeResqml.Length)); Assert.AreEqual(typeResqml, part.ContentTypeDetails.ToString(false)); Assert.AreEqual(true, part.ContentTypeDetails.HasParameters()); Assert.AreEqual(typeResqml + ";version=2.0;type=obj_tectonicBoundaryFeature", part.ContentTypeDetails.ToString()); Assert.AreEqual(2, part.ContentTypeDetails.GetParameterKeys().Length); Assert.AreEqual("2.0", part.ContentTypeDetails.GetParameter("version")); Assert.AreEqual("obj_tectonicBoundaryFeature", part.ContentTypeDetails.GetParameter("type")); } // That should be it! else { Assert.Fail("Unexpected part " + part); } } }
public void ZipBombCreateAndHandle() { // #50090 / #56865 ZipFile zipFile = ZipHelper.OpenZipFile(OpenXml4NetTestDataSamples.GetSampleFile("sample.xlsx")); Assert.IsNotNull(zipFile); ByteArrayOutputStream bos = new ByteArrayOutputStream(2500000); ZipOutputStream append = new ZipOutputStream(bos); // first, copy contents from existing war IEnumerator entries = zipFile.GetEnumerator(); while (entries.MoveNext()) { ZipEntry e2 = (ZipEntry)entries.Current; ZipEntry e = new ZipEntry(e2.Name); e.DateTime = (e2.DateTime); e.Comment = (e2.Comment); e.Size = (e2.Size); append.PutNextEntry(e); if (!e.IsDirectory) { Stream is1 = zipFile.GetInputStream(e); if (e.Name.Equals("[Content_Types].xml")) { ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); IOUtils.Copy(is1, bos2); long size = bos2.Length - "</Types>".Length; append.Write(bos2.ToByteArray(), 0, (int)size); byte[] spam = new byte[0x7FFF]; for (int i = 0; i < spam.Length; i++) { spam[i] = (byte)' '; } // 0x7FFF0000 is the maximum for 32-bit zips, but less still works while (size < 0x7FFF0000) { append.Write(spam, 0, spam.Length); size += spam.Length; } append.Write(Encoding.ASCII.GetBytes("</Types>"), 0, 8); size += 8; e.Size = (size); } else { IOUtils.Copy(is1, append); } } append.CloseEntry(); } append.Close(); zipFile.Close(); byte[] buf = bos.ToByteArray(); bos = null; IWorkbook wb = WorkbookFactory.Create(new ByteArrayInputStream(buf)); wb.GetSheetAt(0); wb.Close(); zipFile.Close(); }
public void TestSetProperties() { String inputPath = OpenXml4NetTestDataSamples.GetSampleFileName("TestPackageCoreProperiesSetters.docx"); FileInfo outputFile = OpenXml4NetTestDataSamples.GetOutputFile("TestPackageCoreProperiesSettersOUTPUT.docx"); // Open namespace OPCPackage p = OPCPackage.Open(inputPath, PackageAccess.READ_WRITE); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); df.TimeZone = TimeZoneInfo.Utc; DateTime dateToInsert = df.Parse("2007-05-12T08:00:00Z"); SimpleDateFormat msdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"); msdf.TimeZone = TimeZoneInfo.Utc; PackageProperties props = p.GetPackageProperties(); //test various date formats props.SetCreatedProperty("2007-05-12T08:00:00Z"); Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T08:00:00"); //no Z, assume Z Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T08:00:00.123Z");//millis Assert.AreEqual(msdf.Parse("2007-05-12T08:00:00.123Z"), props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T10:00:00+0200"); Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T10:00:00+02:00");//colon in tz Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T06:00:00-0200"); Assert.AreEqual(dateToInsert, props.GetCreatedProperty().Value); props.SetCreatedProperty("2007-05-12T10:00:00.123+0200"); Assert.AreEqual(msdf.Parse("2007-05-12T08:00:00.123Z"), props.GetCreatedProperty().Value); props.SetCategoryProperty("MyCategory"); props.SetCategoryProperty("MyCategory"); props.SetContentStatusProperty("MyContentStatus"); props.SetContentTypeProperty("MyContentType"); //props.SetCreatedProperty(new DateTime?(dateToInsert)); props.SetCreatorProperty("MyCreator"); props.SetDescriptionProperty("MyDescription"); props.SetIdentifierProperty("MyIdentifier"); props.SetKeywordsProperty("MyKeywords"); props.SetLanguageProperty("MyLanguage"); props.SetLastModifiedByProperty("Julien Chable"); props.SetLastPrintedProperty(new Nullable <DateTime>(dateToInsert)); props.SetModifiedProperty(new Nullable <DateTime>(dateToInsert)); props.SetRevisionProperty("2"); props.SetTitleProperty("MyTitle"); props.SetSubjectProperty("MySubject"); props.SetVersionProperty("2"); // Save the package in the output directory p.Save(outputFile.FullName); p.Revert(); // Open the newly Created file to check core properties saved values. OPCPackage p2 = OPCPackage.Open(outputFile.FullName, PackageAccess.READ); CompareProperties(p2); p2.Revert(); outputFile.Delete(); }
public void TestOpenPackage() { FileInfo targetFile = OpenXml4NetTestDataSamples.GetOutputFile("TestOpenPackageTMP.docx"); FileInfo inputFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageINPUT.docx"); FileInfo expectedFile = OpenXml4NetTestDataSamples.GetSampleFile("TestOpenPackageOUTPUT.docx"); // Copy the input file in the output directory FileHelper.CopyFile(inputFile.FullName, targetFile.FullName); // Create a namespace OPCPackage pkg = OPCPackage.Open(targetFile.FullName); // Modify core part PackagePartName corePartName = PackagingUriHelper .CreatePartName("/word/document.xml"); PackagePart corePart = pkg.GetPart(corePartName); // Delete some part to have a valid document foreach (PackageRelationship rel in corePart.Relationships) { corePart.RemoveRelationship(rel.Id); pkg.RemovePart(PackagingUriHelper.CreatePartName(PackagingUriHelper .ResolvePartUri(corePart.PartName.URI, rel .TargetUri))); } // Create a content XmlDocument doc = new XmlDocument(); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); string wuri = "http://schemas.openxmlformats.org/wordProcessingml/2006/main"; mgr.AddNamespace("w", wuri); XmlElement elDocument = doc.CreateElement("w:document", wuri); doc.AppendChild(elDocument); XmlElement elBody = doc.CreateElement("w:body", wuri); elDocument.AppendChild(elBody); XmlElement elParagraph = doc.CreateElement("w:p", wuri); elBody.AppendChild(elParagraph); XmlElement elRun = doc.CreateElement("w:r", wuri); elParagraph.AppendChild(elRun); XmlElement elText = doc.CreateElement("w:t", wuri); elRun.AppendChild(elText); elText.InnerText = ("Hello Open XML !"); StreamHelper.SaveXmlInStream(doc, corePart.GetOutputStream()); // Save and close try { pkg.Close(); } catch (IOException) { Assert.Fail(); } ZipFileAssert.AssertEqual(expectedFile, targetFile); File.Delete(targetFile.FullName); Assert.AreEqual(0, Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.tmp").Length, "At Last: There are no temporary files."); }