Example #1
0
 private static void AddFileToZip(string zipFilename, string fileToAdd)
 {
     using (Package package = Package.Open(zipFilename, FileMode.OpenOrCreate))
     {
         Uri partUri = PackUriHelper.CreatePartUri(new Uri(@".\" + Path.GetFileName(fileToAdd), UriKind.Relative));
         if (package.PartExists(partUri))
         {
             package.DeletePart(partUri);
         }
         PackagePart part = package.CreatePart(partUri, "", CompressionOption.Normal);
         using (FileStream stream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
         {
             using (Stream stream2 = part.GetStream())
             {
                 CopyStream(stream, stream2);
             }
         }
     }
 }
        private static Type GetDocumentType(byte[] bytes)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(bytes, 0, bytes.Length);
                using (Package package = Package.Open(stream, FileMode.Open))
                {
                    PackageRelationship relationship = package.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument").FirstOrDefault();
                    if (relationship == null)
                    {
                        relationship = package.GetRelationshipsByType("http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument").FirstOrDefault();
                    }
                    if (relationship != null)
                    {
                        PackagePart part = package.GetPart(PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri));
                        switch (part.ContentType)
                        {
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml":
                        case "application/vnd.ms-word.document.macroEnabled.main+xml":
                        case "application/vnd.ms-word.template.macroEnabledTemplate.main+xml":
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml":
                            return(typeof(WordprocessingDocument));

                        case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml":
                        case "application/vnd.ms-excel.sheet.macroEnabled.main+xml":
                        case "application/vnd.ms-excel.template.macroEnabled.main+xml":
                        case "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml":
                            return(typeof(SpreadsheetDocument));

                        case "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml":
                        case "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml":
                        case "application/vnd.ms-powerpoint.template.macroEnabled.main+xml":
                        case "application/vnd.ms-powerpoint.addin.macroEnabled.main+xml":
                        case "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml":
                        case "application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml":
                            return(typeof(PresentationDocument));
                        }
                        return(typeof(Package));
                    }
                    return(null);
                }
            }
        }
Example #3
0
        private void UpdateSharedStringsXml()
        {
            PackagePart stringPart;

            if (_package.Package.PartExists(SharedStringsUri))
            {
                stringPart = _package.Package.GetPart(SharedStringsUri);
            }
            else
            {
                stringPart = _package.Package.CreatePart(SharedStringsUri, @"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml", _package.Compression);
                Part.CreateRelationship(PackUriHelper.GetRelativeUri(WorkbookUri, SharedStringsUri), TargetMode.Internal, ExcelPackage.schemaRelationships + "/sharedStrings");
            }

            StreamWriter sw = new StreamWriter(stringPart.GetStream(FileMode.Create, FileAccess.Write));

            sw.Write("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" count=\"{0}\" uniqueCount=\"{0}\">", _sharedStrings.Count);
            foreach (string t in _sharedStrings.Keys)
            {
                SharedStringItem ssi = _sharedStrings[t];
                if (ssi.isRichText)
                {
                    sw.Write("<si>");
                    ExcelEncodeString(sw, t);
                    sw.Write("</si>");
                }
                else
                {
                    if (t.Length > 0 && (t[0] == ' ' || t[t.Length - 1] == ' ' || t.Contains("  ") || t.Contains("\t")))
                    {
                        sw.Write("<si><t xml:space=\"preserve\">");
                    }
                    else
                    {
                        sw.Write("<si><t>");
                    }
                    ExcelEncodeString(sw, SecurityElement.Escape(t));
                    sw.Write("</t></si>");
                }
            }
            sw.Write("</sst>");
            sw.Flush();
        }
