CreatePart() public method

public CreatePart ( Uri partUri, string contentType ) : PackagePart
partUri System.Uri
contentType string
return PackagePart
示例#1
0
        private void ZipDirectory(string SourceFolderPath, Package package,int deviceType)
        {
            DirectoryInfo dir = new DirectoryInfo(SourceFolderPath);
            FileInfo[] files=dir.GetFiles();
            foreach (FileInfo fi in files)
            {                
                if ((".tdb".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && deviceType == 1) || (".dat".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && deviceType == 2)
                    || (".doc".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) && deviceType == 2) || ".crd".Equals(fi.Extension, StringComparison.OrdinalIgnoreCase) || deviceType == 3)
                {
                    string relativePath = fi.FullName.Replace(SourceFolderPath, string.Empty);
                    relativePath = relativePath.Replace("\\", "/");
                    Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(relativePath, UriKind.Relative));

                    //resourcePath="Resource\Image.jpg"
                    //Uri partUriResource = PackUriHelper.CreatePartUri(new Uri(resourcePath, UriKind.Relative));

                    PackagePart part = package.CreatePart(partUriDocument, System.Net.Mime.MediaTypeNames.Application.Zip);
                    using (FileStream fs = fi.OpenRead())
                    {
                        using (Stream partStream = part.GetStream())
                        {
                            CopyStream(fs, partStream);
                            fs.Close();
                            partStream.Close();
                        }
                    }
                }                

            }
            DirectoryInfo[] directories = dir.GetDirectories();
            foreach (DirectoryInfo subDi in directories)
            {
                ZipDirectory(SourceFolderPath, package, deviceType);
            }
        }
示例#2
0
        /// <summary>
        /// CertificatePart constructor
        /// </summary>
        internal CertificatePart(System.IO.Packaging.Package container, Uri partName)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            if (partName == null)
            {
                throw new ArgumentNullException("partName");
            }

            partName = PackUriHelper.ValidatePartUri(partName);

            // create if not found
            if (container.PartExists(partName))
            {
                // open the part
                _part = container.GetPart(partName);

                // ensure the part is of the expected type
                if (_part.ValidatedContentType().AreTypeAndSubTypeEqual(_certificatePartContentType) == false)
                {
                    throw new FileFormatException(SR.CertificatePartContentTypeMismatch);
                }
            }
            else
            {
                // create the part
                _part = container.CreatePart(partName, _certificatePartContentType.ToString());
            }
        }
        void AddContent(Package package, PackageDefinition manifest, Uri partUri, string file)
        {
            var part =
                    package.CreatePart(
                        PackUriHelper.CreatePartUri(partUri), System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum);

                using (var partStream = part.GetStream())
                using (var fileStream = fileSystem.OpenFile(file, FileMode.Open))
                {
                    fileStream.CopyTo(partStream);
                    partStream.Flush();
                    fileStream.Position = 0;
                    var hashAlgorithm = new SHA256Managed();
                    hashAlgorithm.ComputeHash(fileStream);
                    manifest.Contents.Add(new ContentDefinition
                    {
                        Name = partUri.ToString(),
                        Description =
                            new ContentDescription
                            {
                                DataStorePath = partUri,
                                LengthInBytes = (int) fileStream.Length,
                                HashAlgorithm = IntegrityCheckHashAlgorithm.Sha256,
                                Hash = Convert.ToBase64String(hashAlgorithm.Hash)
                            }
                    });
                }
        }
示例#4
0
        /// <summary>
        /// Creates a new instance of the ExcelPackage class based on a existing file or creates a new file. 
        /// </summary>
        /// <param name="newFile">If newFile exists, it is opened.  Otherwise it is created from scratch.</param>
        private ExcelPackage(FileInfo newFile)
        {
            _outputFolderPath = newFile.DirectoryName;
            if (newFile.Exists)
            {
                // open the existing package
                _package = Package.Open(newFile.FullName, FileMode.Open, FileAccess.ReadWrite);
            }
            else
            {
                // create a new package and add the main workbook.xml part
                _package = Package.Open(newFile.FullName, FileMode.Create, FileAccess.ReadWrite);

                // save a temporary part to create the default application/xml content type
                var uriDefaultContentType = new Uri("/default.xml", UriKind.Relative);
                var partTemp = _package.CreatePart(uriDefaultContentType, "application/xml");

                var workbook = Workbook.WorkbookXml; // this will create the workbook xml in the package

                // create the relationship to the main part
                _package.CreateRelationship(Workbook.WorkbookUri,
                                            TargetMode.Internal,
                                            schemaRelationships + "/officeDocument");

                // remove the temporary part that created the default xml content type
                _package.DeletePart(uriDefaultContentType);
            }
        }
示例#5
0
 public static void AddFile(Package result,string baseFolder,string relativePath,CompressionOption compressionOption)
 {
     FileInfo f = new FileInfo(baseFolder+relativePath.Replace("/","\\"));
     //f.Extension;
     PackagePart data = result.CreatePart(new Uri(relativePath, UriKind.Relative), GetContentType(f.Name), compressionOption);
     StreamReader reader = new StreamReader(baseFolder+relativePath.Replace("/","\\"));
     WriteAll(data.GetStream(), reader.BaseStream);
     reader.Close();
 }
