Ejemplo n.º 1
0
        internal static CardDef LoadFromXml(XElement xml, PackagePart part)
        {
            var backUri = xml.Attr <string>("back");

            if (backUri != null)
            {
                backUri = part.GetRelationship(backUri).TargetUri.OriginalString;
            }

            var frontUri = xml.Attr <string>("front");

            if (frontUri != null)
            {
                frontUri = part.GetRelationship(frontUri).TargetUri.OriginalString;
            }

            return(new CardDef
            {
                back = backUri,
                front = frontUri,
                Width = xml.Attr <int>("width"),
                Height = xml.Attr <int>("height"),
                CornerRadius = xml.Attr <int>("cornerRadius"),
                Properties = xml.Elements(Defs.XmlnsOctgn + "property")
                             .Select(PropertyDef.LoadFromXml)
                             .ToDictionary(x => x.Name)
            });
        }
Ejemplo n.º 2
0
Archivo: Set.cs Proyecto: wlk0/OCTGN
        public void ExtractImages()
        {
            PackageRelationship defRelationship = Package.GetRelationshipsByType("http://schemas.octgn.org/set/definition").First();
            PackagePart         definition      = Package.GetPart(defRelationship.TargetUri);
            XmlNodeList         cards           = Doc.GetElementsByTagName("card");
            var    markers    = Doc.GetElementsByTagName("marker");
            string extractDir = Path.Combine(UnpackBase, "SetImages", GameId.ToString(), "Sets", Id.ToString(), "Cards");

            foreach (XmlNode card in cards)
            {
                Guid        cardID    = new Guid(card.Attributes["id"].Value);
                Uri         cardImage = definition.GetRelationship("C" + cardID.ToString("N")).TargetUri;
                string      imageUri  = cardImage.ToString();
                string      fileName  = cardID.ToString() + imageUri.Substring(imageUri.LastIndexOf('.'));
                PackagePart part      = Package.GetPart(cardImage);
                ExtractPart(part, extractDir, fileName);
            }
            extractDir = Path.Combine(UnpackBase, "SetImages", GameId.ToString(), "Sets", Id.ToString(), "Markers");
            foreach (XmlNode marker in markers)
            {
                var         id        = new Guid(marker.Attributes["id"].Value);
                Uri         cardImage = definition.GetRelationship("M" + id.ToString("N")).TargetUri;
                string      imageUri  = cardImage.ToString();
                string      fileName  = id.ToString() + imageUri.Substring(imageUri.LastIndexOf('.'));
                PackagePart part      = Package.GetPart(cardImage);
                ExtractPart(part, extractDir, fileName);
            }
        }
Ejemplo n.º 3
0
        public void TestLoadExcelHyperlinkRelations()
        {
            Stream      is1   = OpenXml4NetTestDataSamples.OpenSampleStream("ExcelWithHyperlinks.xlsx");
            OPCPackage  pkg   = OPCPackage.Open(is1);
            PackagePart sheet = pkg.GetPart(
                PackagingUriHelper.CreatePartName(SHEET_WITH_COMMENTS));

            Assert.IsNotNull(sheet);

            // rId1 is url
            PackageRelationship url = sheet.GetRelationship("rId1");

            Assert.IsNotNull(url);
            Assert.AreEqual("rId1", url.Id);
            Assert.AreEqual("/xl/worksheets/sheet1.xml", url.SourceUri.ToString());
            Assert.AreEqual("http://poi.apache.org/", url.TargetUri.ToString());

            // rId2 is file
            PackageRelationship file = sheet.GetRelationship("rId2");

            Assert.IsNotNull(file);
            Assert.AreEqual("rId2", file.Id);
            Assert.AreEqual("/xl/worksheets/sheet1.xml", file.SourceUri.ToString());
            Assert.AreEqual("WithVariousData.xlsx", file.TargetUri.ToString());

            // rId3 is mailto
            PackageRelationship mailto = sheet.GetRelationship("rId3");

            Assert.IsNotNull(mailto);
            Assert.AreEqual("rId3", mailto.Id);
            Assert.AreEqual("/xl/worksheets/sheet1.xml", mailto.SourceUri.ToString());
            Assert.AreEqual("mailto:[email protected]?subject=XSSF%20Hyperlinks", mailto.TargetUri.AbsoluteUri);
        }
        public void RemoveImage(string id)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            if (id.Length == 0)
            {
                return;
            }

            if (!_part.RelationshipExists(id))
            {
                return;
            }

            PackageRelationship imageRel = _part.GetRelationship(id);

            Uri imageUri = PackUriHelper.ResolvePartUri(imageRel.SourceUri, imageRel.TargetUri);

            if (_part.Package.PartExists(imageUri))
            {
                _part.Package.DeletePart(imageUri);
            }

            _part.DeleteRelationship(id);
        }
Ejemplo n.º 5
0
        internal static GroupDef LoadFromXml(XElement xml, PackagePart part, int index)
        {
            var bg = xml.Attr <string>("background");

            if (bg != null)
            {
                bg = part.GetRelationship(bg).TargetUri.OriginalString;
            }

            var board = xml.Attr <string>("board");

            if (board != null)
            {
                board = part.GetRelationship(board).TargetUri.OriginalString;
            }

            var icon = xml.Attr <string>("icon");

            if (icon != null)
            {
                icon = part.GetRelationship(icon).TargetUri.OriginalString;
            }

            return(new GroupDef
            {
                Id = (byte)index,
                Name = xml.Attr <string>("name"),
                icon = icon,
                Shortcut = xml.Attr <string>("shortcut"),
                background = bg,
                BackgroundStyle = xml.Attr <string>("backgroundStyle"),
                board = board,
                BoardPosition = xml.Attr <Rect>("boardPosition"),
                Visibility = xml.Attr <GroupVisibility>("visibility"),
                Width = xml.Attr <int>("width"),
                Height = xml.Attr <int>("height"),
                Ordered = xml.Attr("ordered", true),
                Collapsed = xml.Attr <bool>("collapsed"),
                CardActions = xml.Elements()
                              .Where(
                    x =>
                    x.Name == Defs.XmlnsOctgn + "cardaction" || x.Name == Defs.XmlnsOctgn + "cardactions")
                              .Select(BaseActionDef.LoadFromXml)
                              .ToArray(),
                GroupActions = xml.Elements()
                               .Where(
                    x =>
                    x.Name == Defs.XmlnsOctgn + "groupaction" ||
                    x.Name == Defs.XmlnsOctgn + "groupactions")
                               .Select(BaseActionDef.LoadFromXml)
                               .ToArray()
            });
        }