Example #4
0
        /// <summary>
        /// Initializes a new instance of the HomeScreenViewModel class that loads model content from the given Uri
        /// </summary>
        /// <param name="modelContentUri">Uri to the collection of AttractScreenImage models to be loaded</param>
        public HomeScreenViewModel(Uri modelContentUri)
            : base()
        {
            this.LoadModels(PackUriHelper.CreatePackUri(DefaultAttractScreenModelContent));
            this.CurrentImage = this.Images[this.currentIndex];

            this.experienceSelected = new RelayCommand <RoutedEventArgs>(this.OnExperienceSelected);

            using (Stream experienceModelsStream = Application.GetResourceStream(modelContentUri).Stream)
            {
                var experiences = XamlServices.Load(experienceModelsStream) as IList <ExperienceOptionModel>;
                if (null == experiences)
                {
                    throw new InvalidDataException();
                }

                this.Experiences = new ObservableCollection <ExperienceOptionModel>(experiences);
            }
        }
Example #5
0
        /// <summary>
        /// Loads the collection of AttractScreenImage models and transforms them to a collection of images.
        /// </summary>
        /// <param name="modelContentUri">Uri to the collection of AttractScreenImage models to be loaded</param>
        protected void LoadModels(Uri modelContentUri)
        {
            //using (Stream attractModelsStream = Application.GetResourceStream(modelContentUri).Stream)
            //{
            //    this.images = new ObservableCollection<Image>(
            //        from imageModel in XamlServices.Load(attractModelsStream) as IList<AttractImageModel>
            //        select new Image() { Source = new BitmapImage(imageModel.ImageUri) });
            //}

            string[] myImages = Directory.GetFiles("Content/myImages");

            foreach (var image in myImages)
            {
                Image tmpImage = new Image();
                tmpImage.Source = new BitmapImage(PackUriHelper.CreatePackUri(image));

                this.images.Add(tmpImage);
            }
        }
Example #6
0
        /// <summary>
        /// Create an AMLX file with the aml file as string input
        /// </summary>
        /// <param name="caex">the complete aml file as a string</param>
        /// <param name="filename">the path to the original gsdml/iodd file</param>
        /// <returns>the result message as a string</returns>
        private string createAMLXFromString(string caex, string filename)
        {
            // create the CAEXDocument from byte string
            byte[]       bytearray = System.Text.Encoding.Unicode.GetBytes(caex);
            CAEXDocument document  = CAEXDocument.LoadFromBinary(bytearray);

            // create the amlx file
            string name = Path.GetFileNameWithoutExtension(filename);

            AutomationMLContainer amlx;

            if (name.Contains(".amlx"))
            {
                amlx = new AutomationMLContainer(".\\modellingwizard\\" + name, FileMode.Create);
            }
            else
            {
                amlx = new AutomationMLContainer(".\\modellingwizard\\" + name + ".amlx", FileMode.Create);
            }

            // create the aml package path
            Uri partUri = PackUriHelper.CreatePartUri(new Uri("/" + name + "-root.aml", UriKind.Relative));

            // create a temp aml file
            string path = Path.GetTempFileName();

            document.SaveToFile(path, true);

            // copy the new aml into the package
            PackagePart root = amlx.AddRoot(path, partUri);

            // copy the original file into the package
            Uri gsdURI     = new Uri(new FileInfo(filename).Name, UriKind.Relative);
            Uri gsdPartURI = PackUriHelper.CreatePartUri(gsdURI);

            amlx.AddAnyContent(root, filename, gsdPartURI);

            amlx.Save();
            amlx.Close();

            return("Sucessfully imported device!\nCreated File " + Path.GetFullPath(".\\modellingwizard\\" + name + ".amlx"));
        }
Example #7
0
        /// <summary>
        /// 将文件夹及其子文件夹添加到包
        /// </summary>
        /// <param name="folderName">要添加的目录</param>
        /// <param name="compressedFileName">要创建的包路径</param>
        /// <param name="overrideExisting">覆盖已经存在的包</param>
        /// <returns></returns>
        public static int PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
        {
            //去掉目录路径末尾的\
            folderName = folderName.EndsWith(@"\") ? folderName.Remove(folderName.Length - 1) : folderName;

            int intR = 0;

            if (Directory.Exists(folderName) && (overrideExisting || !File.Exists(compressedFileName)))
            {
                try
                {
                    using (Package package = Package.Open(compressedFileName, FileMode.Create))
                    {
                        //获取压缩路径下的所有子目录和子文件
                        var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
                        foreach (string fileName in fileList)
                        {
                            //获取子目录和子文件夹的相对路径
                            string pathInPackage = Path.GetDirectoryName(fileName)?.Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);
                            //文件/文件夹的url
                            Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
                            //添加文件
                            PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
                            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                            {
                                if (packagePartDocument != null)
                                {
                                    fileStream.CopyTo(packagePartDocument.GetStream());
                                }
                            }
                        }
                    }
                    intR = 1;
                }
                catch (Exception e)
                {
                    intR = -1;
                    Console.WriteLine(e);
                }
            }
            return(intR);
        }
