internal void AddPackageFiles(Package package, PackagePart rootFile)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            // get all supplementary files related to the root file
            var relations = rootFile.GetRelationships();

            // get all parts
            var parts = package.GetParts();

            // add all supplementary files
            foreach (var relation in relations)
            {
                DocumentFileType type;
                if (!relation.TryParseDocumentFileType(out type))
                {
                    continue;
                }

                var part = parts.FirstOrDefault(p => PackUriHelper.ComparePartUri(p.Uri, relation.TargetUri) == 0);
                if (part != null)
                {
                    _files.Add(new PackageDocumentFile(part)
                    {
                        Type = type
                    });
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Saves the XmlDocument into the package at the specified Uri.
        /// </summary>
        /// <param name="uri">The Uri of the component</param>
        /// <param name="xmlDoc">The XmlDocument to save</param>
        internal void SaveWorkbook(Uri uri, XmlDocument xmlDoc)
        {
            PackagePart part = _package.GetPart(uri);

            if (Workbook.VbaProject == null)
            {
                if (part.ContentType != contentTypeWorkbookDefault)
                {
                    part = _package.CreatePart(uri, contentTypeWorkbookDefault, Compression);
                }
            }
            else
            {
                if (part.ContentType != contentTypeWorkbookMacroEnabled)
                {
                    var rels = part.GetRelationships();
                    _package.DeletePart(uri);
                    part = Package.CreatePart(uri, contentTypeWorkbookMacroEnabled);
                    foreach (var rel in rels)
                    {
                        Package.DeleteRelationship(rel.Id);
                        part.CreateRelationship(rel.TargetUri, rel.TargetMode, rel.RelationshipType);
                    }
                }
            }
            xmlDoc.Save(part.GetStream(FileMode.Create, FileAccess.Write));
        }
Ejemplo n.º 3
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.º 4
0
        static void AddSignableItems(
            PackageRelationship relationship,
            List <Uri> partsToSign,
            List <PackageRelationshipSelector> relationshipsToSign)
        {
            PackageRelationshipSelector selector =
                new PackageRelationshipSelector(
                    relationship.SourceUri,
                    PackageRelationshipSelectorType.Id,
                    relationship.Id);

            relationshipsToSign.Add(selector);
            if (relationship.TargetMode == TargetMode.Internal)
            {
                PackagePart part = relationship.Package.GetPart(
                    PackUriHelper.ResolvePartUri(
                        relationship.SourceUri, relationship.TargetUri));
                if (partsToSign.Contains(part.Uri) == false)
                {
                    partsToSign.Add(part.Uri);
                    foreach (PackageRelationship childRelationship in
                             part.GetRelationships())
                    {
                        AddSignableItems(childRelationship,
                                         partsToSign, relationshipsToSign);
                    }
                }
            }
        }
Ejemplo n.º 5
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)
            {
            }
        }
        public DocumentPartCollection CreateDocumentParts(PackagePart packagePart)
        {
            DocumentPartCollection parts = new DocumentPartCollection();

            foreach (PackageRelationship relationship in packagePart.GetRelationships())
            {
                parts.Add(CreateDocumentPart(relationship));
            }
            return(parts);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Sets the document theme
        /// </summary>
        /// <param name="theme">Theme package</param>
        public void SetTheme(Package theme)
        {
            // Gets the theme manager part
            PackageRelationship themeManagerRelationship =
                theme.GetRelationshipsByType(mainDocumentRelationshipType).FirstOrDefault();

            if (themeManagerRelationship != null)
            {
                PackagePart themeManagerPart = theme.GetPart(themeManagerRelationship.TargetUri);

                // Gets the theme main part
                PackageRelationship themeRelationship =
                    themeManagerPart.GetRelationshipsByType(themeRelationshipType).FirstOrDefault();
                if (themeRelationship != null)
                {
                    PackagePart themePart        = theme.GetPart(themeRelationship.TargetUri);
                    XDocument   newThemeDocument = XDocument.Load(XmlReader.Create(themePart.GetStream(FileMode.Open, FileAccess.Read)));

                    // Removes existing theme part from document
                    if (parentDocument.Document.MainDocumentPart.ThemePart != null)
                    {
                        parentDocument.Document.MainDocumentPart.DeletePart(parentDocument.Document.MainDocumentPart.ThemePart);
                    }

                    // Creates a new theme part
                    ThemePart documentThemePart = parentDocument.Document.MainDocumentPart.AddNewPart <ThemePart>();
                    XDocument themeDocument     = parentDocument.GetXDocument(documentThemePart);
                    themeDocument.Add(newThemeDocument.Root);

                    var embeddedItems =
                        themeDocument
                        .Descendants()
                        .Attributes(relationshipns + "embed");
                    foreach (PackageRelationship imageRelationship in themePart.GetRelationships())
                    {
                        // Adds an image part to the theme part and stores contents inside
                        PackagePart imagePart    = theme.GetPart(imageRelationship.TargetUri);
                        ImagePart   newImagePart =
                            documentThemePart.AddImagePart(GetImagePartType(imagePart.ContentType));
                        newImagePart.FeedData(imagePart.GetStream(FileMode.Open, FileAccess.Read));

                        // Updates relationship references into the theme XDocument
                        XAttribute relationshipAttribute = embeddedItems.FirstOrDefault(e => e.Value == imageRelationship.Id);
                        if (relationshipAttribute != null)
                        {
                            relationshipAttribute.Value = documentThemePart.GetIdOfPart(newImagePart);
                        }
                    }

                    // Updates the theme part with actual contents of the theme XDocument
                    using (XmlWriter newThemeWriter = XmlWriter.Create(documentThemePart.GetStream(FileMode.Create, FileAccess.Write)))
                        themeDocument.WriteTo(newThemeWriter);
                }
            }
        }
Ejemplo n.º 8
0
        private Uri GetMetaPartUri(PackagePart part)
        {
            PackageRelationship relationship = null;

            foreach (var rel in part.GetRelationships())
            {
                relationship = rel;
            }

            return(_archive.GetPart(relationship.TargetUri).Uri);
        }
Ejemplo n.º 9
0
        public PackagePartRelationshipPropertyCollection(PackagePart packagePart)
        {
            BasePackagePart = packagePart;
            if (BasePackagePart is null)
            {
                throw new ArgumentNullException(nameof(BasePackagePart));
            }

            BasePackageRelationshipCollection = BasePackagePart.GetRelationships();
            Build();
        }
Ejemplo n.º 10
0
        public PBIdentityComposite LoadFromFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    Professionbuddy.Log("Loading profile {0}", path);
                    ProfilePath = path;

                    if (Path.GetExtension(path).Equals(".package", StringComparison.InvariantCultureIgnoreCase))
                    {
                        using (Package zipFile = Package.Open(path, FileMode.Open, FileAccess.Read))
                        {
                            var packageRelation = zipFile.GetRelationships().FirstOrDefault();
                            if (packageRelation == null)
                            {
                                Professionbuddy.Err("{0} contains no usable profiles", path);
                                return(null);
                            }
                            PackagePart pbProfilePart = zipFile.GetPart(packageRelation.TargetUri);
                            path = ExtractPart(pbProfilePart, _pb.TempFolder);
                            var pbProfileRelations = pbProfilePart.GetRelationships();
                            foreach (var rel in pbProfileRelations)
                            {
                                var hbProfilePart = zipFile.GetPart(rel.TargetUri);
                                ExtractPart(hbProfilePart, _pb.TempFolder);
                            }
                        }
                    }
                    Branch.Children.Clear();
                    PBIdentityComposite idComp;
                    XmlReaderSettings   settings = new XmlReaderSettings();
                    settings.IgnoreWhitespace             = true;
                    settings.IgnoreProcessingInstructions = true;
                    settings.IgnoreComments = true;

                    using (XmlReader reader = XmlReader.Create(path, settings))
                    {
                        idComp = new PBIdentityComposite(Branch);
                        idComp.ReadXml(reader);
                    }
                    XmlPath = path;
                    return(idComp);
                }
                else
                {
                    Professionbuddy.Err("Profile: {0} does not exist", path);
                    return(null);
                }
            }
            catch (Exception ex) { Professionbuddy.Err(ex.ToString()); return(null); }
        }