示例#6
0
 void CreatePart(Package package, string filePath, Stream sourceStream)
 {
     filePath = filePath.Replace(PackageDirectory, "").TrimStart('\\');
     var uri = PackUriHelper.CreatePartUri(new Uri(Uri.EscapeDataString(filePath), UriKind.Relative));
     var packagePart = package.CreatePart(uri, "application/octet", CompressionOption.Maximum);
     using (var stream = packagePart.GetStream())
     {
         sourceStream.CopyTo(stream);
     }
 }
示例#7
0
        private static void CreatePart(Package package, string file, string contentType)
        {
            var part = package.CreatePart(
                new Uri("/" + file, UriKind.Relative), contentType);

            using (var fileStream = new FileStream(
                GetPath(PackagePath + file), FileMode.Open, FileAccess.Read)) {
                CopyStream(fileStream, part.GetStream());
            }
        }
示例#8
0
 private static void AddFileToPackage(Package zip, string f)
 {
     PackagePart p = zip.CreatePart(
         PackUriHelper.CreatePartUri(new Uri(new FileInfo(f).Name, UriKind.RelativeOrAbsolute)), MediaTypeNames.Text.Plain);
     using (var fileStream = new FileStream(f, FileMode.Open, FileAccess.Read))
     {
         CopyStream(fileStream, p.GetStream());
         // zip.CreateRelationship(p.Uri, TargetMode.Internal, f);
     }
 }
        void AddPackageManifest(Package package, PackageDefinition manifest)
        {
            var manifestPartUri = PackUriHelper.CreatePartUri(new Uri("/package.xml", UriKind.Relative));
            var manifestPart = package.CreatePart(manifestPartUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum);
            using (var manifestPartStream = manifestPart.GetStream())
            {
                manifest.ToXml().Save(manifestPartStream);
            }

            package.CreateRelationship(manifestPartUri, TargetMode.External, AzureCloudServiceConventions.CtpFormatPackageDefinitionRelationshipType);
        }
		private void WriteCache(Package package)
		{
			Uri cacheUri = GetPartUri(cacheName);
			PackagePart part = package.CreatePart(cacheUri, MediaTypeNames.Application.Octet, CompressionOption.Fast);

			BinaryFormatter formatter = new BinaryFormatter();
			using (Stream stream = part.GetStream())
			{
				formatter.Serialize(stream, Cache);
			}

			package.CreateRelationship(cacheUri, TargetMode.Internal, D3AssemblyConstants.DefaultXmlNamespace);
		}
示例#11
0
        /// <summary>
        /// Gets the content of the given part.
        /// Shared objects are resolved here.
        /// </summary>
        private static void SavePartContent(System.IO.Packaging.Package package, Uri uri, byte[] content, Dictionary <string, string> sharedObjects)
        {
            // Decide how to store this content
            if (content.Length < 80)
            {
                // Store directly
                var contentPart = package.CreatePart(uri, ContentTypeZip, CompressionOption.Normal);
                using (var contentPartStream = contentPart.GetStream(FileMode.Create, FileAccess.Write))
                {
                    contentPartStream.Write(content, 0, content.Length);
                }
            }
            else
            {
                // Store as shared object
                var hash    = CreateHash(content);
                var hashKey = Hex(hash);

                // Create content part that contains the hash of the shared object.
                var contentPart = package.CreatePart(uri, ContentTypeSharedObject, CompressionOption.NotCompressed);
                using (var contentPartStream = contentPart.GetStream(FileMode.Create, FileAccess.Write))
                {
                    contentPartStream.Write(hash, 0, hash.Length);
                }

                // Does the shared object exists?
                if (!sharedObjects.ContainsKey(hashKey))
                {
                    // Create shared object part
                    var sharedObjectUri = CreateSharedObjectPartUri(hashKey);
                    var objectPart      = package.CreatePart(sharedObjectUri, ContentTypeZip, CompressionOption.Normal);
                    using (var objectPartStream = objectPart.GetStream(FileMode.Create, FileAccess.Write))
                    {
                        objectPartStream.Write(content, 0, content.Length);
                    }
                    sharedObjects[hashKey] = hashKey;
                }
            }
        }
示例#12
0
 void CreatePart(Package package, string entry)
 {
     var filePath = entry.Replace(PackageDirectory, "").TrimStart('\\');
     var segments = filePath.Split(new[] { '/', Path.DirectorySeparatorChar }, StringSplitOptions.None)
                .Select(Uri.EscapeDataString);
     var escapedPath = String.Join("/", segments);
     var uri = PackUriHelper.CreatePartUri(new Uri(escapedPath, UriKind.Relative));
     var packagePart = package.CreatePart(uri, "application/octet", CompressionOption.Maximum);
     using (var inputFileStream = File.OpenRead(entry))
     using (var zipStream = packagePart.GetStream())
     {
         inputFileStream.CopyTo(zipStream);
     }
 }