Example #8
0
        private void CopyPivotTable(ExcelWorksheet Copy, ExcelWorksheet added)
        {
            string prevName = "";

            foreach (var tbl in Copy.PivotTables)
            {
                string xml = tbl.PivotTableXml.OuterXml;
                int    Id  = _pck.Workbook._nextPivotTableID++;

                string name;
                if (prevName == "")
                {
                    name = Copy.PivotTables.GetNewTableName();
                }
                else
                {
                    int ix = int.Parse(prevName.Substring(10)) + 1;
                    name = string.Format("PivotTable{0}", ix);
                    while (_pck.Workbook.ExistsPivotTableName(name))
                    {
                        name = string.Format("PivotTable{0}", ++ix);
                    }
                }
                prevName = name;
                XmlDocument xmlDoc = new XmlDocument();
                Copy.Save();    //Save the worksheet first
                xmlDoc.LoadXml(xml);
                //xmlDoc.SelectSingleNode("//d:table/@id", tbl.NameSpaceManager).Value = Id.ToString();
                xmlDoc.SelectSingleNode("//d:pivotTableDefinition/@name", tbl.NameSpaceManager).Value = name;
                xml = xmlDoc.OuterXml;

                var          uriTbl    = new Uri(string.Format("/xl/pivotTables/pivotTable{0}.xml", Id), UriKind.Relative);
                var          part      = _pck.Package.CreatePart(uriTbl, ExcelPackage.schemaPivotTable, _pck.Compression);
                StreamWriter streamTbl = new StreamWriter(part.GetStream(FileMode.Create, FileAccess.Write));
                streamTbl.Write(xml);
                streamTbl.Close();

                //create the relationship and add the ID to the worksheet xml.
                added.Part.CreateRelationship(PackUriHelper.ResolvePartUri(added.WorksheetUri, uriTbl), TargetMode.Internal, ExcelPackage.schemaRelationships + "/pivotTable");
                part.CreateRelationship(PackUriHelper.ResolvePartUri(tbl.Relationship.SourceUri, tbl.CacheDefinition.Relationship.TargetUri), tbl.CacheDefinition.Relationship.TargetMode, tbl.CacheDefinition.Relationship.RelationshipType);
            }
        }
Example #9
0
        private static PackagePart GetPackagePart(Package filePackage,
                                                  string relationship)
        {
            // Use the namespace that describes the relationship
            // to get the relationship.
            PackageRelationship packageRel =
                filePackage.GetRelationshipsByType(relationship).FirstOrDefault();
            PackagePart part = null;

            // If the Visio file package contains this type of relationship with
            // one of its parts, return that part.
            if (packageRel != null)
            {
                // Clean up the URI using a helper class and then get the part.
                Uri docUri = PackUriHelper.ResolvePartUri(
                    new Uri("/", UriKind.Relative), packageRel.TargetUri);
                part = filePackage.GetPart(docUri);
            }
            return(part);
        }
Example #10
0
 private void CheckUri(string localName, string attr)
 {
     if (!object.ReferenceEquals(attr, _lastAttr))      // Check for same string object, not for equality!
     {
         _lastAttr = attr;
         string [] uris = _schema.ExtractUriFromAttr(localName, attr);
         if (uris != null)
         {
             foreach (string uriAttr in uris)
             {
                 if (uriAttr.Length > 0)
                 {
                     Uri targetUri    = PackUriHelper.ResolvePartUri(_baseUri, new Uri(uriAttr, UriKind.Relative));
                     Uri absTargetUri = PackUriHelper.Create(_packageUri, targetUri);
                     _loader.UriHitHandler(_node, absTargetUri);
                 }
             }
         }
     }
 }