Ejemplo n.º 6
0
        public void TestCreateRelationsFromScratch()
        {
            MemoryStream baos = new MemoryStream();
            OPCPackage   pkg  = OPCPackage.Create(baos);

            PackagePart partA =
                pkg.CreatePart(PackagingUriHelper.CreatePartName("/partA"), "text/plain");
            PackagePart partB =
                pkg.CreatePart(PackagingUriHelper.CreatePartName("/partB"), "image/png");

            Assert.IsNotNull(partA);
            Assert.IsNotNull(partB);

            // Internal
            partA.AddRelationship(partB.PartName, TargetMode.Internal, "http://example/Rel");

            // External
            partA.AddExternalRelationship("http://poi.apache.org/", "http://example/poi");
            partB.AddExternalRelationship("http://poi.apache.org/ss/", "http://example/poi/ss");

            // Check as expected currently
            Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.ToString());
            Assert.AreEqual("http://poi.apache.org/",
                            partA.GetRelationship("rId2").TargetUri.ToString());
            Assert.AreEqual("http://poi.apache.org/ss/",
                            partB.GetRelationship("rId1").TargetUri.ToString());


            // Save, and re-load
            pkg.Close();
            MemoryStream bais = new MemoryStream(baos.ToArray());

            pkg = OPCPackage.Open(bais);

            partA = pkg.GetPart(PackagingUriHelper.CreatePartName("/partA"));
            partB = pkg.GetPart(PackagingUriHelper.CreatePartName("/partB"));


            // Check the relations
            Assert.AreEqual(2, partA.Relationships.Size);
            Assert.AreEqual(1, partB.Relationships.Size);

            Assert.AreEqual("/partB", partA.GetRelationship("rId1").TargetUri.OriginalString);
            Assert.AreEqual("http://poi.apache.org/",
                            partA.GetRelationship("rId2").TargetUri.ToString());
            Assert.AreEqual("http://poi.apache.org/ss/",
                            partB.GetRelationship("rId1").TargetUri.ToString());
            // Check core too
            Assert.AreEqual("/docProps/core.xml",
                            pkg.GetRelationshipsByType(
                                "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties").GetRelationship(0).TargetUri.ToString());
        }
Ejemplo n.º 7
0
        public void CheckPartRelationships()
        {
            AddThreeParts();
            Assert.AreEqual(4, package.GetParts().Count(), "#a");
            PackagePart         part = package.GetPart(uris [0]);
            PackageRelationship r1   = part.CreateRelationship(part.Uri, TargetMode.Internal, "self");
            PackageRelationship r2   = package.CreateRelationship(part.Uri, TargetMode.Internal, "fake");
            PackageRelationship r3   = package.CreateRelationship(new Uri("/fake/uri", UriKind.Relative), TargetMode.Internal, "self");

            Assert.AreEqual(6, package.GetParts().Count(), "#b");
            Assert.AreEqual(1, part.GetRelationships().Count(), "#1");
            Assert.AreEqual(1, part.GetRelationshipsByType("self").Count(), "#2");
            Assert.AreEqual(r1, part.GetRelationship(r1.Id), "#3");
            Assert.AreEqual(2, package.GetRelationships().Count(), "#4");
            Assert.AreEqual(1, package.GetRelationshipsByType("self").Count(), "#5");
            Assert.AreEqual(r3, package.GetRelationship(r3.Id), "#6");

            Assert.AreEqual(6, package.GetParts().Count(), "#c");
            Assert.AreEqual(part.Uri, r1.SourceUri, "#7");
            Assert.AreEqual(new Uri("/", UriKind.Relative), r3.SourceUri, "#8");

            PackageRelationship r4 = part.CreateRelationship(uris [2], TargetMode.Internal, "other");

            Assert.AreEqual(part.Uri, r4.SourceUri);

            PackageRelationshipCollection relations = package.GetPart(uris [2]).GetRelationships();

            Assert.AreEqual(0, relations.Count());
            Assert.AreEqual(6, package.GetParts().Count(), "#d");
        }
Ejemplo n.º 8
0
        public void RelationshipPartGetRelationships()
        {
            CheckAutomaticParts2();
            PackagePart p = package.GetPart(relationshipUri);

            try
            {
                p.CreateRelationship(uris[0], TargetMode.Internal, "asdas");
                Assert.Fail("This should fail 1");
            }
            catch (InvalidOperationException)
            {
            }

            try
            {
                p.DeleteRelationship("aa");
                Assert.Fail("This should fail 2");
            }
            catch (InvalidOperationException)
            {
            }

            try
            {
                p.GetRelationship("id");
                Assert.Fail("This should fail 3");
            }
            catch (InvalidOperationException)
            {
            }

            try
            {
                p.GetRelationships();
                Assert.Fail("This should fail 4");
            }
            catch (InvalidOperationException)
            {
            }

            try
            {
                p.GetRelationshipsByType("type");
                Assert.Fail("This should fail 5");
            }
            catch (InvalidOperationException)
            {
            }

            try
            {
                p.RelationshipExists("id");
                Assert.Fail("This should fail 6");
            }
            catch (InvalidOperationException)
            {
            }
        }
Ejemplo n.º 9
0
        public static FontDef FromXml(XElement xml, PackagePart part)
        {
            string srcUri = part.GetRelationship(xml.Attr <string>("src")).TargetUri.OriginalString;

            return(new FontDef {
                FileName = srcUri, Size = xml.Attr <int>("size"), Target = xml.Attr <string>("target"), Id = xml.Attr <string>("src")
            });
        }