示例#13
0
        /// <summary>
        ///By package because  ChangeDocumentType not working well
        /// </summary>
        /// <param name="documentStream"></param>
        private void ChangeDocmToDocxUsingPackage(Stream documentStream)
        {
            // Open the document in the stream and replace the custom XML part
            using (System.IO.Packaging.Package packageFile = System.IO.Packaging.Package.Open(documentStream, FileMode.Open, FileAccess.ReadWrite))
            {
                System.IO.Packaging.PackagePart packagePart = null;
                // Find part containing the correct namespace
                foreach (var part in packageFile.GetParts())
                {
                    if (part.ContentType.Equals("application/vnd.ms-word.document.macroEnabled.main+xml", StringComparison.OrdinalIgnoreCase))
                    {
                        packagePart = part;
                        break;
                    }
                }
                if (packagePart != null)
                {
                    using (MemoryStream source = new MemoryStream())
                    {
                        CopyStream(packagePart.GetStream(), source);

                        var saveRelationBeforeDelPart = new List <PackageRelationship>();
                        foreach (var item in packagePart.GetRelationships())
                        {
                            saveRelationBeforeDelPart.Add(item);
                        }

                        Uri uriData = packagePart.Uri;
                        // Delete the existing XML part
                        if (packageFile.PartExists(uriData))
                        {
                            packageFile.DeletePart(uriData);
                        }

                        // Load the custom XML data
                        var pkgprtData = packageFile.CreatePart(uriData, "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", System.IO.Packaging.CompressionOption.SuperFast);

                        source.Position = 0;//reset position
                        CopyStream(source, pkgprtData.GetStream(FileMode.Create));

                        foreach (var copyRel in saveRelationBeforeDelPart)
                        {
                            pkgprtData.CreateRelationship(copyRel.TargetUri, copyRel.TargetMode, copyRel.RelationshipType, copyRel.Id);
                        }
                    }
                }
            }
        }
示例#14
0
    static void WriteManifest(Package package, string nuspecPath)
    {
        var uri = PackUriHelper.CreatePartUri(new Uri(Uri.EscapeDataString(Path.GetFileName(nuspecPath)), UriKind.Relative));

        // Create the manifest relationship
        package.CreateRelationship(uri, TargetMode.Internal, "http://schemas.microsoft.com/packaging/2010/07/manifest");

        // Create the part
        var packagePart = package.CreatePart(uri, "application/octet", CompressionOption.Maximum);

        using (var stream = packagePart.GetStream())
        using (var fileStream = File.OpenRead(nuspecPath))
        {
            fileStream.CopyTo(stream);
        }
    }
示例#15
0
        /// <summary>
        /// Creates a package-level or part-level relationship and its target part
        /// (if the target part wasn't already created before). If the sourceTargetFilePath does not exist,
        /// then both relationship and part will not be created.
        /// </summary>
        /// <param name="package"></param>
        /// <param name="sourcePart">Set to null for a package-level relationship</param>
        /// <param name="sourceTargetFilePath"></param>
        /// <param name="targetUri"></param>
        /// <param name="targetMimeType"></param>
        /// <param name="relationshipTypeUri"></param>
        /// <param name="targetPart">The target part that was created</param>
        /// <returns>True if relationship and part (if not already created before) was created,
        /// False if source file does not exist and thus relationship and part wasn't created.</returns>
        private static bool CreateRelationshipAndTargetPart(
            System.IO.Packaging.Package package, System.IO.Packaging.PackagePart sourcePart,
            string sourceTargetFilePath, string targetUri, string targetMimeType, string relationshipTypeUri,
            out System.IO.Packaging.PackagePart targetPart)
        {
            // TODO add console output for added parts and relationships

            targetPart = null;

            if (!File.Exists(sourceTargetFilePath))
            {
                Console.WriteLine(
                    "Warning: The following source file does not exist: " + sourceTargetFilePath +
                    ". Part and relationship will not be created.");
                return(false);
            }
            try
            {
                targetPart = package.CreatePart(
                    PackUriHelper.CreatePartUri(
                        new Uri(targetUri, UriKind.Relative)), targetMimeType, CompressionOption.Maximum);
                using (FileStream fileStream = new FileStream(sourceTargetFilePath, FileMode.Open, FileAccess.Read))
                {
                    fileStream.CopyTo(targetPart.GetStream());
                }
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine(
                    "Warning: The following part URI already exists and will not be created again: " +
                    targetUri + ". Relationship will still be created.");
            }
            if (sourcePart == null)
            {
                package.CreateRelationship(
                    PackUriHelper.CreatePartUri(
                        new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri);
            }
            else
            {
                sourcePart.CreateRelationship(
                    PackUriHelper.CreatePartUri(
                        new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri);
            }
            return(true);
        }
		private static void ExportProcessPart(Package package, WfProcessDescriptor processDesc, WfExportProcessDescriptorContext context)
		{
			Uri partUri = CreatePartUri(processDesc.Key, WfProcessDescriptorPackagePartType.ProcessPart);

			if (context.ExistingParts.Contains(partUri.ToString()))
				return;

			XElement xeWfProcess = context.Formatter.Serialize(processDesc);
			XDocument xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), xeWfProcess);

			PackagePart part = package.CreatePart(partUri, MediaTypeNames.Text.Xml, CompressionOption.Normal);

			using (Stream stream = part.GetStream())
				xDoc.Save(stream);

			context.ExistingParts.Add(partUri.ToString());
		}
        public void Zip(string fullPathSource, bool recursive, string whereClause, string fullPathDestination, string zipFileName, bool overWrite)
        {
            Log.WriteLog(" -- Init -- ", "Log", this.GetType().Name, this.AppConfig);
            List <FileInfo> selectedFiles = this.SelectFiles(fullPathSource, recursive, whereClause, fullPathDestination);

            if (File.Exists(string.Concat(fullPathDestination, "\\", zipFileName)) && overWrite)
            {
                File.Delete(string.Concat(fullPathDestination, "\\", zipFileName));
            }
            else if (File.Exists(string.Concat(fullPathDestination, "\\", zipFileName)))
            {
                throw new IOException("File already exists");
            }
            string location = string.Concat(fullPathDestination, "\\", zipFileName);

            if (Path.GetExtension(location).ToLower() != ".zip")
            {
                throw new IOException("File Extension in not valid");
            }
            FileStream ZipFileStream = new FileStream(location, FileMode.Create);

            using (System.IO.Packaging.Package Package = System.IO.Packaging.Package.Open(ZipFileStream, FileMode.OpenOrCreate))
            {
                foreach (FileInfo file in selectedFiles)
                {
                    try
                    {
                        string[] strArrays = new string[] { string.Concat(this.RemoveDrivefromDirectory(file.DirectoryName), "\\", file.Name) };
                        Uri      UriPath   = PackUriHelper.CreatePartUri(new Uri(Path.Combine(strArrays), UriKind.Relative));
                        System.IO.Packaging.PackagePart PackagePart = Package.CreatePart(UriPath, "text/xml", CompressionOption.Maximum);
                        string[] strArrays1 = new string[] { string.Concat(file.DirectoryName, "\\", file.Name) };
                        byte[]   Data       = File.ReadAllBytes(Path.Combine(strArrays1));
                        PackagePart.GetStream().Write(Data, 0, Data.Count <byte>());
                        Package.CreateRelationship(PackagePart.Uri, TargetMode.Internal, "http://schemas.microsoft.com/opc/2006/sample/document");
                    }
                    catch (Exception exception)
                    {
                        Exception e = exception;
                        Log.WriteLog(e.Message, "Error", this.GetType().Name, this.AppConfig);
                        throw e;
                    }
                }
            }
            ZipFileStream.Close();
        }