Example #11
0
 /// <summary>
 /// Opens the read.
 /// </summary>
 /// <typeparam name="TResult"></typeparam>
 /// <param name="packagePath">The package path.</param>
 /// <param name="relationshipType">  The System.IO.Packaging.PackageRelationship.RelationshipType to match and return in the collection..</param>
 /// <param name="reader">The reader.</param>
 /// <returns>The return value of the method</returns>
 internal static TResult OpenRead <TResult>(FileInfo packagePath, string relationshipType, Func <Stream, TResult> reader)
 {
     using (Package package = Package.Open(packagePath.FullName, FileMode.Open, FileAccess.Read))
     {
         // Get the Package Relationships and look for the Document part based on the RelationshipType
         Uri uriDocumentTarget            = null;
         PackageRelationship relationship = package.GetRelationshipsByType(relationshipType).FirstOrDefault();
         if (relationship == null)
         {
             throw new ArgumentException("the package does not contain the requested part");
         }
         // Resolve the Relationship Target Uri so the Document Part can be retrieved.
         uriDocumentTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
         PackagePart _documentPart = package.GetPart(uriDocumentTarget); // Open the Part
         TResult     _rslt         = default(TResult);
         using (Stream _strm = _documentPart.GetStream(FileMode.Open, FileAccess.Read))
             _rslt = reader(_strm); //let read the content by the caller
         return(_rslt);
     }
 }
Example #12
0
        public static void Save(string packageName, string data, string xmlRamData)
        {
            Uri partUriData   = PackUriHelper.CreatePartUri(new Uri(@"Content\data.cf", UriKind.Relative));
            Uri partUriRamDef = PackUriHelper.CreatePartUri(new Uri(@"Content\rd.xx", UriKind.Relative));

            using (Package package = Package.Open(packageName, FileMode.Create))
            {
                // Add the Document part to the Package
                PackagePart packagePartDocument = package.CreatePart(partUriRamDef, System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum);
                using (System.IO.MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xmlRamData)))
                {
                    CopyStream(stream, packagePartDocument.GetStream());
                }
                PackagePart packagePartData = package.CreatePart(partUriData, System.Net.Mime.MediaTypeNames.Text.Plain, CompressionOption.Maximum);
                using (System.IO.MemoryStream stream = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(data)))
                {
                    CopyStream(stream, packagePartData.GetStream());
                }
            }
        }
 // Token: 0x06008483 RID: 33923 RVA: 0x00248558 File Offset: 0x00246758
 private void CheckUri(string localName, string attr)
 {
     if (attr != this._lastAttr)
     {
         this._lastAttr = attr;
         string[] array = this._schema.ExtractUriFromAttr(localName, attr);
         if (array != null)
         {
             foreach (string text in array)
             {
                 if (text.Length > 0)
                 {
                     Uri partUri = PackUriHelper.ResolvePartUri(this._baseUri, new Uri(text, UriKind.Relative));
                     Uri uri     = PackUriHelper.Create(this._packageUri, partUri);
                     this._loader.UriHitHandler(this._node, uri);
                 }
             }
         }
     }
 }
Example #14
0
        public void ProjectFileIsAdded()
        {
            var packageBuilder = _container.Resolve <IPackageBuilder>();
            var stream         = BuildHelloWorld(packageBuilder);

            string content;

            using (var sourceStream = GetType().Assembly.GetManifestResourceStream(GetType(), "Hello.World.csproj.txt")) {
                content = new StreamReader(sourceStream).ReadToEnd();
            }

            var package     = Package.Open(stream);
            var projectUri  = PackUriHelper.CreatePartUri(new Uri("/Content/Modules/Hello.World/Hello.World.csproj", UriKind.Relative));
            var projectPart = package.GetPart(projectUri);

            using (var projectStream = projectPart.GetStream()) {
                var projectContent = new StreamReader(projectStream).ReadToEnd();
                Assert.That(projectContent, Is.EqualTo(content));
            }
        }