Ejemplo n.º 10
0
        public void Assert_50154(OPCPackage pkg)
        {
            Uri         drawingUri  = new Uri("/xl/drawings/drawing1.xml", UriKind.Relative);
            PackagePart drawingPart = pkg.GetPart(PackagingUriHelper.CreatePartName(drawingUri));
            PackageRelationshipCollection drawingRels = drawingPart.Relationships;

            Assert.AreEqual(6, drawingRels.Size);

            // expected one image
            Assert.AreEqual(1, drawingPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image").Size);
            // and three hyperlinks
            Assert.AreEqual(5, drawingPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink").Size);

            PackageRelationship rId1 = drawingPart.GetRelationship("rId1");
            Uri parent = drawingPart.PartName.URI;
            Uri rel1   = new Uri(Path.Combine(parent.ToString(), rId1.TargetUri.ToString()), UriKind.Relative);
            Uri rel11  = PackagingUriHelper.RelativizeUri(drawingPart.PartName.URI, rId1.TargetUri);

            Assert.AreEqual("#'Another Sheet'!A1", HttpUtility.UrlDecode(rel1.ToString().Split(new char[] { '/' })[3]));

            PackageRelationship rId2 = drawingPart.GetRelationship("rId2");
            Uri rel2 = PackagingUriHelper.RelativizeUri(drawingPart.PartName.URI, rId2.TargetUri);

            Assert.AreEqual("../media/image1.png", rel2.OriginalString);

            PackageRelationship rId3 = drawingPart.GetRelationship("rId3");
            Uri rel3 = new Uri(Path.Combine(parent.ToString(), rId3.TargetUri.ToString()), UriKind.Relative);

            Assert.AreEqual("#ThirdSheet!A1", rel3.OriginalString.Split(new char[] { '/' })[3]);

            PackageRelationship rId4 = drawingPart.GetRelationship("rId4");
            Uri rel4 = new Uri(Path.Combine(parent.ToString(), rId4.TargetUri.ToString()), UriKind.Relative);

            Assert.AreEqual("#'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A1", HttpUtility.UrlDecode(rel4.OriginalString.Split(new char[] { '/' })[3]));

            //PackageRelationship rId5 = drawingPart.GetRelationship("rId5");
            //Uri rel5 = new Uri(Path.Combine(parent.ToString(), rId5.TargetUri.ToString()), UriKind.Relative);
            //// back slashed have been Replaced with forward
            //Assert.AreEqual("file:///D:/chan-chan.mp3", rel5.ToString());

            //PackageRelationship rId6 = drawingPart.GetRelationship("rId6");
            //Uri rel6 = new Uri(ResolveRelativePath(parent.ToString(), HttpUtility.UrlDecode(rId6.TargetUri.ToString())), UriKind.Relative);
            //Assert.AreEqual("../../../../../../../cygwin/home/yegor/dinom/&&&[access].2010-10-26.log", rel6.OriginalString);
            //Assert.AreEqual("#'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A5", HttpUtility.UrlDecode(rel6.OriginalString.Split(new char[] { '/' })[3]));
        }
        public PackageRelationship GetImageRelationship(string relationshipId)
        {
            if (!PackagePart.RelationshipExists(relationshipId))
            {
                throw new ArgumentOutOfRangeException($"Package relationship ${relationshipId} does not exist", nameof(relationshipId));
            }

            return(PackagePart.GetRelationship(relationshipId));
        }
Ejemplo n.º 12
0
        public static ScriptDef FromXml(XElement xml, PackagePart part)
        {
            string      srcUri     = part.GetRelationship(xml.Attr <string>("src")).TargetUri.OriginalString;
            PackagePart scriptPart = part.Package.GetPart(new Uri(srcUri, UriKind.Relative));

            using (Stream stream = scriptPart.GetStream(FileMode.Open, FileAccess.Read))
                using (var textReader = new StreamReader(stream))
                    return new ScriptDef {
                               Python = textReader.ReadToEnd(), FileName = srcUri
                    };
        }
Ejemplo n.º 13
0
        private static IconDef FromXml(XElement xml, PackagePart part)
        {
            var icon = xml.Attr <string>("icon");

            if (icon != null)
            {
                icon = part.GetRelationship(icon).TargetUri.OriginalString;
            }
            return(new IconDef {
                Icon = icon, Pattern = xml.Attr <string>("pattern")
            });
        }
Ejemplo n.º 14
0
 public PackagePart GetPartById(string id)
 {
     try
     {
         PackagePart corePart = this.CorePart;
         return(corePart.GetRelatedPart(corePart.GetRelationship(id)));
     }
     catch (Exception ex)
     {
         throw new ArgumentException("GetTargetPart exception", ex);
     }
 }
Ejemplo n.º 15
0
        private PackageRelationship GetFooderRelationship(FooderType fooderType, string relationshipId)
        {
            var relationshipType = fooderType == FooderType.Header ? RelationshipTypes.Header : RelationshipTypes.Footer;
            var relationship     = PackagePart.GetRelationship(relationshipId);

            if (relationship.RelationshipType != relationshipType)
            {
                throw new Exception($"Relationship {relationshipId} type does not match {fooderType}");
            }

            return(relationship);
        }
Ejemplo n.º 16
0
        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"));
        }
        void IPersistable.Load(ExcelLoadContext context)
        {
            PackagePart currentSheetPart = context.Package.GetPart(this._WorkSheet.SheetUri);

            if (currentSheetPart.RelationshipExists(this._RelationshipID))
            {
                PackageRelationship rel = currentSheetPart.GetRelationship(this._RelationshipID);
                PictureUri = PackUriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri);

                XElement vmlDrawingPictureXml = context.Package.GetXElementFromUri(PictureUri);
                if (vmlDrawingPictureXml != null)
                {
                    context.Reader.ReadHeaderFooterVmlDrawingPicture(this, vmlDrawingPictureXml);
                }
            }
        }
Ejemplo n.º 18
0
        internal static CounterDef LoadFromXml(XElement xml, PackagePart part, int index)
        {
            var icon = xml.Attr <string>("icon");

            if (icon != null)
            {
                icon = part.GetRelationship(icon).TargetUri.OriginalString;
            }

            return(new CounterDef
            {
                Id = (byte)index,
                Name = xml.Attr <string>("name"),
                Icon = icon,
                Start = xml.Attr <int>("default"),
                Reset = xml.Attr("reset", true)
            });
        }