示例#18
0
        /// <summary>
        /// If this document does not contain a /word/numbering.xml add the default one generated by Microsoft Word 
        /// when the default bullet, numbered and multilevel lists are added to a blank document
        /// </summary>
        /// <param name="package"></param>
        /// <param name="mainDocumentPart"></param>
        /// <returns></returns>
        internal static XDocument AddDefaultNumberingXml(Package package)
        {
            XDocument numberingDoc;
            // Create the main document part for this package
            PackagePart wordNumbering = package.CreatePart(new Uri("/word/numbering.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", CompressionOption.Maximum);

            numberingDoc = DecompressXMLResource("Novacode.Resources.numbering.xml.gz");

            // Save /word/numbering.xml
            using (TextWriter tw = new StreamWriter(wordNumbering.GetStream(FileMode.Create, FileAccess.Write)))
                numberingDoc.Save(tw, SaveOptions.None);

            PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
                                                                          p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));

            mainDocumentPart.CreateRelationship(wordNumbering.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering");
            return numberingDoc;
        }
示例#19
0
        void WriteRelationships()
        {
            bool exists = Package.PartExists(RelationshipsPartUri);

            if (exists && Relationships.Count == 0)
            {
                Package.DeletePart(RelationshipsPartUri);
                return;
            }

            if (!exists)
            {
                PackagePart part = Package.CreatePart(RelationshipsPartUri, Package.RelationshipContentType);
                part.IsRelationship = true;
            }
            using (Stream s = Package.GetPart(RelationshipsPartUri).GetStream())
                Package.WriteRelationships(Relationships, s);
        }
示例#20
0
        private static void CreateNewPart(PackagePart inputPart, Package outputPackage)
        {
            var contentType = IsObfuscatedFont(inputPart) ? "application/vnd.ms-opentype" : inputPart.ContentType;

            var outputPart = outputPackage.CreatePart(inputPart.Uri, contentType, CompressionOption.Normal);
            if (outputPart == null)
            {
                throw new ApplicationException("Couldn't create new part");
            }

            if (IsObfuscatedFont(inputPart))
            {
                CopyObfuscatedFontPart(inputPart, outputPart);
            }
            else
            {
                CopyPart(inputPart, outputPart);
            }
        }