Example #15
0
        public override void Rename()
        {
            string str = "/";

            for (VsixFileNode parent = this.Parent; parent != null && !(parent is VsixPackageNode); parent = parent.Parent)
            {
                str = "/" + parent.Name + str;
            }
            Uri partUri = PackUriHelper.CreatePartUri(new Uri(str + this.Name, UriKind.RelativeOrAbsolute));

            if (this.Part.Package.PartExists(partUri))
            {
                return;
            }
            PackagePart part = this.Part.Package.CreatePart(partUri, this.Part.ContentType);

            Utilities.CopyStream(this.Part.GetStream(), part.GetStream(FileMode.Open, FileAccess.Write));
            this.Part.Package.DeletePart(this.Part.Uri);
            this.Part = part;
        }
Example #16
0
 public void AddFile(string fileToAdd)
 {
     using (var zip = System.IO.Packaging.Package.Open(ZipFileName, FileMode.OpenOrCreate))
     {
         var destFilename = ".\\" + Path.GetFileName(fileToAdd);
         var uri          = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
         if (zip.PartExists(uri))
         {
             zip.DeletePart(uri);
         }
         var part = zip.CreatePart(uri, "", CompressionOption.Normal);
         using (var fileStream = ZipStreamProvider.GetStream(fileToAdd))
         {
             using (var dest = part.GetStream())
             {
                 CopyStream(fileStream, dest);
             }
         }
     }
 }
Example #17
0
 public static void AddFileToZip(string zipFilename, string fileToAdd)
 {
     using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
     {
         string destFilename = ".\\" + Path.GetFileName(fileToAdd);
         Uri    uri          = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
         if (zip.PartExists(uri))
         {
             zip.DeletePart(uri);
         }
         PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
         using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
         {
             using (Stream dest = part.GetStream())
             {
                 CopyStream(fileStream, dest);
             }
         }
     }
 }
Example #18
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);
                    }
                }
            }
        }