Ejemplo n.º 19
0
        public void TestExcelWorkbook()
        {
            MemoryStream stream  = new MemoryStream();
            Package      package = CreateSpreadsheet(stream);

            Assert.IsTrue(package.PartExists(new Uri("/xl/workbook.xml", UriKind.Relative)), "#1");
            Assert.IsTrue(package.PartExists(new Uri("/xl/sharedStrings.xml", UriKind.Relative)), "#2");

            package.Close();
            package = Package.Open(new MemoryStream(stream.ToArray()), FileMode.Open);

            PackagePart workbookPart = package.GetPart(new Uri("/xl/workbook.xml", UriKind.Relative));

            Assert.IsTrue(workbookPart.RelationshipExists("rel1"), "#3");

            var r = workbookPart.GetRelationship("rel1");

            Assert.IsFalse(r.TargetUri.IsAbsoluteUri, "#4");
            package.Close();
        }
Ejemplo n.º 20
0
        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);
            }
        }
Ejemplo n.º 21
0
        void IPersistable.Load(ExcelLoadContext context)
        {
            PackagePart currentSheetPart = context.Package.GetPart(this._WorkSheet.SheetUri);

            if (currentSheetPart.RelationshipExists(this.RelationshipID))
            {
                PackageRelationship vmlDrawingRelation = currentSheetPart.GetRelationship(this.RelationshipID);
                this._VmlDrawingsUri = PackUriHelper.ResolvePartUri(vmlDrawingRelation.SourceUri, vmlDrawingRelation.TargetUri);
                XElement vmlDrawingElement = context.Package.GetXElementFromUri(this._VmlDrawingsUri);
                context.Reader.ReadSheetCommentVmlDrawing(this, vmlDrawingElement);

                PackageRelationshipCollection commentParts = currentSheetPart.GetRelationshipsByType(ExcelCommon.Schema_Comment);
                foreach (PackageRelationship commentPartRelationship in commentParts)
                {
                    this._CommentUri = PackUriHelper.ResolvePartUri(commentPartRelationship.SourceUri, commentPartRelationship.TargetUri);
                    PackagePart commentPart = context.Package.GetPart(this._CommentUri);
                    XDocument   commentXml  = XDocument.Load(commentPart.GetStream());

                    context.Reader.ReadSheetComments(this, commentXml.Root);
                }
            }
        }
Ejemplo n.º 22
0
        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());
        }
Ejemplo n.º 23
0
        private static XElement MoveRelatedPartsToDestination(
            PackagePart partOfDeletedContent,
            PackagePart partInNewDocument,
            XElement contentElement)
        {
            List <XElement> elementsToUpdate = contentElement
                                               .Descendants()
                                               .Where(d => d.Attributes().Any(a => ComparisonUnitWord.RelationshipAttributeNames.Contains(a.Name)))
                                               .ToList();

            foreach (XElement element in elementsToUpdate)
            {
                List <XAttribute> attributesToUpdate = element
                                                       .Attributes()
                                                       .Where(a => ComparisonUnitWord.RelationshipAttributeNames.Contains(a.Name))
                                                       .ToList();

                foreach (XAttribute att in attributesToUpdate)
                {
                    var rId = (string)att;

                    PackageRelationship relationshipForDeletedPart = partOfDeletedContent.GetRelationship(rId);

                    Uri targetUri = PackUriHelper
                                    .ResolvePartUri(
                        new Uri(partOfDeletedContent.Uri.ToString(), UriKind.Relative),
                        relationshipForDeletedPart.TargetUri);

                    PackagePart relatedPackagePart = partOfDeletedContent.Package.GetPart(targetUri);
                    string[]    uriSplit           = relatedPackagePart.Uri.ToString().Split('/');
                    string[]    last = uriSplit[uriSplit.Length - 1].Split('.');
                    string      uriString;
                    if (last.Length == 2)
                    {
                        uriString = uriSplit.SkipLast(1).Select(p => p + "/").StringConcatenate() +
                                    "P" + Guid.NewGuid().ToString().Replace("-", "") + "." + last[1];
                    }
                    else
                    {
                        uriString = uriSplit.SkipLast(1).Select(p => p + "/").StringConcatenate() +
                                    "P" + Guid.NewGuid().ToString().Replace("-", "");
                    }

                    Uri uri = relatedPackagePart.Uri.IsAbsoluteUri
                        ? new Uri(uriString, UriKind.Absolute)
                        : new Uri(uriString, UriKind.Relative);

                    PackagePart newPart = partInNewDocument.Package.CreatePart(uri, relatedPackagePart.ContentType);

                    // ReSharper disable once PossibleNullReferenceException
                    using (Stream oldPartStream = relatedPackagePart.GetStream())
                        using (Stream newPartStream = newPart.GetStream())
                        {
                            FileUtils.CopyStream(oldPartStream, newPartStream);
                        }

                    string newRid = "R" + Guid.NewGuid().ToString().Replace("-", "");
                    partInNewDocument.CreateRelationship(newPart.Uri, TargetMode.Internal,
                                                         relationshipForDeletedPart.RelationshipType, newRid);
                    att.Value = newRid;

                    if (newPart.ContentType.EndsWith("xml"))
                    {
                        XDocument newPartXDoc;
                        using (Stream stream = newPart.GetStream())
                        {
                            newPartXDoc = XDocument.Load(stream);
                            MoveRelatedPartsToDestination(relatedPackagePart, newPart, newPartXDoc.Root);
                        }

                        using (Stream stream = newPart.GetStream())
                            newPartXDoc.Save(stream);
                    }
                }
            }

            return(contentElement);
        }