Ejemplo n.º 11
0
        internal void Load(OpenXmlPackage openXmlPackage, PackagePart packagePart)
        {
            Debug.Assert(openXmlPackage.Package.GetPart(packagePart.Uri) == packagePart);

            _openXmlPackage = openXmlPackage;
            _metroPart      = packagePart;
            _uri            = packagePart.Uri;

            if (_metroPart.GetRelationships().Any())
            {
                // Media (Audio, Video) parts should not reference any other parts.
                throw new OpenXmlPackageException(ExceptionMessages.MediaDataPartShouldNotReferenceOtherParts);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        ///  Function to check whether Current doc is having Sub documents or not
        /// </summary>
        /// <returns></returns>
        public String MasterSubDecision()
        {
            Package pack = Package.Open(tempInput, FileMode.Open, FileAccess.ReadWrite);

            foreach (PackageRelationship searchRelation in pack.GetRelationshipsByType(wordRelationshipType))
            {
                packRelationship = searchRelation;
                break;
            }

            Uri         partUri     = PackUriHelper.ResolvePartUri(packRelationship.SourceUri, packRelationship.TargetUri);
            PackagePart mainPartxml = pack.GetPart(partUri);
            int         cnt         = 0;

            foreach (PackageRelationship searchRelation in mainPartxml.GetRelationships())
            {
                packRelationship = searchRelation;
                if (packRelationship.RelationshipType == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/subDocument")
                {
                    if (packRelationship.TargetMode.ToString() == "External")
                    {
                        cnt++;
                    }
                }
            }
            pack.Close();

            if (cnt > 0)
            {
                DialogResult dr = MessageBox.Show(resManager.GetString("MasterSubConfirmation"), "SaveAsDAISY", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                if (dr == DialogResult.Yes)
                {
                    masterSubFlag = "Yes";
                }
                else
                {
                    masterSubFlag = "No";
                }
            }
            else
            {
                masterSubFlag = "NoMasterSub";
            }

            return(masterSubFlag);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Find all subdocuments.
        /// The Errors array is filled if errors are found
        /// </summary>
        /// <param name="tempInputPath">Path to the copy of the word document.</param>
        /// <param name="originalInputPath">Path to the original word document.</param>
        /// <returns>Collection of the subdocuments.</returns>
        public static SubdocumentsList FindSubdocuments(string tempInputPath, string originalInputPath)
        {
            PackageRelationship relationship = null;
            SubdocumentsList    result       = new SubdocumentsList();

            Package packDoc = Package.Open(tempInputPath, FileMode.Open, FileAccess.ReadWrite);

            foreach (PackageRelationship searchRelation in packDoc.GetRelationshipsByType(WordRelationshipType))
            {
                relationship = searchRelation;
                break;
            }

            Uri         partUri     = PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri);
            PackagePart mainPartxml = packDoc.GetPart(partUri);

            foreach (PackageRelationship searchRelation in mainPartxml.GetRelationships())
            {
                relationship = searchRelation;
                if (IsExternalSubdocumentRelationship(relationship))
                {
                    bool subDocumentFound = IsMsWordSubdocumentRelationship(relationship);
                    result.SubdocumentsCount += subDocumentFound ? 1 : 0;
                    String filePath = GetRealFilePath(relationship.TargetUri.ToString(), originalInputPath);
                    if (!string.IsNullOrEmpty(filePath))
                    {
                        if (subDocumentFound)
                        {
                            result.Subdocuments.Add(new SubdocumentInfo(filePath, relationship.Id));
                        }
                        else
                        {
                            result.NotTranslatedSubdocuments.Add(new SubdocumentInfo(filePath, relationship.Id));
                        }
                    }
                    else
                    {
                        result.Errors.Add(
                            "The subdocument " + originalInputPath + "\\" + relationship.TargetUri.ToString() + " was not found on your system."
                            );
                    }
                }
            }
            packDoc.Close();
            return(result);
        }
        public void Remove()
        {
            // Remove all image parts first
            foreach (PackageRelationship relationship in _part.GetRelationships())
            {
                Uri relUri = PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri);
                if (_part.Package.PartExists(relUri))
                {
                    _part.Package.DeletePart(relUri);
                }
            }

            _part.Package.DeleteRelationship(_id);
            _part.Package.DeletePart(_part.Uri);

            _part = null;
            _id   = null;
        }
Ejemplo n.º 15
0
        private List <HtmlStore> ParseDocx(string fileName)
        {
            using (_package = Package.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                PackageRelationship rel     = _package.GetRelationships().Where(c => c.RelationshipType == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument").First();
                PackagePart         docPart = _package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), rel.TargetUri));
                _docRels = docPart.GetRelationships();

                XDocument doc = null;
                using (Stream st = docPart.GetStream(FileMode.Open, FileAccess.Read))
                {
                    StreamReader sr = new StreamReader(st);
                    doc = XDocument.Load(sr, LoadOptions.None);
                    ParseDocument(doc);
                }
                if (!_isAnswerMode && _sb.Length > 0)
                {
                    string addStr = ReplaceWrongChars(_sb.ToString());
                    if (addStr.Length > 0)
                    {
                        AddQuestion(_sb.ToString());
                    }
                }
                else if (_isAnswerMode)
                {
                    AddAnswer(_sb.ToString());
                }
            }
            int index = 1;

            foreach (var quest in _questions)
            {
                quest.Html         = ReplaceWrongChars(ReplaceWrongChars(quest.Html.Replace(Environment.NewLine, "<br/>")));
                quest.QuestionType = QuestionTypeHelper.GetQuestionType(quest);
                quest.QuestIndex   = index;
                index++;
                foreach (var ans in quest.SubItems)
                {
                    ans.Html = ReplaceWrongChars(ReplaceWrongChars(ans.Html.Replace(Environment.NewLine, "<br/>")));
                }
            }
            _package.Close();
            return(_questions);
        }
Ejemplo n.º 16
0
        /// <summary>Profile behavior.</summary>
        //public PrioritySelector Branch { get; protected set; }
        public static PbProfile LoadFromFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    string extension = Path.GetExtension(path);
                    if (extension != null && extension.Equals(".package", StringComparison.InvariantCultureIgnoreCase))
                    {
                        using (Package zipFile = Package.Open(path, FileMode.Open, FileAccess.Read))
                        {
                            PackageRelationship packageRelation = zipFile.GetRelationships().FirstOrDefault();
                            if (packageRelation == null)
                            {
                                PBLog.Warn("{0} contains no usable profiles", path);
                                return(null);
                            }
                            PackagePart pbProfilePart = zipFile.GetPart(packageRelation.TargetUri);
                            path = ExtractPart(pbProfilePart, DynamicCodeCompiler.TempFolder);
                            PackageRelationshipCollection pbProfileRelations = pbProfilePart.GetRelationships();
                            foreach (PackageRelationship rel in pbProfileRelations)
                            {
                                PackagePart hbProfilePart = zipFile.GetPart(rel.TargetUri);
                                ExtractPart(hbProfilePart, DynamicCodeCompiler.TempFolder);
                            }
                        }
                    }
                    var element     = XElement.Load(path);
                    var versionAttr = element.Attribute("version");
                    var version     = versionAttr != null?int.Parse(versionAttr.Value) : 0;

                    var branch = (PBBranch)FromXml(element, new PBBranch());
                    return(new PbProfile(branch, version, path));
                }
                PBLog.Warn("Profile: {0} does not exist", path);
                return(null);
            }
            catch (Exception ex)
            {
                PBLog.Warn(ex.ToString());
                return(null);
            }
        }