Example #19
0
 internal static void AddFileToZip(string zipFilename, string fileToAdd, string storeAsName = null)
 {
     using (var zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
     {
         string destFilename = (String.IsNullOrWhiteSpace(storeAsName) ? fileToAdd : storeAsName);
         var    uri          = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
         if (zip.PartExists(uri))
         {
             zip.DeletePart(uri);
         }
         var part = zip.CreatePart(uri, "", CompressionOption.Normal);
         using (var fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
         {
             using (var outputStream = part.GetStream())
             {
                 CopyStream(fileStream, outputStream);
             }
         }
     }
 }
Example #20
0
        internal ExcelVbaProject(ExcelWorkbook wb)
        {
            _wb        = wb;
            _pck       = _wb._package.Package;
            References = new ExcelVbaReferenceCollection();
            Modules    = new ExcelVbaModuleCollection(this);
            var rel = _wb.Part.GetRelationshipsByType(schemaRelVba).FirstOrDefault();

            if (rel != null)
            {
                Uri  = PackUriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri);
                Part = _pck.GetPart(Uri);
                GetProject();
            }
            else
            {
                Lcid = 0;
                Part = null;
            }
        }
Example #21
0
 private static void AddFileToZip(string zipFilename, string fileToAdd, string directory, CompressionOption compression)
 {
     using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
     {
         string destFilename = "." + fileToAdd.Substring(directory.Length);
         Uri    uri          = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
         if (zip.PartExists(uri))
         {
             zip.DeletePart(uri);
         }
         PackagePart part = zip.CreatePart(uri, "", compression);
         using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
         {
             using (Stream dest = part.GetStream())
             {
                 CopyStream(fileStream, dest);
             }
         }
     }
 }
Example #22
0
        public void ExportModel(Model.Model model)
        {
            Uri uriModel = PackUriHelper.CreatePartUri(new Uri(VpaxFormat.DAXMODEL, UriKind.Relative));

            using (TextWriter tw = new StreamWriter(this.Package.CreatePart(uriModel, "application/json", CompressionOption.Maximum).GetStream(), Encoding.UTF8))
            {
                tw.Write(
                    JsonConvert.SerializeObject(
                        model,
                        Formatting.Indented,
                        new JsonSerializerSettings
                {
                    PreserveReferencesHandling = PreserveReferencesHandling.All,
                    ReferenceLoopHandling      = ReferenceLoopHandling.Serialize
                }
                        )
                    );
                tw.Close();
            }
        }
Example #23
0
 static void AddFileToZip(string zipFilename, string fileToAdd)
 {
     using (var zip = Package.Open(zipFilename, FileMode.OpenOrCreate))
     {
         var destFilename = @".\" + Path.GetFileName(fileToAdd);
         var uri          = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
         if (zip.PartExists(uri))
         {
             zip.DeletePart(uri);
         }
         var part = zip.CreatePart(uri, "", CompressionOption.Normal);
         using (var source = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
         {
             using (var destination = part.GetStream())
             {
                 CopyStream(source, destination);
             }
         }
     }
 }
Example #24
0
        private static void TryUpdatePackageId(ZipPackage package, string signedPackageId)
        {
            // Update package id
            var manifestRelationType = package.GetRelationshipsByType("http://schemas.microsoft.com/packaging/2010/07/manifest").SingleOrDefault();

            if (manifestRelationType != null)
            {
                var manifestPart = package.GetPart(manifestRelationType.TargetUri);
                var manifest     = Manifest.ReadFrom(manifestPart.GetStream(), NullPropertyProvider.Instance, false);
                manifest.Metadata.Id = signedPackageId;

                package.DeleteRelationship(manifestRelationType.Id);
                package.DeletePart(manifestPart.Uri);

                Uri uri             = PackUriHelper.CreatePartUri(new Uri(string.Format("/{0}.nuspec", signedPackageId), UriKind.Relative));
                var newManifestPart = package.CreatePart(uri, "application/octet", CompressionOption.Maximum);
                manifest.Save(newManifestPart.GetStream(FileMode.Create));
                package.CreateRelationship(uri, TargetMode.Internal, "http://schemas.microsoft.com/packaging/2010/07/manifest");
            }
        }
Example #25
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);
        }
Example #26
0
        public static bool ExtrahovatPoznamkyPodCarouDoSouboru(string strDocx, string strVystup, bool blnFormatovatOdsazeni)
        {
            using (FileStream fs = new FileStream(strDocx, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    using (Package wdPackage = Package.Open(sr.BaseStream))
                    {
                        PackagePart documentPart = null;
                        PackagePart footnotePart = null;
                        Uri         documentUri  = null;

                        foreach (PackageRelationship relationship in wdPackage.GetRelationshipsByType(RelDocumentRelationshipType))
                        {
                            documentUri  = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
                            documentPart = wdPackage.GetPart(documentUri);
                            break;                             //only one part
                        }

                        if (documentPart != null)
                        {
                            foreach (PackageRelationship relationship in documentPart.GetRelationshipsByType(RelFootnotesRelationshipType))
                            {
                                Uri footnoteUri = PackUriHelper.ResolvePartUri(documentUri, relationship.TargetUri);
                                footnotePart = wdPackage.GetPart(footnoteUri);
                                break;                                 //only one part
                            }
                        }

                        if (footnotePart == null)
                        {
                            wdPackage.Close();
                            return(false);
                        }
                        UlozitPackagePart(strVystup, blnFormatovatOdsazeni, footnotePart);
                        wdPackage.Close();
                    }
                }
            }
            return(true);
        }