示例#21
0
        private void ZipDirectory(DirectoryInfo di, Package package)
        {
            foreach (FileInfo fi in di.GetFiles())
            {
                string relativePath = fi.FullName.Replace(SourceFolderPath, string.Empty);
                relativePath = relativePath.Replace("\\", "/");
                PackagePart part = package.CreatePart(new Uri(relativePath, UriKind.Relative), System.Net.Mime.MediaTypeNames.Application.Zip);
                using (FileStream fs = fi.OpenRead())
                {
                    CopyStream(fs, part.GetStream());
                }

            }

            foreach (DirectoryInfo subDi in di.GetDirectories())
            {
                ZipDirectory(subDi, package);
            }
        }
 public static void CreateAfChunkPart(Package package, int afChunkId, string htmlString)
 {
     const string HtmlContentType = "application/xhtml+xml";
     var formattedAfChunk = string.Format("afchunk{0}", afChunkId);
     var formattedAfChunkPartPath = string.Format("word/{0}.dat", formattedAfChunk);
     var docPart = GetDocumentPart(package);
     var partUriAfChunk = PackUriHelper.CreatePartUri(new Uri(formattedAfChunkPartPath, UriKind.Relative));
     var packagePartAfChunk = package.CreatePart(partUriAfChunk, HtmlContentType);            
     using (var afChunkStream = packagePartAfChunk.GetStream())
     {
         using (var stringStream = new StreamWriter(afChunkStream, Encoding.UTF8))
         {
             stringStream.Write(htmlString);
         }
     }
     docPart.CreateRelationship(
                                new Uri(formattedAfChunk + ".dat", UriKind.Relative),
                                TargetMode.Internal,
                                OfficeAfChunkRelType,
                                string.Format("altChunkId{0}", afChunkId));
 }
示例#23
0
        /// <summary>
        /// If this document does not contain a /word/styles.xml add the default one generated by Microsoft Word.
        /// </summary>
        /// <param name="package"></param>
        /// <param name="mainDocumentPart"></param>
        /// <returns></returns>
        internal static XDocument AddDefaultStylesXml(Package package)
        {
            XDocument stylesDoc;
            // Create the main document part for this package
            PackagePart word_styles = package.CreatePart(new Uri("/word/styles.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);

            stylesDoc = HelperFunctions.DecompressXMLResource("Novacode.Resources.default_styles.xml.gz");
            XElement lang = stylesDoc.Root.Element(XName.Get("docDefaults", DocX.w.NamespaceName)).Element(XName.Get("rPrDefault", DocX.w.NamespaceName)).Element(XName.Get("rPr", DocX.w.NamespaceName)).Element(XName.Get("lang", DocX.w.NamespaceName));
            lang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);

            // Save /word/styles.xml
            using (TextWriter tw = new StreamWriter(word_styles.GetStream(FileMode.Create, FileAccess.Write)))
                stylesDoc.Save(tw, SaveOptions.None);

            PackagePart mainDocumentPart = package.GetParts().Where
            (
                p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)||p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase)
            ).Single();

            mainDocumentPart.CreateRelationship(word_styles.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles");
            return stylesDoc;
        }
示例#24
0
 public static void AddFileToPackage(Package package, string uri, string filePath, string contentType)
 {
     FileInfo info = new FileInfo(filePath);
     uri = MakeUriSafe(uri);
     if (!info.Exists)
     {
         throw new FileNotFoundException(Strings.Package_FileCouldNotBeAdded, filePath);
     }
     Uri partUri = new Uri(uri, UriKind.Relative);
     string extension = info.Extension;
     if (package.PartExists(partUri))
     {
         package.DeletePart(partUri);
     }
     PackagePart part = package.CreatePart(partUri, contentType, CompressionOption.Maximum);
     using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
     {
         using (Stream stream2 = part.GetStream())
         {
             CopyStream(stream, stream2);
         }
         stream.Close();
     }
 }
示例#25
0
 public static void RenamePath(Package package, string oldUri, string newUri)
 {
     Uri partUri = new Uri(oldUri, UriKind.Relative);
     Uri uri2 = new Uri(newUri, UriKind.Relative);
     if (package.PartExists(partUri))
     {
         PackagePart part = package.GetPart(partUri);
         PackagePart part2 = package.CreatePart(uri2, part.ContentType, part.CompressionOption);
         using (Stream stream = part.GetStream())
         {
             using (Stream stream2 = part2.GetStream())
             {
                 CopyStream(stream, stream2);
             }
         }
         package.DeletePart(partUri);
     }
 }
        private void ExportModulesInternal(Package package, PlatformExportManifest manifest, Action<ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo();

            foreach (var module in manifest.Modules)
            {
                var moduleDescriptor = InnerGetModulesWithInterface(typeof(ISupportExportImportModule)).FirstOrDefault(x => x.Id == module.Id);
                if (moduleDescriptor != null)
                {
                    //Create part for module
                    var modulePartUri = PackUriHelper.CreatePartUri(new Uri(module.Id + ".json", UriKind.Relative));
                    var modulePart = package.CreatePart(modulePartUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Normal);

                    Action<ExportImportProgressInfo> modulePorgressCallback = (x) =>
                    {
                        progressInfo.Description = String.Format("{0}: {1}", module.Id, x.Description);
                        progressCallback(progressInfo);
                    };

                    progressInfo.Description = String.Format("{0}: exporting...", module.Id);
                    progressCallback(progressInfo);

                    try
                    {
                        ((ISupportExportImportModule)moduleDescriptor.ModuleInfo.ModuleInstance).DoExport(modulePart.GetStream(), manifest, modulePorgressCallback);
                    }
                    catch (Exception ex)
                    {
                        progressInfo.Errors.Add(ex.ExpandExceptionMessage());
                        progressCallback(progressInfo);
                    }

                    module.PartUri = modulePartUri.ToString();
                }
            }

        }
        private void ExportPlatformEntriesInternal(Package package, PlatformExportManifest manifest, Action<ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo();
            var platformExportObj = new PlatformExportEntries();

            if (manifest.HandleSecurity)
            {
                //Roles
                platformExportObj.Roles = _roleManagementService.SearchRoles(new RoleSearchRequest { SkipCount = 0, TakeCount = int.MaxValue }).Roles;
                //users 
                var usersResult = _securityService.SearchUsersAsync(new UserSearchRequest { TakeCount = int.MaxValue }).Result;
                progressInfo.Description = String.Format("Security: {0} users exporting...", usersResult.Users.Count());
                progressCallback(progressInfo);

                foreach (var user in usersResult.Users)
                {
                    platformExportObj.Users.Add(_securityService.FindByIdAsync(user.Id, UserDetails.Export).Result);
                }
            }

            //Export setting for selected modules
            if (manifest.HandleSettings)
            {
                progressInfo.Description = String.Format("Settings: selected modules settings exporting...");
                progressCallback(progressInfo);

                platformExportObj.Settings = manifest.Modules.SelectMany(x => _settingsManager.GetModuleSettings(x.Id)).ToList();
            }

            //Dynamic properties
            var allTypes = _dynamicPropertyService.GetAvailableObjectTypeNames();

            progressInfo.Description = String.Format("Dynamic properties: load properties...");
            progressCallback(progressInfo);

            platformExportObj.DynamicProperties = allTypes.SelectMany(x => _dynamicPropertyService.GetProperties(x)).ToList();
            platformExportObj.DynamicPropertyDictionaryItems = platformExportObj.DynamicProperties.Where(x => x.IsDictionary).SelectMany(x => _dynamicPropertyService.GetDictionaryItems(x.Id)).ToList();

            //Create part for platform entries
            var platformEntiriesPart = package.CreatePart(_platformEntriesPartUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Normal);
            using (var partStream = platformEntiriesPart.GetStream())
            {
                platformExportObj.SerializeJson<PlatformExportEntries>(partStream);
            }
        }