Ejemplo n.º 17
0
        static void CreateListOfSignableItems(PackageRelationship relationship, List <Uri> PartstobeSigned, List <PackageRelationshipSelector> SignableReleationships)
        {
            // This function adds the releation to SignableReleationships. And then it gets the part based on the releationship. Parts URI gets added to the PartstobeSigned list.
            PackageRelationshipSelector selector = new PackageRelationshipSelector(relationship.SourceUri, PackageRelationshipSelectorType.Id, relationship.Id);

            SignableReleationships.Add(selector);
            if (relationship.TargetMode == TargetMode.Internal)
            {
                PackagePart part = relationship.Package.GetPart(PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri));
                if (PartstobeSigned.Contains(part.Uri) == false)
                {
                    PartstobeSigned.Add(part.Uri);
                    // GetRelationships Function: Returns a Collection Of all the releationships that are owned by the part.
                    foreach (PackageRelationship childRelationship in part.GetRelationships())
                    {
                        CreateListOfSignableItems(childRelationship, PartstobeSigned, SignableReleationships);
                    }
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Profile behavior.
        /// </summary>
        //public PrioritySelector Branch { get; protected set; }
        public PbDecorator LoadFromFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    ProfilePath = path;

                    string extension = Path.GetExtension(path);
                    if (extension != null && extension.Equals(".package", StringComparison.InvariantCultureIgnoreCase))
                    {
                        using (Package zipFile = Package.Open(path, FileMode.Open, FileAccess.Read))
                        {
                            PackageRelationship packageRelation = zipFile.GetRelationships().FirstOrDefault();
                            if (packageRelation == null)
                            {
                                Professionbuddy.Err("{0} contains no usable profiles", path);
                                return(null);
                            }
                            PackagePart pbProfilePart = zipFile.GetPart(packageRelation.TargetUri);
                            path = ExtractPart(pbProfilePart, DynamicCodeCompiler.TempFolder);
                            PackageRelationshipCollection pbProfileRelations = pbProfilePart.GetRelationships();
                            foreach (PackageRelationship rel in pbProfileRelations)
                            {
                                PackagePart hbProfilePart = zipFile.GetPart(rel.TargetUri);
                                ExtractPart(hbProfilePart, DynamicCodeCompiler.TempFolder);
                            }
                        }
                    }
                    XmlPath = path;
                    return((PbDecorator)Load(XElement.Load(path), new PbDecorator()));
                }
                Professionbuddy.Err("Profile: {0} does not exist", path);
                return(null);
            }
            catch (Exception ex)
            {
                Professionbuddy.Err(ex.ToString());
                return(null);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Function checks whether Document si Master/sub doc or simple doc
        /// </summary>
        /// <param name="listSubDocs">List of Documents</param>
        /// <returns> Message saying Liist of Docs are simple docs or not</returns>
        public static string CheckingSubDocs(ArrayList listSubDocs)
        {
            PackageRelationship relationship = null;
            String resultSubDoc = "simple";

            //TODO:
            for (int i = 0; i < listSubDocs.Count; i++)
            {
                string[] splt = listSubDocs[i].ToString().Split('|');
                Package  pack;
                pack = Package.Open(splt[0].ToString(), FileMode.Open, FileAccess.ReadWrite);

                foreach (PackageRelationship searchRelation in pack.GetRelationshipsByType(WordRelationshipType))
                {
                    relationship = searchRelation;
                    break;
                }
                if (relationship == null)
                {
                    continue;
                }

                Uri         partUri     = PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri);
                PackagePart mainPartxml = pack.GetPart(partUri);

                foreach (PackageRelationship searchRelation in mainPartxml.GetRelationships())
                {
                    relationship = searchRelation;
                    //checking whether Doc is simple or Master\sub Doc
                    if (relationship.RelationshipType == WordSubdocumentRelationshipType)
                    {
                        if (relationship.TargetMode.ToString() == "External")
                        {
                            resultSubDoc = "complex";
                        }
                    }
                }
                pack.Close();
            }
            return(resultSubDoc);
        }