Example #27
0
        private void WriteSharedStringsXml(Package package)
        {
            int count = _sheets.Sum(x => x.WordCount);

            Uri uri = PackUriHelper.CreatePartUri(new Uri("xl/sharedStrings.xml", UriKind.Relative));

            //Create the workbook part.
            PackagePart part = package.CreatePart(uri, NS_SHARED_STRINGS, CompressionOption.Maximum);

            using (var writer = XmlWriter.Create(part.GetStream(FileMode.Create, FileAccess.Write), xmlSettings)) {
                writer.WriteStartDocument(true);

                writer.WriteStartElement("sst", SCHEMA_MAIN);
                writer.WriteAttributeString("count", count.ToString(NumberFormatInfo.InvariantInfo));
                writer.WriteAttributeString(
                    "uniqueCount",
                    _sharedStrings.Count.ToString(NumberFormatInfo.InvariantInfo));
                // writer.WriteAttributeString("xmlns", SCHEMA_MAIN);

                foreach (var s in _sharedStrings.OrderBy(x => x.Value))
                {
                    writer.WriteStartElement("si");
                    writer.WriteStartElement("t");
                    writer.WriteString(s.Key);
                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }

            //Create the relationship for the workbook part.
            Uri         bookUri  = PackUriHelper.CreatePartUri(new Uri("xl/workbook.xml", UriKind.Relative));
            PackagePart bookPart = package.GetPart(bookUri);

            bookPart.CreateRelationship(
                uri,
                TargetMode.Internal,
                RELATIONSHIP_SHAREDSTRINGS,
                "rId" + (_sheets.Count + 1));
        }
        public void CreatePackage(string sourceDirectory, string packagePath)
        {
            var foundTiles = pathProvider.GetTiles(sourceDirectory, extension);

            foreach (var foundTile in foundTiles)
            {
                Cache.Add(foundTile.ID, true);
            }

            string shortExtension = "image/" + extension.TrimStart('.');

            const int flushCnt = 20;
            int       counter  = 0;

            using (Package package = Package.Open(packagePath, FileMode.Create))
            {
                WriteCache(package);

                foreach (var foundTile in foundTiles)
                {
                    Uri         partUri = PackUriHelper.CreatePartUri(new Uri(foundTile.Path, UriKind.Relative));
                    PackagePart part    = package.CreatePart(partUri, shortExtension, CompressionOption.Fast);

                    using (FileStream fs = new FileStream(Path.Combine(sourceDirectory, foundTile.Path), FileMode.Open, FileAccess.Read))
                    {
                        CopyStream(fs, part.GetStream());
                    }

                    package.CreateRelationship(part.Uri, TargetMode.Internal, D3AssemblyConstants.DefaultXmlNamespace);

                    counter++;
                    if (counter % flushCnt == 0)
                    {
                        counter = 0;
                        package.Flush();
                    }

                    Console.WriteLine(foundTile.Path);
                }
            }
        }
        private void CreateXml(ExcelPackage pck)
        {
            var  commentParts = Worksheet.Part.GetRelationshipsByType(ExcelPackage.schemaComment);
            bool isLoaded     = false;

            CommentXml = new XmlDocument();
            foreach (var commentPart in commentParts)
            {
                Uri  = PackUriHelper.ResolvePartUri(commentPart.SourceUri, commentPart.TargetUri);
                Part = pck.Package.GetPart(Uri);
                XmlHelper.LoadXmlSafe(CommentXml, Part.GetStream());
                RelId    = commentPart.Id;
                isLoaded = true;
            }
            //Create a new document
            if (!isLoaded)
            {
                CommentXml.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><comments xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"><authors /><commentList /></comments>");
                Uri = null;
            }
        }
Example #30
0
        private static void ZipFilesToStream(Stream destination,
                                             IEnumerable <string> files, CompressionOption compressionLevel)
        {
            using (Package package = Package.Open(destination, FileMode.Create)) {
                foreach (string path in files)
                {
                    // fix for white spaces in file names (by ErrCode)
                    Uri fileUri = PackUriHelper.CreatePartUri(new Uri(@"/" +
                                                                      Path.GetFileName(path), UriKind.Relative));

                    string contentType = @"data/" + ZipHelper.GetFileExtentionName(path);

                    using (Stream zipStream =
                               package.CreatePart(fileUri, contentType, compressionLevel).GetStream()) {
                        using (FileStream fileStream = new FileStream(path, FileMode.Open)) {
                            fileStream.CopyTo(zipStream);
                        }
                    }
                }
            }
        }