Ejemplo n.º 24
0
        private void Apply(Package package, string localFilename, bool installed)
        {
            using (Package setPkg = Package.Open(localFilename, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
            {
                // Extract information about the target set
                PackageRelationship defRelationship =
                    setPkg.GetRelationshipsByType("http://schemas.octgn.org/set/definition").First();
                PackagePart definition = setPkg.GetPart(defRelationship.TargetUri);
                Set         set;
                using (XmlReader reader = XmlReader.Create(definition.GetStream(), XmlSettings))
                {
                    reader.ReadToFollowing("set"); // <?xml ... ?>
                    set = new Set(localFilename, reader, _game.Repository);
                    // Check if the set game matches the patch
                    if (set.Game != _game)
                    {
                        return;
                    }
                }

                // Check if there is a patch for this set
                string relationId = "S" + set.Id.ToString("N");
                if (!package.RelationshipExists(relationId))
                {
                    return;
                }

                PackagePart patchPart = package.GetPart(package.GetRelationship(relationId).TargetUri);
                XDocument   patchDoc;
                using (Stream stream = patchPart.GetStream())
                    patchDoc = XDocument.Load(stream);

                // Check if the set is at least the required version for patching
                if (set.Version < patchDoc.Root.Attr <Version>("minVersion"))
                {
                    return;
                }
                if (set.Version > patchDoc.Root.Attr <Version>("maxVersion"))
                {
                    return;
                }

                if (installed)
                {
                    _game.DeleteSet(_game.Sets.Single(s => s.PackageName == localFilename));
                }

                // Process the set
                if (patchDoc.Root != null)
                {
                    foreach (XElement action in patchDoc.Root.Elements())
                    {
                        switch (action.Name.LocalName)
                        {
                        case "new":
                        {
                            var         targetUri      = new Uri(action.Attr <string>("targetUri"), UriKind.Relative);
                            var         relationshipId = action.Attr <string>("relationshipId");
                            var         contentType    = action.Attr <string>("contentType");
                            PackagePart part           = setPkg.PartExists(targetUri)
                                                           ? setPkg.GetPart(targetUri)
                                                           : setPkg.CreatePart(targetUri, contentType,
                                                                               CompressionOption.Normal);
                            if (part != null)
                            {
                                using (Stream targetStream = part.GetStream(FileMode.Create, FileAccess.Write))
                                    using (
                                        Stream srcStream =
                                            package.GetPart(patchPart.GetRelationship(relationshipId).TargetUri).
                                            GetStream())
                                        srcStream.CopyTo(targetStream);
                            }
                            break;
                        }

                        case "newrel":
                        {
                            var partUri          = new Uri(action.Attr <string>("partUri"), UriKind.Relative);
                            var relationshipId   = action.Attr <string>("relationshipId");
                            var targetUri        = new Uri(action.Attr <string>("targetUri"), UriKind.Relative);
                            var relationshipType = action.Attr <string>("relationshipType");

                            PackagePart part = setPkg.GetPart(partUri);
                            if (part.RelationshipExists(relationshipId))
                            {
                                part.DeleteRelationship(relationshipId);
                            }
                            part.CreateRelationship(targetUri, TargetMode.Internal, relationshipType,
                                                    relationshipId);
                            break;
                        }

                        default:
                            throw new InvalidFileFormatException("Unknown patch action: " + action.Name);
                        }
                    }
                }
            }

            OnProgress(string.Format("{0} patched.", Path.GetFileName(localFilename)));

            if (installed)
            {
                try
                {
                    _game.InstallSet(localFilename);
                }
                catch (Exception ex)
                {
                    OnProgress(string.Format("{0} can't be re-installed.\nDetails: {1}", localFilename, ex.Message),
                               true);
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// This method is under development!
        /// </summary>
        /// <param name="packageFileName">
        /// The package file name.
        /// </param>
        /// <typeparam name="T">
        /// </typeparam>
        /// <returns>
        /// </returns>
        public static IEnumerable <T> ImportFromFromOpenXmlPackageFile <T>(string packageFileName) where T : class, new()
        {
            var list = new List <T>();

            using (var excelPackage = Package.Open(packageFileName, FileMode.Open, FileAccess.Read))
            {
                PackagePart documentPart = null;

                Uri documentUri = null;

                // Get the main document part (workbook.xml).
                foreach (var relationship in excelPackage.GetRelationshipsByType(documentRelationshipType))
                {
                    // There should only be one document part in the package.
                    documentUri  = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
                    documentPart = excelPackage.GetPart(documentUri);

                    // There should only be one instance, but get out no matter what.
                    break;
                }

                if (documentPart != null)
                {
                    // Load the contents of the workbook.
                    using (var reader = XmlReader.Create(documentPart.GetStream()))
                    {
                        var workBook = XDocument.Load(reader);

                        // initialize with an empty list in order to get no NULL reference exception
                        // if the data cannot be found
                        IEnumerable <XElement> sheets = new List <XElement>();

                        // suppress nulls by creating new elements if needed -
                        // we simply need the Rows. If there are no rown, we get NULL,
                        // what does exactly represent what we want.
                        // ReSharper disable PossibleNullReferenceException
                        workBook.MapIfExist2(
                            x => x.Root.Element(mainNameSpace + "sheets").Elements(mainNameSpace + "sheet"), ref sheets);

                        foreach (var sheet in sheets)
                        {
                            var rel = sheet.Attribute(relationShip + "id");
                            if (rel == null)
                            {
                                continue;
                            }

                            var relId = rel.Value;

                            // get the relation between the document and the sheet.
                            var sheetRelation = documentPart.GetRelationship(relId);
                            var sheetUri      = System.IO.Packaging.PackUriHelper.ResolvePartUri(
                                documentUri, sheetRelation.TargetUri);
                            var sheetPart = excelPackage.GetPart(sheetUri);

                            using (var sheetReader = XmlReader.Create(sheetPart.GetStream()))
                            {
                                var sheetXml = XDocument.Load(sheetReader);

                                IEnumerable <XElement> data = new List <XElement>();

                                // suppress nulls by creating new elements if needed -
                                // we simply need the Rows. If there are no rown, we get NULL,
                                // what does exactly represent what we want.
                                // ReSharper disable PossibleNullReferenceException
                                sheetXml.MapIfExist2(
                                    x => x.Root.Element(mainNameSpace + "sheetData").Elements(mainNameSpace + "row"),
                                    ref data);

                                XmlHelper.DeserializeList(data, list, mainNameSpace + "c");
                            }

                            break;
                        }
                    }
                }
            }

            return(list);
        }
Ejemplo n.º 26
0
        public void InstallSet(string filename)
        {
            SQLiteTransaction trans = GamesRepository.DatabaseConnection.BeginTransaction();

            try
            {
                using (Package package = Package.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    PackageRelationship defRelationship =
                        package.GetRelationshipsByType("http://schemas.octgn.org/set/definition").First();
                    PackagePart definition = package.GetPart(defRelationship.TargetUri);

                    var settings = new XmlReaderSettings
                    {
                        ValidationType = ValidationType.Schema, IgnoreWhitespace = true
                    };
                    using (
                        Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(GamesRepository),
                                                                                             "CardSet.xsd"))
                        //CardSet.xsd determines the "attributes" of a card (name, guid, alternate, dependent)
                        if (s != null)
                        {
                            using (XmlReader reader = XmlReader.Create(s))
                                settings.Schemas.Add(null, reader);
                        }

                    // Read the cards
                    using (XmlReader reader = XmlReader.Create(definition.GetStream(), settings))
                    {
                        reader.ReadToFollowing("set"); // <?xml ... ?>

                        var set = new Set(filename, reader, Repository);
                        if (set.Game != this)
                        {
                            throw new ApplicationException(
                                      string.Format("The set '{0}' is not built for the game '{1}'.", set.Name, Name));
                        }
                        if (set.GameVersion.Major != Version.Major || set.GameVersion.Minor != Version.Minor)
                        {
                            throw new ApplicationException(
                                      string.Format(
                                          "The set '{0}' is incompatible with the installed game version.\nGame version: \nSet made for version: {1:2}.",
                                          set.Name, set.GameVersion));
                        }

                        InsertSet(set);

                        if (reader.IsStartElement("packaging"))
                        {
                            reader.ReadStartElement(); // <packaging>
                            while (reader.IsStartElement("pack"))
                            {
                                string xml  = reader.ReadOuterXml();
                                var    pack = new Pack(set, xml);
                                InsertPack(pack, xml, set.Id);
                            }
                            reader.ReadEndElement(); // </packaging>
                        }

                        if (reader.IsStartElement("markers"))
                        {
                            reader.ReadStartElement(); // <markers>
                            while (reader.IsStartElement("marker"))
                            {
                                reader.MoveToAttribute("name");
                                string markerName = reader.Value;
                                reader.MoveToAttribute("id");
                                var    markerId       = new Guid(reader.Value);
                                Uri    markerImageUri = definition.GetRelationship("M" + markerId.ToString("N")).TargetUri;
                                string markerUri      = markerImageUri.OriginalString;
                                if (!package.PartExists(markerImageUri))
                                {
                                    throw new ApplicationException(
                                              string.Format(
                                                  "Image for marker '{0}', with URI '{1}' was not found in the package.",
                                                  markerName, markerUri));
                                }
                                reader.Read(); // <marker />
                                InsertMarker(markerId, markerName, markerUri, set.Id);
                            }
                            reader.ReadEndElement(); // </markers>
                        }

                        if (reader.IsStartElement("cards"))
                        {
                            reader.ReadStartElement(); // <cards>
                            while (reader.IsStartElement("card"))
                            {
                                InsertCard(new CardModel(reader, this, set, definition, package));
                            }
                            // cards are parsed through the CardModel constructor, which are then inserted individually into the database
                            reader.ReadEndElement(); // </cards>
                        }

                        reader.ReadEndElement();
                    }

                    CopyDecks(package);
                    package.Close();

                    // Commit the changes
                    trans.Commit();
                }
            }
            catch (Exception e)
            {
                trans.Rollback();
                throw e;
            }
            if (SimpleDataTableCache.CacheExists())
            {
                SimpleDataTableCache.ClearCache();
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Create a new Picture.
        /// </summary>
        /// <param name="id">A unique id that identifies an Image embedded in this document.</param>
        /// <param name="name">The name of this Picture.</param>
        /// <param name="descr">The description of this Picture.</param>
        internal Picture(DocX document, string id, string name, string descr)
        {
            PackagePart word_document = document.package.GetPart(new Uri("/word/document.xml", UriKind.Relative));
            PackagePart part          = document.package.GetPart(word_document.GetRelationship(id).TargetUri);

            this.id    = id;
            this.name  = name;
            this.descr = descr;

            using (System.Drawing.Image img = System.Drawing.Image.FromStream(part.GetStream()))
            {
                this.cx = img.Width * 9526;
                this.cy = img.Height * 9526;
            }

            XElement e = new XElement(DocX.w + "drawing");

            xml = XElement.Parse
                      (string.Format(@"
            <drawing xmlns = ""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
                <wp:inline distT=""0"" distB=""0"" distL=""0"" distR=""0"" xmlns:wp=""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"">
                    <wp:extent cx=""{0}"" cy=""{1}"" />
                    <wp:effectExtent l=""0"" t=""0"" r=""0"" b=""0"" />
                    <wp:docPr id=""1"" name=""{3}"" descr=""{4}"" />
                    <wp:cNvGraphicFramePr>
                        <a:graphicFrameLocks xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" noChangeAspect=""1"" />
                    </wp:cNvGraphicFramePr>
                    <a:graphic xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"">
                        <a:graphicData uri=""http://schemas.openxmlformats.org/drawingml/2006/picture"">
                            <pic:pic xmlns:pic=""http://schemas.openxmlformats.org/drawingml/2006/picture"">
                                <pic:nvPicPr>
                                <pic:cNvPr id=""0"" name=""{3}"" />
                                    <pic:cNvPicPr />
                                </pic:nvPicPr>
                                <pic:blipFill>
                                    <a:blip r:embed=""{2}"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""/>
                                    <a:stretch>
                                        <a:fillRect />
                                    </a:stretch>
                                </pic:blipFill>
                                <pic:spPr>
                                    <a:xfrm>
                                        <a:off x=""0"" y=""0"" />
                                        <a:ext cx=""{0}"" cy=""{1}"" />
                                    </a:xfrm>
                                    <a:prstGeom prst=""rect"">
                                        <a:avLst />
                                    </a:prstGeom>
                                </pic:spPr>
                            </pic:pic>
                        </a:graphicData>
                    </a:graphic>
                </wp:inline>
            </drawing>
            ", cx, cy, id, name, descr));

            this.xfrm =
                (
                    from d in xml.Descendants()
                    where d.Name.LocalName.Equals("xfrm")
                    select d
                ).Single();

            this.prstGeom =
                (
                    from d in xml.Descendants()
                    where d.Name.LocalName.Equals("prstGeom")
                    select d
                ).Single();

            this.rotation = xfrm.Attribute(XName.Get("rot")) == null ? 0 : uint.Parse(xfrm.Attribute(XName.Get("rot")).Value);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// This constructor parses the XML in reader. Used when reading a card from XML, mainly when installing a set.
        /// </summary>
        /// <param name="reader">The XML</param>
        /// <param name="game"></param>
        /// <param name="set"></param>
        /// <param name="definition"></param>
        /// <param name="package"></param>
        public CardModel(XmlReader reader, Game game, Set set, PackagePart definition, Package package)
        {
            Properties = new SortedList <string, object>(game.CustomProperties.Count,
                                                         StringComparer.InvariantCultureIgnoreCase);
            reader.MoveToAttribute("name");
            Name = reader.Value;
            reader.MoveToAttribute("id");
            Id = new Guid(reader.Value);
            //           isMutable = false;
            if (reader.MoveToAttribute("alternate"))
            {
                try { Alternate = new Guid(reader.Value); }
                catch (Exception e)
                {
                    throw new ArgumentException(String.Format("The value {0} is not of expected type for property Alternate. Alternate must be a GUID.",
                                                              reader.Value));
                }
            }
            else
            {
                Alternate = System.Guid.Empty;
            }
            if (reader.MoveToAttribute("dependent"))
            {
                try
                {
                    Dependent = new Guid(reader.Value).ToString();
                }
                catch (Exception e)
                {
                    try
                    {
                        Dependent = Boolean.Parse(reader.Value).ToString();
                    }
                    catch (Exception eff)
                    {
                        throw new ArgumentException(String.Format("The value {0} is not of expected type for property Dependent. Dependent must be either true/false, or the Guid of the card to use instead.",
                                                                  reader.Value));
                    }
                }
            }
            else
            {
                Dependent = String.Empty;
            }
            Uri cardImageUri = definition.GetRelationship("C" + Id.ToString("N")).TargetUri;

            ImageUri = cardImageUri.OriginalString;
            if (!package.PartExists(cardImageUri))
            {
                throw new Exception(string.Format("Image for card '{0}', with URI '{1}' was not found in the package.",
                                                  Name, ImageUri));
            }
            reader.Read(); // <card>

            Set = set;

            while (reader.IsStartElement("property"))
            {
                reader.MoveToAttribute("name");
                PropertyDef prop = game.CustomProperties.FirstOrDefault(p => p.Name == reader.Value);
                if (prop == null)
                {
                    throw new ArgumentException(string.Format("The property '{0}' is unknown", reader.Value));
                }
                reader.MoveToAttribute("value");
                try
                {
                    switch (prop.Type)
                    {
                    case PropertyType.String:
                        Properties.Add(prop.Name, reader.Value);
                        break;

                    case PropertyType.Integer:
                        Properties.Add(prop.Name, Int32.Parse(reader.Value));
                        break;

                    case PropertyType.Char:
                        Properties.Add(prop.Name, Char.Parse(reader.Value));
                        break;

                    default:
                        throw new NotImplementedException();
                    }
                }
                catch (FormatException)
                {
                    throw new ArgumentException(String.Format("The value {0} is not of expected type for property {1}",
                                                              reader.Value, prop.Name));
                }
                reader.Read(); // <property/>
            }

            reader.Read(); // </card>
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Loads the main document part of a CDDX file.
        /// </summary>
        /// <param name="package">The package containing the document to load.</param>
        /// <returns>True if succeeded, false otherwise.</returns>
        bool LoadMainDocument(Package package)
        {
            // Open the document part
            PackageRelationship documentRelationship = package.GetRelationshipsByType(RelationshipTypes.Document).FirstOrDefault();
            PackagePart         documentPart         = package.GetPart(documentRelationship.TargetUri);

            using (Stream docStream = documentPart.GetStream(FileMode.Open))
            {
                Document = new IODocument();

                XmlDocument doc = new XmlDocument();
                doc.Load(docStream);

                // Set up namespaces
                XmlNamespaceManager namespaceManager = new XmlNamespaceManager(doc.NameTable);
                namespaceManager.AddNamespace("cdd", Namespaces.Document);
                namespaceManager.AddNamespace("ec", Namespaces.DocumentComponentDescriptions);

                // Read version
                double     version     = 1.0;
                XmlElement rootElement = doc.SelectSingleNode("/cdd:circuit", namespaceManager) as XmlElement;
                if (rootElement != null && rootElement.HasAttribute("version"))
                {
                    double.TryParse(rootElement.Attributes["version"].InnerText, out version);
                }
                if (version > FormatVersion)
                {
                    m_newerVersion = true;
                }

                if (m_newerVersion)
                {
                    LoadResult.Type = DocumentLoadResultType.SuccessNewerVersion;
                }
                else
                {
                    LoadResult.Type = DocumentLoadResultType.Success;
                }

                // Read size
                double  width     = 640d;
                double  height    = 480d;
                XmlNode widthNode = doc.SelectSingleNode("/cdd:circuit/cdd:properties/cdd:width", namespaceManager);
                if (widthNode != null)
                {
                    double.TryParse(widthNode.InnerText, out width);
                }
                XmlNode heightNode = doc.SelectSingleNode("/cdd:circuit/cdd:properties/cdd:height", namespaceManager);
                if (heightNode != null)
                {
                    double.TryParse(heightNode.InnerText, out height);
                }
                Document.Size = new Size(width, height);

                // Read sources
                m_typeParts.Clear();
                Dictionary <string, IOComponentType> componentTypes = new Dictionary <string, IOComponentType>(); // for use when loading component elements
                XmlNodeList componentSourceNodes = doc.SelectNodes("/cdd:circuit/cdd:definitions/cdd:src", namespaceManager);
                foreach (XmlElement source in componentSourceNodes)
                {
                    // Read collection
                    string collection = null;
                    if (source.HasAttribute("col"))
                    {
                        collection = source.Attributes["col"].InnerText;
                    }

                    foreach (XmlElement addType in source.SelectNodes("cdd:add", namespaceManager))
                    {
                        // Read item
                        string typeId = addType.Attributes["id"].InnerText;
                        string item   = null;
                        if (addType.HasAttribute("item"))
                        {
                            item = addType.Attributes["item"].InnerText;
                        }

                        // Read additional attributes for opening with the same component description
                        string name = null;
                        if (addType.HasAttribute("name", Namespaces.DocumentComponentDescriptions))
                        {
                            name = addType.Attributes["name", Namespaces.DocumentComponentDescriptions].InnerText;
                        }
                        Guid guid = Guid.Empty;
                        if (addType.HasAttribute("guid", Namespaces.DocumentComponentDescriptions))
                        {
                            guid = new Guid(addType.Attributes["guid", Namespaces.DocumentComponentDescriptions].InnerText);
                        }

                        // Create new IOComponentType
                        IOComponentType type = new IOComponentType(collection, item);
                        type.Name = name;
                        type.GUID = guid;

                        // Read additional attributes for embedding
                        if (addType.HasAttribute("id", Namespaces.Relationships))
                        {
                            string relationshipId                = addType.Attributes["id", Namespaces.Relationships].InnerText;
                            PackageRelationship relationship     = documentPart.GetRelationship(relationshipId);
                            PackagePart         embeddedTypePart = package.GetPart(PackUriHelper.ResolvePartUri(documentPart.Uri, relationship.TargetUri));
                            m_typeParts.Add(type, embeddedTypePart);
                        }

                        componentTypes.Add(typeId, type);
                    }
                }

                // Read wire elements
                XmlNodeList wires = doc.SelectNodes("/cdd:circuit/cdd:elements//cdd:w", namespaceManager);
                foreach (XmlElement wire in wires)
                {
                    // Read wire
                    double      x           = double.Parse(wire.Attributes["x"].InnerText);
                    double      y           = double.Parse(wire.Attributes["y"].InnerText);
                    Orientation orientation = Orientation.Vertical;
                    if (wire.HasAttribute("o") && wire.Attributes["o"].InnerText.ToLowerInvariant() == "h")
                    {
                        orientation = Orientation.Horizontal;
                    }
                    double size = 10d;
                    if (wire.HasAttribute("sz"))
                    {
                        size = double.Parse(wire.Attributes["sz"].InnerText);
                    }

                    Document.Wires.Add(new IOWire(new Point(x, y), size, orientation));
                }

                // Read component elements
                XmlNodeList componentElements = doc.SelectNodes("/cdd:circuit/cdd:elements//cdd:c", namespaceManager);
                foreach (XmlElement element in componentElements)
                {
                    // Read component element
                    string id = null;
                    if (element.HasAttribute("id"))
                    {
                        id = element.Attributes["id"].InnerText;
                    }
                    string typeId = element.Attributes["tp"].InnerText;

                    // Read layout information
                    Point?location = null;
                    if (element.HasAttribute("x") && element.HasAttribute("y"))
                    {
                        location = new Point(double.Parse(element.Attributes["x"].InnerText), double.Parse(element.Attributes["y"].InnerText));
                    }
                    double?size = null;
                    if (element.HasAttribute("sz"))
                    {
                        size = double.Parse(element.Attributes["sz"].InnerText);
                    }
                    Orientation?orientation = null;
                    if (element.HasAttribute("o") && element.Attributes["o"].InnerText.ToLowerInvariant() == "h")
                    {
                        orientation = Orientation.Horizontal;
                    }
                    else if (element.HasAttribute("o") && element.Attributes["o"].InnerText.ToLowerInvariant() == "v")
                    {
                        orientation = Orientation.Vertical;
                    }
                    bool?flipped = null;
                    if (element.HasAttribute("flp") && element.Attributes["flp"].InnerText.ToLowerInvariant() == "false")
                    {
                        flipped = false;
                    }
                    else if (element.HasAttribute("flp"))
                    {
                        flipped = true;
                    }

                    // Read properties
                    List <IOComponentProperty> properties = new List <IOComponentProperty>();
                    XmlNodeList propertyNodes             = element.SelectNodes("cdd:prs/cdd:p", namespaceManager);
                    foreach (XmlElement property in propertyNodes)
                    {
                        // Read property
                        string key        = property.Attributes["k"].InnerText;
                        string value      = property.Attributes["v"].InnerText;
                        bool   isStandard = true;
                        if (property.HasAttribute("st", Namespaces.DocumentComponentDescriptions) && property.Attributes["st", Namespaces.DocumentComponentDescriptions].InnerText == "false")
                        {
                            isStandard = false;
                        }

                        properties.Add(new IOComponentProperty(key, value, isStandard));
                    }

                    // Read connections
                    Dictionary <string, string> connections = new Dictionary <string, string>();
                    XmlNodeList connectionNodes             = element.SelectNodes("cdd:cns/cdd:cn", namespaceManager);
                    foreach (XmlNode connection in connectionNodes)
                    {
                        // Read connection
                        string point        = connection.Attributes["pt"].InnerText;
                        string connectionId = connection.Attributes["id"].InnerText;

                        connections.Add(point, connectionId);
                    }

                    // Find type
                    IOComponentType type = null;
                    if (typeId.StartsWith("{") && typeId.EndsWith("}"))
                    {
                        // Type in expected format: {0}
                        string typeIdOnly = typeId.Substring(1, typeId.Length - 2); // Remove curly braces
                        if (componentTypes.ContainsKey(typeIdOnly))
                        {
                            type = componentTypes[typeIdOnly];
                        }
                        else
                        {
                            throw new NotSupportedException(); // Undefined type
                        }
                    }

                    Document.Components.Add(new IOComponent(id, location, size, flipped, orientation, type, properties, connections));
                }

                return(true);
            }
        }