Ejemplo n.º 20
0
 private void CreateListOfSignableItems(PackageRelationship relationship, List <Uri> PartstobeSigned, List <PackageRelationshipSelector> SignableReleationships)
 {
     try
     {
         PackageRelationshipSelector packageRelationshipSelector = new PackageRelationshipSelector(relationship.SourceUri, PackageRelationshipSelectorType.Id, relationship.Id);
         SignableReleationships.Add(packageRelationshipSelector);
         if (relationship.TargetMode == TargetMode.Internal)
         {
             PackagePart part = relationship.Package.GetPart(PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri));
             if (!PartstobeSigned.Contains(part.Uri))
             {
                 PartstobeSigned.Add(part.Uri);
                 foreach (PackageRelationship packageRelationship in part.GetRelationships())
                 {
                     this.CreateListOfSignableItems(packageRelationship, PartstobeSigned, SignableReleationships);
                 }
             }
         }
     }
     catch (Exception exception)
     {
         throw new Exception(exception.Message);
     }
 }
Ejemplo n.º 21
0
        private PackagePart GetAnnotationPart(Uri uri)
        {
            Package package = PackageStore.GetPackage(documentUri);

            if (package == null)
            {
                return(null);
            }

            // Get the FixedDocumentSequence part from the package.
            PackagePart fdsPart = package.GetPart(uri);

            // Search through all the document relationships to find the
            // annotations relationship part (or null, of there is none).
            PackageRelationship annotRel = null;

            annotRel
                = fdsPart.GetRelationships().FirstOrDefault <PackageRelationship>(
                      pr => pr.RelationshipType == annotRelsType);

            PackagePart annotPart;

            //If annotations relationship does not exist, create a new
            //annotations part, if required, and a relationship for it.
            if (annotRel == null)
            {
                Uri annotationUri =
                    PackUriHelper.CreatePartUri(new Uri("annotations.xml",
                                                        UriKind.Relative));

                if (package.PartExists(annotationUri))
                {
                    annotPart = package.GetPart(annotationUri);
                }
                else
                {
                    //Create a new Annotations part in the document.
                    annotPart = package.CreatePart(annotationUri, annotContentType);
                }

                //Create a new relationship that points to the Annotations part.
                fdsPart.CreateRelationship(annotPart.Uri,
                                           TargetMode.Internal,
                                           annotRelsType);
            }
            else
            {
                //If an annotations relationship exists,
                //get the annotations part that it references.

                //Get the Annotations part specified by the relationship.
                annotPart = package.GetPart(annotRel.TargetUri);

                if (annotPart == null)
                {
                    //The annotations part pointed to by the annotation
                    //relationship Uri is not present. Handle as required.
                    return(null);
                }
            }

            return(annotPart);
        }