示例#28
0
文件: Form1.cs 项目: abb1/Testing
        void testingabpckg()
        {
            //try
            //{

            string InputFolder = @"C:\Users\inbakad\Desktop\input";

            //------------

            using (System.IO.Packaging.Package ABpackage = System.IO.Packaging.Package.Open(@"C:\Users\inbakad\Desktop\output\zenon.abpkg", FileMode.Create))
            {
                //get all files to be included in package in corresponding folder
                string[] filenames = Directory.GetFiles(InputFolder, "*.*", SearchOption.AllDirectories);
                foreach (string file in filenames)
                {
                    //create packagePart for each file in folder
                    //uri shall be relative --> remove absolute path, uri shall start with "/", uri doesn't accept blanks --> replace with %20
                    if (!InputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
                    {
                        InputFolder = InputFolder + Path.DirectorySeparatorChar;
                    }
                    string fileRelativePath = file.ToString().Replace(InputFolder, "/");
                    //prepare path for uri:
                    //fileRelativePath = fileRelativePath.Replace(" ", "%20");
                    //fileRelativePath = fileRelativePath.Replace("{", "%7b");
                    //fileRelativePath = fileRelativePath.Replace("}", "%7d");
                    //convert path info into uri format
                    fileRelativePath = fileRelativePath.Replace("\\", "/");
                    var    packagePartUri = PackUriHelper.CreatePartUri(new Uri(fileRelativePath, UriKind.Relative));
                    string extension      = Path.GetExtension(@file);
                    if (string.IsNullOrEmpty(extension))
                    {
                        extension = ".%00";
                    }
                    var packagePart = ABpackage.CreatePart(packagePartUri, "part/" + extension);
                    //get file content and write to package part
                    using (var packageStream = packagePart.GetStream(FileMode.Create, FileAccess.ReadWrite))
                    {
                        try
                        {
                            using (FileStream currentFileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                            {
                                currentFileStream.CopyTo(packageStream);
                                Console.WriteLine("Added file: " + file);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        ABpackage.CreateRelationship(packagePart.Uri, TargetMode.Internal, "rel");
                    }
                }
                // Flush package to ensure all data is written to it
                ABpackage.Flush();
            }


            //----------------------
            //using (System.IO.Packaging.Package ABpackage = System.IO.Packaging.Package.Open(@"C:\Users\inbakad\Desktop\output\test.abpkg", FileMode.Create)) ;
            //{

            //   // get all files to be included in package in corresponding folder
            //    string[] filenames = Directory.GetFiles(InputFolder, "*.*", SearchOption.AllDirectories);
            //   // string[] encodefiles = new string[filenames.Length];
            //    int I = 0;
            //    foreach (string file in filenames)
            //    {
            //      //  create packagePart for each file in folder

            //      //  uri shall be relative-- > remove absolute path, uri shall start with "/", uri doesn't accept blanks --> replace with %20
            //        if (!InputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
            //                InputFolder = InputFolder + Path.DirectorySeparatorChar;
            //        string fileRelativePath = file.ToString().Replace(InputFolder, "/");


            //        var packagePartUri = PackUriHelper.CreatePartUri(new Uri(fileRelativePath, UriKind.Relative));
            //        var pckg = PackUriHelper.CreatePartUri(new Uri(fileRelativePath));
            //       // encodefiles[I] = Uri.EscapeDataString(fileRelativePath);
            //       // I++;
            //        string escaprstr = Uri.EscapeDataString(filePath);
            //        //prepare path for uri:
            //        //remove blanks
            //        fileRelativePath = fileRelativePath.Replace(" ", "%20");
            //        fileRelativePath = fileRelativePath.Replace("{", "%7b");
            //        fileRelativePath = fileRelativePath.Replace("}", "%7d");
            //        convert path info into uri format
            //          fileRelativePath = fileRelativePath.Replace("\\", "/");
            //        var packagePartUri = PackUriHelper.CreatePartUri(new Uri(fileRelativePath, UriKind.Relative));
            //        // string extension = Path.GetExtension(@file);
            //        if (string.IsNullOrEmpty(extension))
            //            extension = ".%00";
            //        var packagePart = ABpackage.CreatePart(packagePartUri, "part/" + extension);
            //        get file content and write to package part
            //        using (var packageStream = packagePart.GetStream(FileMode.Create, FileAccess.ReadWrite))
            //        {
            //            try
            //            {
            //                using (FileStream currentFileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
            //                {
            //                    currentFileStream.CopyTo(packageStream);
            //                    Console.WriteLine("Added file: " + file);
            //                }
            //            }
            //            catch (Exception ex)
            //            {
            //                Console.WriteLine(ex.Message);
            //            }
            //            // ABpackage.CreateRelationship(packagePart.Uri, TargetMode.Internal, "rel");
            //        }
            //    }
            // Flush package to ensure all data is written to it

            //}
            //ABpackage.Flush();
            // return encodefiles ;
        }
示例#29
0
        private void WriteManifest(Package package)
        {
            Uri uri = UriUtility.CreatePartUri(Id + Constants.ManifestExtension);

            // Create the manifest relationship
            package.CreateRelationship(uri, TargetMode.Internal, Constants.PackageRelationshipNamespace + ManifestRelationType);

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

            using (Stream stream = packagePart.GetStream())
            {
                Manifest manifest = Manifest.Create(this);
                manifest.Save(stream);
            }
        }
示例#30
0
 private void AddUriToPackage(string path, string file, Package pkg)
 {
     Uri uri = null;
     PackagePart pkgPart = null;
     uri = PackUriHelper.CreatePartUri(new Uri(file, UriKind.Relative));
     pkgPart = pkg.CreatePart(uri, string.Empty);
     using (FileStream fileStream = new FileStream(path + file, FileMode.Open, FileAccess.Read))
     {
         CopyStream(fileStream, pkgPart.GetStream());
     }
 }
		private static void ExportMappingPart(Package package, WfExportProcessDescriptorContext context)
		{
			if (context.MappingInfo.Count == 0)
				return;

			Uri partUri = CreatePartUri(string.Empty, WfProcessDescriptorPackagePartType.MappingPart);

			XElement mappingsXml = new XElement("Mappings");

			foreach (var mapItem in context.MappingInfo)
			{
				mappingsXml.Add(new XElement("Item",
					new XAttribute("matrixID", mapItem.MatrixPath),
					new XAttribute("matrixDefID", mapItem.MatrixDefID),
					new XAttribute("processDescID", mapItem.ProcessDescriptionID))
				);
			}

			XDocument xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), mappingsXml);

			PackagePart part = package.CreatePart(partUri, MediaTypeNames.Text.Xml);

			using (Stream stream = part.GetStream())
			{
				xDoc.Save(stream);
			}
		}
		private static void ExportMatrixDefPart(Package package, WfMatrixDefinition matrixDef, WfExportProcessDescriptorContext context)
		{
			Uri partUri = CreatePartUri(matrixDef.Key, WfProcessDescriptorPackagePartType.MatrixDefPart);

			if (context.ExistingParts.Contains(partUri.ToString()))
				return;

			XElement matrixDefXml = context.Formatter.Serialize(matrixDef);

			XDocument xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"), matrixDefXml);
			PackagePart part = package.CreatePart(partUri, MediaTypeNames.Text.Xml);

			using (var stream = part.GetStream())
			{
				xDoc.Save(stream);
				stream.Flush();
			}

			context.ExistingParts.Add(partUri.ToString());
		}
示例#33
0
        internal static PackagePart CreateOrGetSettingsPart(Package package)
        {
            PackagePart settingsPart;

            Uri settingsUri = new Uri("/word/settings.xml", UriKind.Relative);
            if (!package.PartExists(settingsUri))
            {
                settingsPart = package.CreatePart(settingsUri, "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", CompressionOption.Maximum);

                PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
                                                                              p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));

                mainDocumentPart.CreateRelationship(settingsUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings");

                XDocument settings = XDocument.Parse
                (@"<?xml version='1.0' encoding='utf-8' standalone='yes'?>
                <w:settings xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:r='http://schemas.openxmlformats.org/officeDocument/2006/relationships' xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math' xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w10='urn:schemas-microsoft-com:office:word' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:sl='http://schemas.openxmlformats.org/schemaLibrary/2006/main'>
                  <w:zoom w:percent='100' />
                  <w:defaultTabStop w:val='720' />
                  <w:characterSpacingControl w:val='doNotCompress' />
                  <w:compat />
                  <w:rsids>
                    <w:rsidRoot w:val='00217F62' />
                    <w:rsid w:val='001915A3' />
                    <w:rsid w:val='00217F62' />
                    <w:rsid w:val='00A906D8' />
                    <w:rsid w:val='00AB5A74' />
                    <w:rsid w:val='00F071AE' />
                  </w:rsids>
                  <m:mathPr>
                    <m:mathFont m:val='Cambria Math' />
                    <m:brkBin m:val='before' />
                    <m:brkBinSub m:val='--' />
                    <m:smallFrac m:val='off' />
                    <m:dispDef />
                    <m:lMargin m:val='0' />
                    <m:rMargin m:val='0' />
                    <m:defJc m:val='centerGroup' />
                    <m:wrapIndent m:val='1440' />
                    <m:intLim m:val='subSup' />
                    <m:naryLim m:val='undOvr' />
                  </m:mathPr>
                  <w:themeFontLang w:val='en-IE' w:bidi='ar-SA' />
                  <w:clrSchemeMapping w:bg1='light1' w:t1='dark1' w:bg2='light2' w:t2='dark2' w:accent1='accent1' w:accent2='accent2' w:accent3='accent3' w:accent4='accent4' w:accent5='accent5' w:accent6='accent6' w:hyperlink='hyperlink' w:followedHyperlink='followedHyperlink' />
                  <w:shapeDefaults>
                    <o:shapedefaults v:ext='edit' spidmax='2050' />
                    <o:shapelayout v:ext='edit'>
                      <o:idmap v:ext='edit' data='1' />
                    </o:shapelayout>
                  </w:shapeDefaults>
                  <w:decimalSymbol w:val='.' />
                  <w:listSeparator w:val=',' />
                </w:settings>"
                );

                XElement themeFontLang = settings.Root.Element(XName.Get("themeFontLang", DocX.w.NamespaceName));
                themeFontLang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);

                // Save the settings document.
                using (TextWriter tw = new StreamWriter(settingsPart.GetStream()))
                    settings.Save(tw);
            }
            else
                settingsPart = package.GetPart(settingsUri);
            return settingsPart;
        }
        private void WriteManifest(Package package, int minimumManifestVersion)
        {
            Uri uri = UriUtility.CreatePartUri(Id + Constants.ManifestExtension);

            // Create the manifest relationship
            package.CreateRelationship(uri, TargetMode.Internal,
                                       Constants.PackageRelationshipNamespace + ManifestRelationType);

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

            using (Stream stream = packagePart.GetStream())
            {
                Manifest manifest = Manifest.Create(this);
                //if (PackageAssemblyReferences.Any())
                //{
                //    manifest.Metadata.References = new List<ManifestReference>(
                //        PackageAssemblyReferences.Select(reference => new ManifestReference {File = reference.File}));
                //}
                manifest.Save(stream, minimumManifestVersion);
            }
        }
		private static void ExportMatrixPart(Package package, WfProcessDescriptor processDesp, WfExportProcessDescriptorContext context)
		{
			var matrix = WfMatrixAdapter.Instance.LoadByProcessKey(processDesp.Key, false);

			if (matrix == null)
				return;

			matrix.Loaded = true;

			Uri partUri = CreatePartUri(context.MatrixCounter.ToString(), WfProcessDescriptorPackagePartType.MatrixPart);

			if (context.ExistingParts.Contains(partUri.ToString()))
				return;

			context.MappingInfo.Add(new WfPackageRelationMapping()
			{
				MatrixPath = partUri.ToString(),
				MatrixDefID = matrix.Definition.Key,
				ProcessDescriptionID = processDesp.Key
			});

			ExportMatrixDefPart(package, matrix.Definition, context);

			PackagePart part = package.CreatePart(partUri, MediaTypeNames.Application.Octet, CompressionOption.Normal);
			using (MemoryStream bytes = matrix.ExportToExcel2007(context.ExportParams.MatrixRoleAsPerson))
			{
				using (Stream stream = part.GetStream())
				{
					bytes.CopyTo(stream);
				}
			}

			context.ExistingParts.Add(partUri.ToString());
			context.MatrixCounter++;
		}