Ejemplo n.º 22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="target">
        ///
        /// </param>
        /// <exception cref="ArgumentNullException" />
        public void CopyTo([NotNull] Package target)
        {
            if (target is null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (!target.FileOpenAccess.HasFlag(FileAccess.Read))
            {
                throw new IOException("The package is write-only.");
            }

            if (!_package.PartExists(PartUri))
            {
                return;
            }

            if (target.PartExists(PartUri))
            {
                target.DeletePart(PartUri);
            }

            target.GetPart(Document.PartUri)
            .CreateRelationship(PartUri, TargetMode.Internal, RelationshipType);

            PackagePart source      = _package.GetPart(PartUri);
            PackagePart destination = target.CreatePart(PartUri, ContentType);

            using (Stream from = source.GetStream())
            {
                using (Stream to = destination.GetStream())
                {
                    from.CopyTo(to);
                }
            }

            foreach (PackageRelationship relationship in source.GetRelationships())
            {
                if (relationship.RelationshipType != ChartInfo.RelationshipType &&
                    relationship.RelationshipType != ImageInfo.RelationshipType &&
                    relationship.RelationshipType != HyperlinkInfo.RelationshipType)
                {
                    continue;
                }

                destination.CreateRelationship(
                    relationship.TargetUri,
                    relationship.TargetMode,
                    relationship.RelationshipType,
                    relationship.Id);

                if (relationship.RelationshipType != ChartInfo.RelationshipType &&
                    relationship.RelationshipType != ImageInfo.RelationshipType)
                {
                    continue;
                }

                PackagePart part = _package.GetPart(MakePartUri(relationship.TargetUri));

                using (Stream from = part.GetStream())
                {
                    using (Stream to = target.CreatePart(part.Uri, part.ContentType).GetStream())
                    {
                        from.CopyTo(to);
                    }
                }
            }
        }
 public PackagePartRelationshipPropertyCollection(PackagePart packagePart)
     : base(packagePart.GetRelationships())
 {
     PackagePart = packagePart;
 }
Ejemplo n.º 24
0
        /* Core Function to translate all Sub documents */
        public void MultipleOwnDocCore(String inputFile, String outputfilepath)
        {
            try {
                subList          = new ArrayList();
                langMergeDoc     = new ArrayList();
                notTranslatedDoc = new ArrayList();
                subList.Add(inputFile + "|Master");

                //OPening the Package of the Current Document
                Package packDoc;
                packDoc = Package.Open(inputFile, FileMode.Open, FileAccess.ReadWrite);

                //Searching for Document.xml
                foreach (PackageRelationship searchRelation in packDoc.GetRelationshipsByType(wordRelationshipType))
                {
                    relationship = searchRelation;
                    break;
                }

                Uri         partUri     = PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri);
                PackagePart mainPartxml = packDoc.GetPart(partUri);

                foreach (PackageRelationship searchRelation in mainPartxml.GetRelationships())
                {
                    relationship = searchRelation;
                    if (relationship.RelationshipType == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/subDocument")
                    {
                        if (relationship.TargetMode.ToString() == "External")
                        {
                            String fileName = relationship.TargetUri.ToString();

                            //Checking whether sub document is of type Docx or Doc
                            if (Path.GetExtension(fileName) == ".docx" || Path.GetExtension(fileName) == ".doc")
                            {
                                subCount++;

                                //Making a list of all Sub documents in the current Document
                                if (fileName.Contains("file") && fileName.Contains("/Local Settings/Temp/"))
                                {
                                    fileName = fileName.Replace("file:///", "");
                                    int indx = fileName.LastIndexOf("/Local Settings/Temp/");
                                    fileName = fileName.Substring(indx + 21);
                                    fileName = Path.GetDirectoryName(inputFile) + "//" + fileName;
                                    if (File.Exists(fileName))
                                    {
                                        subList.Add(fileName + "|" + relationship.Id.ToString());
                                    }
                                }
                                else if (fileName.Contains("file"))
                                {
                                    fileName = fileName.Replace("file:///", "");
                                    if (File.Exists(fileName))
                                    {
                                        subList.Add(fileName + "|" + relationship.Id.ToString());
                                    }
                                }
                                else
                                {
                                    fileName = Path.GetDirectoryName(inputFile) + "\\" + Path.GetFileName(fileName);
                                    if (fileName.Contains("%20"))
                                    {
                                        fileName = fileName.Replace("%20", " ");
                                    }
                                    if (File.Exists(fileName))
                                    {
                                        subList.Add(fileName + "|" + relationship.Id.ToString());
                                    }
                                }
                            }
                            //If sub document is of type other than Docx and Doc format
                            else
                            {
                                if (fileName.Contains("file") && fileName.Contains("/Local Settings/Temp/"))
                                {
                                    fileName = fileName.Replace("file:///", "");
                                    int indx = fileName.LastIndexOf("/Local Settings/Temp/");
                                    fileName = fileName.Substring(indx + 21);
                                    fileName = Path.GetDirectoryName(inputFile) + "//" + fileName;
                                    if (File.Exists(fileName))
                                    {
                                        notTranslatedDoc.Add(fileName);
                                    }
                                }
                                else if (fileName.Contains("file"))
                                {
                                    fileName = fileName.Replace("file:///", "");
                                    if (File.Exists(fileName))
                                    {
                                        notTranslatedDoc.Add(fileName);
                                    }
                                }
                                else
                                {
                                    fileName = Path.GetDirectoryName(inputFile) + "\\" + Path.GetFileName(fileName);
                                    if (File.Exists(fileName))
                                    {
                                        notTranslatedDoc.Add(fileName);
                                    }
                                }
                            }
                        }
                    }
                }
                packDoc.Close();
            } catch (Exception e) {
                //MessageBox.Show(this.resourceManager.GetString("TranslationFailed") + "\n" + this.resourceManager.GetString("WellDaisyFormat") + "\n" + " \"" + Path.GetFileName(tempInputFile) + "\"\n" + validationErrorMsg + "\n" + "Problem is:" + "\n" + e.Message + "\n", "SaveAsDAISY", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// Sets the document theme
        /// </summary>
        /// <param name="theme">Theme package</param>
        public static OpenXmlPowerToolsDocument SetTheme(WmlDocument doc, OpenXmlPowerToolsDocument themeDoc)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    using (OpenXmlMemoryStreamDocument themeStream = new OpenXmlMemoryStreamDocument(themeDoc))
                        using (Package theme = themeStream.GetPackage())
                        {
                            // Gets the theme manager part
                            PackageRelationship themeManagerRelationship =
                                theme.GetRelationshipsByType(mainDocumentRelationshipType).FirstOrDefault();
                            if (themeManagerRelationship != null)
                            {
                                PackagePart themeManagerPart = theme.GetPart(themeManagerRelationship.TargetUri);

                                // Gets the theme main part
                                PackageRelationship themeRelationship =
                                    themeManagerPart.GetRelationshipsByType(themeRelationshipType).FirstOrDefault();
                                if (themeRelationship != null)
                                {
                                    PackagePart themePart        = theme.GetPart(themeRelationship.TargetUri);
                                    XDocument   newThemeDocument = XDocument.Load(XmlReader.Create(themePart.GetStream(FileMode.Open, FileAccess.Read)));

                                    // Removes existing theme part from document
                                    if (document.MainDocumentPart.ThemePart != null)
                                    {
                                        document.MainDocumentPart.DeletePart(document.MainDocumentPart.ThemePart);
                                    }

                                    // Creates a new theme part
                                    ThemePart documentThemePart = document.MainDocumentPart.AddNewPart <ThemePart>();

                                    var embeddedItems =
                                        newThemeDocument
                                        .Descendants()
                                        .Attributes(relationshipns + "embed");
                                    foreach (PackageRelationship imageRelationship in themePart.GetRelationships())
                                    {
                                        // Adds an image part to the theme part and stores contents inside
                                        PackagePart imagePart    = theme.GetPart(imageRelationship.TargetUri);
                                        ImagePart   newImagePart =
                                            documentThemePart.AddImagePart(GetImagePartType(imagePart.ContentType));
                                        newImagePart.FeedData(imagePart.GetStream(FileMode.Open, FileAccess.Read));

                                        // Updates relationship references into the theme XDocument
                                        XAttribute relationshipAttribute = embeddedItems.FirstOrDefault(e => e.Value == imageRelationship.Id);
                                        if (relationshipAttribute != null)
                                        {
                                            relationshipAttribute.Value = documentThemePart.GetIdOfPart(newImagePart);
                                        }
                                    }
                                    documentThemePart.PutXDocument(newThemeDocument);
                                }
                            }
                        }
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
Ejemplo n.º 26
0
        public void Sanitize(string packagePath)
        {
            try
            {
                //Open the package
                using (Package package = Package.Open(packagePath, FileMode.Open, FileAccess.ReadWrite))
                {

                    //Get the document part
                    Uri uriDocument = new Uri(docUri, UriKind.Relative);
                    PackagePart documentPart = package.GetPart(uriDocument);

                    //Load the document part into a stream
                    Stream partStream = documentPart.GetStream(FileMode.Open, FileAccess.ReadWrite);

                    //Add the namespace manager to reference the Word namespace
                    NameTable nameTable = new NameTable();
                    XmlNamespaceManager manager = new XmlNamespaceManager(nameTable);
                    manager.AddNamespace("w", wordSpace);

                    //Create a temporary XML document from the stream
                    //so we can manipulate the XML elements
                    XmlDocument tempDoc = new XmlDocument(nameTable);
                    tempDoc.Load(partStream);

                    //Remove deleted text from temporary XML document
                    XmlNodeList delNodes = tempDoc.SelectNodes("//w:del", manager);
                    foreach (XmlNode delNode in delNodes)
                    {
                        delNode.ParentNode.RemoveChild(delNode);
                    }

                    //Promote the inserted text in temporary XMl document
                    //so it appears normally in the Word document
                    XmlNodeList insNodes = tempDoc.SelectNodes("//w:ins", manager);
                    foreach (XmlNode insNode in insNodes)
                    {
                        foreach (XmlNode childNode in insNode.ChildNodes)
                        {
                            insNode.ParentNode.InsertBefore(childNode, insNode);
                        }

                        insNode.ParentNode.RemoveChild(insNode);
                    }

                    //Remove comments text from temporary XML document
                    //Must remove several different elements to accomplish this
                    XmlNodeList commentStartNodes = tempDoc.SelectNodes(
                                                    "//w:commentRangeStart", manager);
                    foreach (XmlNode commentStartNode in commentStartNodes)
                    {
                        commentStartNode.ParentNode.RemoveChild(commentStartNode);
                    }

                    XmlNodeList commentEndNodes = tempDoc.SelectNodes(
                                                  "//w:commentRangeEnd", manager);
                    foreach (XmlNode commentEndNode in commentEndNodes)
                    {
                        commentEndNode.ParentNode.RemoveChild(commentEndNode);
                    }

                    XmlNodeList commentRefNodes = tempDoc.SelectNodes(
                                                  "//w:commentReference", manager);
                    foreach (XmlNode commentRefNode in commentRefNodes)
                    {
                        commentRefNode.ParentNode.RemoveChild(commentRefNode);
                    }

                    //Save the temporary XMl document changes back to the document part
                    documentPart.GetStream().SetLength(0);
                    tempDoc.Save(documentPart.GetStream());

                    //delete the relationship with the comments part
                    Uri uriComments = new Uri("/word/comments.xml", UriKind.Relative);
                    PackagePart commentsPart = package.GetPart(uriComments);

                    PackageRelationshipCollection relationships = documentPart.GetRelationships();

                    foreach (PackageRelationship relationship in relationships)
                    {
                        if (relationship.TargetUri.ToString() == "comments.xml")
                        {
                            documentPart.DeleteRelationship(relationship.Id);
                            break;
                        }
                    }

                    //Delete comments part from package
                    package.DeletePart(uriComments);

                    //Save the package changes
                    package.Flush();
                    package.Close();

                }
            }
            catch (Exception x)
            {
                LogMessage(x.Message, EventLogEntryType.Error);
            }
        }