示例#36
0
        private static void CreatePart(Package package, string path, Stream sourceStream)
        {
            if (PackageUtility.IsManifest(path))
            {
                return;
            }

            Uri uri = UriUtility.CreatePartUri(path);

            // Create the part
            PackagePart packagePart = package.CreatePart(uri, DefaultContentType, CompressionOption.Maximum);
            using (Stream stream = packagePart.GetStream())
            {
                sourceStream.CopyTo(stream);
            }
        }
示例#37
0
        /// <summary>
        /// CertificatePart constructor
        /// </summary>
        internal CertificatePart(Package container, Uri partName)
        {
            if (container == null)
                throw new ArgumentNullException("container");
            
            if (partName == null)
                throw new ArgumentNullException("partName");

            partName = PackUriHelper.ValidatePartUri(partName);
            
            // create if not found
            if (container.PartExists(partName))
            {
                // open the part
                _part = container.GetPart(partName);

                // ensure the part is of the expected type
                if (_part.ValidatedContentType.AreTypeAndSubTypeEqual(_certificatePartContentType) == false)
                    throw new FileFormatException(SR.Get(SRID.CertificatePartContentTypeMismatch));
            }
            else
            {
                // create the part
                _part = container.CreatePart(partName, _certificatePartContentType.ToString());
            }
        }