public static bool VytvoritCustomUI(string souborDocx, string customUiXml, bool zalohovat) { bool uspech = false; ZalohovatDokument(souborDocx, zalohovat); string customUiRelationshipType = ZjistiVerziCustomUi(customUiXml); if (customUiRelationshipType == null) { return(uspech); } string customUiXmlUri = "/customUI/customUI.xml"; string CustomUiId = "rCustomUiId"; if (customUiRelationshipType == RelCustomUiW14RelationshipType) { customUiXmlUri = "/customUI/customUI2010.xml"; CustomUiId = "rCustomUi2010Id"; } using (Package wdPackage = Package.Open(souborDocx, FileMode.Open, FileAccess.ReadWrite)) { PackageRelationship docPackageRelationship = wdPackage.GetRelationshipsByType(customUiRelationshipType).FirstOrDefault(); Uri documentUri = null; if (docPackageRelationship == null) { documentUri = PackUriHelper.CreatePartUri(new Uri(customUiXmlUri, UriKind.Relative)); wdPackage.CreatePart(documentUri, "application/xml"); docPackageRelationship = wdPackage.CreateRelationship(documentUri, TargetMode.Internal, customUiRelationshipType, CustomUiId); } if (docPackageRelationship != null) { if (documentUri == null) { documentUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), docPackageRelationship.TargetUri); } PackagePart documentPart = wdPackage.GetPart(documentUri); string customXml = "<customUI xmlns=\"http://schemas.microsoft.com/office/2006/01/customui\"><ribbon><tabs><tab id=\"tbKarta\" label=\"Karta\"></tab></tabs></ribbon></customUI>"; if (customUiXml != null) { using (StreamReader streamReader = new StreamReader(customUiXml)) { customXml = streamReader.ReadToEnd(); } } using (StreamWriter streamWriter = new StreamWriter(documentPart.GetStream(FileMode.Create))) { streamWriter.Write(customXml); uspech = true; } } } return(uspech); }
/// <summary> /// Add stream to package /// </summary> /// <param name="package"></param> /// <param name="stream"></param> /// <param name="Name"></param> private static void AddStream(Package package, Stream stream, string Name) { var partUri = PackUriHelper.CreatePartUri(new Uri(Name, UriKind.Relative)); var part = package.CreatePart(partUri, "", CompressionOption.Normal); CopyStream(stream, part.GetStream()); }
/// <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 = 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")); }
public void Generate(Package sourcePackage, Package targetPackage, FileInfo outputFile) { var serializer = new XmlSerializer(typeof(DataSchemaModel)); var uri = PackUriHelper.CreatePartUri(new Uri("/replication.xml", UriKind.Relative)); var sourceModel = (DataSchemaModel)serializer.Deserialize(sourcePackage.GetPart(uri).GetStream()); var targetModel = (DataSchemaModel)serializer.Deserialize(targetPackage.GetPart(uri).GetStream()); var outputFileSql = new List <string>(); foreach (var publicationToCreate in sourceModel.Model.Elements.Except(targetModel.Model.Elements, x => x.Name)) { var createPublicationStep = new CreatePublicationStep(publicationToCreate); outputFileSql.AddRange(createPublicationStep.GenerateTSQL()); } foreach (var publicationToAlter in sourceModel.Model.Elements.Intersect(targetModel.Model.Elements, x => x.Name)) { var sqlPublicationComparer = new SqlPublicationComparer(); var matchingPublicationInTarget = targetModel.Model.Elements.Single(x => x.Name == publicationToAlter.Name); var alterPublicationStep = new AlterPublicationStep(sqlPublicationComparer.Compare(publicationToAlter, matchingPublicationInTarget)); outputFileSql.AddRange(alterPublicationStep.GenerateTSQL()); } foreach (var publicationToDrop in targetModel.Model.Elements.Except(sourceModel.Model.Elements, x => x.Name)) { var dropPublicationStep = new DropPublicationStep(publicationToDrop); outputFileSql.AddRange(dropPublicationStep.GenerateTSQL()); } }
/// <summary> /// Adds the speficied file to the package as document part /// </summary> private static void CreateDocumentPart(Package package, FileInfo file, string contentType, bool storeInDirectory) { Uri partUriDocument; // Convert system path and file names to Part URIs. if (storeInDirectory) { partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.Combine(file.Directory.Name, file.Name), UriKind.Relative)); } else { partUriDocument = PackUriHelper.CreatePartUri(new Uri(file.Name, UriKind.Relative)); } // Add the Document part to the Package PackagePart packagePartDocument = package.CreatePart( partUriDocument, contentType); // Copy the data to the Document Part using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, packagePartDocument.GetStream()); } // Add a Package Relationship to the Document Part package.CreateRelationship(packagePartDocument.Uri, TargetMode.Internal, PackageRelationshipType); }
private TileSourceDefinition[] LoadTilesetFromPackage(string filename, System.Xml.Serialization.XmlSerializer serializer) { TileSourceDefinition[] tileSources; Uri partUriMap = PackUriHelper.CreatePartUri(new Uri("Tileset.xml", UriKind.Relative)); using (Package package = Package.Open(filename, FileMode.Open, FileAccess.Read)) { PackagePart tilesetDocument = package.GetPart(partUriMap); using (Stream stream = tilesetDocument.GetStream()) { tileSources = (TileSourceDefinition[])serializer.Deserialize(stream); } foreach (TileSourceDefinition source in tileSources) { Uri partUriImage = PackUriHelper.CreatePartUri(new Uri(source.Filename, UriKind.Relative)); PackagePart imageDocument = package.GetPart(partUriImage); using (Stream imageStream = imageDocument.GetStream()) { AddTileSource(source, imageStream); } } } return(tileSources); }
internal static Uri CreatePartUri(string path) { char[] separator = new char[] { '/', Path.DirectorySeparatorChar }; IEnumerable <string> values = Enumerable.Select <string, string>(path.Split(separator, StringSplitOptions.None), new Func <string, string>(Uri.EscapeDataString)); return(PackUriHelper.CreatePartUri(new Uri(string.Join("/", values), UriKind.Relative))); }
/// <summary> /// Embeds the related file into the specified package. /// </summary> /// <param name="package">The package.</param> /// <exception cref="AmlxCorruptedDocumentException">File not existing any more: + _location</exception> internal void Embed(Package package) { // check if the file was already embedded if (_part != null) { return; } if (!System.IO.File.Exists(_fullPath)) { throw new AmlxCorruptedDocumentException("File not existing any more: " + _location); } // create part and add content var mimetype = XMLMimeTypeMapper.GetMimeType(_fullPath); var uri = PackUriHelper.CreatePartUri(_location); _part = package.CreatePart(uri, mimetype, CompressionOption.Normal); if (_part == null) { throw new AmlxException("Cannot create part for mimetype " + mimetype); } using (var stream = _part.GetStream(FileMode.Create)) { using (var reader = new FileStream(_fullPath, FileMode.Open, FileAccess.Read)) { reader.CopyStreamTo(stream); } } // remove origin System.IO.File.Delete(_fullPath); }
public static void Compress(FileInfo fi, DirectoryInfo dir) { if (fi.Exists) { fi.Delete(); } Package zipFilePackage = ZipPackage.Open(fi.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite); foreach (FileInfo physicalFile in dir.GetFiles()) { string physicalfilePath = physicalFile.FullName; Uri partUri = PackUriHelper.CreatePartUri(new Uri(physicalFile.Name, UriKind.Relative)); PackagePart newFilePackagePart = zipFilePackage.CreatePart(partUri, System.Net.Mime.MediaTypeNames.Text.Xml); byte[] fileContent = File.ReadAllBytes(physicalfilePath); newFilePackagePart.GetStream().Write(fileContent, 0, fileContent.Length); } foreach (DirectoryInfo subDir in dir.GetDirectories()) { foreach (FileInfo physicalFile in subDir.GetFiles()) { string physicalfilePath = physicalFile.FullName; Uri partUri = PackUriHelper.CreatePartUri(new Uri(subDir.Name + "/" + physicalFile.Name, UriKind.Relative)); PackagePart newFilePackagePart = zipFilePackage.CreatePart(partUri, System.Net.Mime.MediaTypeNames.Text.Xml); byte[] fileContent = File.ReadAllBytes(physicalfilePath); newFilePackagePart.GetStream().Write(fileContent, 0, fileContent.Length); } } zipFilePackage.Close(); }
public static void Compress(FileInfo fi, DirectoryInfo dir) { if (fi.Exists) { fi.Delete(); } Package package = Package.Open(fi.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite); FileInfo[] files = dir.GetFiles(); for (int i = 0; i < files.Length; i++) { FileInfo fileInfo = files[i]; string fullName = fileInfo.FullName; Uri partUri = PackUriHelper.CreatePartUri(new Uri(fileInfo.Name, UriKind.Relative)); PackagePart packagePart = package.CreatePart(partUri, "text/xml"); byte[] array = File.ReadAllBytes(fullName); packagePart.GetStream().Write(array, 0, array.Length); } DirectoryInfo[] directories = dir.GetDirectories(); for (int j = 0; j < directories.Length; j++) { DirectoryInfo directoryInfo = directories[j]; FileInfo[] files2 = directoryInfo.GetFiles(); for (int k = 0; k < files2.Length; k++) { FileInfo fileInfo2 = files2[k]; string fullName2 = fileInfo2.FullName; Uri partUri2 = PackUriHelper.CreatePartUri(new Uri(directoryInfo.Name + "/" + fileInfo2.Name, UriKind.Relative)); PackagePart packagePart2 = package.CreatePart(partUri2, "text/xml"); byte[] array2 = File.ReadAllBytes(fullName2); packagePart2.GetStream().Write(array2, 0, array2.Length); } } package.Close(); }
/// <summary> /// Add a folder along with its subfolders to a Package /// </summary> /// <param name="folderName">The folder to add</param> /// <param name="compressedFileName">The package to create</param> /// <param name="overrideExisting">Override exsisitng files</param> /// <returns>ReturnResult</returns> public ReturnResult PackageFolder(string folderName, string compressedFileName, bool overrideExisting) { if (folderName.EndsWith(@"\")) { folderName = folderName.Remove(folderName.Length - 1); } ReturnResult result = new ReturnResult(); if (!Directory.Exists(folderName)) { result.Message = "Source folder doesnt exist in" + folderName; return(result); } if (!overrideExisting && File.Exists(compressedFileName)) { result.Message = "Destination file " + compressedFileName + " cannot be overwritten"; return(result); } try { using (Package package = Package.Open(compressedFileName, FileMode.Create)) { var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories); ZipEventArgs zipArgs = new ZipEventArgs() { TotalFiles = fileList.Count(), FileNumber = 0, BytesZipped = 0, TotalBytes = 0 }; foreach (string fileName in fileList) { zipArgs.FileNumber++; if (Path.GetFileName(fileName).IndexOfAny(Path.GetInvalidFileNameChars()) > -1) { continue; } //The path in the package is all of the subfolders after folderName string pathInPackage; pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName); Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative)); PackagePart packagePartDocument = package.CreatePart(partUriDocument, System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum); using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { fileStream.CopyTo(packagePartDocument.GetStream()); zipArgs.BytesZipped += fileStream.Length; OnZip(zipArgs); } package.CreateRelationship(packagePartDocument.Uri, TargetMode.Internal, PackageRelationshipType); } } } catch (Exception e) { throw new Exception("Error zipping folder " + folderName, e); } OnZipEnd(new ZipEndEventArgs()); result.Success = true; result.Message = "OK"; return(result); }
/// <summary> /// this method holds the logic for packaging the deck folder and saving to the user specified location /// </summary> /// <param name="zipFilename"> user given package name</param> /// <param name="fileToAdd"> deck files to be added</param> private static string AddFileToZip(string zipFilename, string fileToAdd) { try { 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()) { Utils.CopyStream(fileStream, dest); } } return(uri.ToString()); } } catch (Exception e) { Utils.LogException(MethodBase.GetCurrentMethod(), e); return(string.Empty); } }
private static void UnpackAndProcessModel(Package package, string path, Action <XElement, string, XmlWriter> processElement) { var part = package.GetPart(PackUriHelper.CreatePartUri(new Uri("/model.xml", UriKind.Relative))); var targetFilePath = Path.Combine(path, "model.xml"); var readerSettings = new XmlReaderSettings() { CheckCharacters = false, IgnoreWhitespace = false }; var writerSettings = new XmlWriterSettings() { CloseOutput = true, CheckCharacters = false, Indent = false }; using (var source = part.GetStream(FileMode.Open, FileAccess.Read)) using (var source2 = part.GetStream(FileMode.Open, FileAccess.Read)) using (var target = File.OpenWrite(targetFilePath)) using (var reader = XmlReader.Create(source, readerSettings)) using (var navigableReader = new NavigableReader(source2)) using (var writer = XmlWriter.Create(target, writerSettings)) { var xmlInfo = (IXmlLineInfo)reader; while (reader.Read()) { while (reader.NodeType == XmlNodeType.Element && reader.Name == "Element") { navigableReader.NavigateTo(xmlInfo.LineNumber, xmlInfo.LinePosition); XElement e = XNode.ReadFrom(reader) as XElement; var elementString = navigableReader.ReadUntil(xmlInfo.LineNumber, xmlInfo.LinePosition); processElement(e, elementString, writer); } CopySingleXmlNode(reader, writer); } } }
public bool TryAccessFile(string path, bool create, out IPackageFile file) { var uri = PackUriHelper.CreatePartUri(new Uri(".\\" + path, UriKind.Relative)); if (create) { if (_package.PartExists(uri)) { _package.DeletePart(uri); } var part = _package.CreatePart(uri, "", CompressionOption.Normal); file = new PackageFile(part); return(true); } else if (_package.PartExists(uri)) { file = new PackageFile(_package.GetPart(uri)); return(true); } else { file = null; return(false); } }
/// <summary> /// Saves the PTFConfig files in the profile to the specified path. /// </summary> /// <param name="path">Path</param> public void SavePtfCfgTo(string path) { CheckIfClosed(); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } Uri ptfcfgBase = PackUriHelper.CreatePartUri(new Uri("ptfconfig", UriKind.Relative)); foreach (var part in profilePackage.GetParts()) { if (part.Uri.ToString().IndexOf("/ptfconfig/") == 0) { string uri = part.Uri.ToString(); string name = uri.Substring(uri.LastIndexOf("/") + 1); using (var fs = new FileStream(Path.Combine(path, name), FileMode.Create)) { CopyStream(part.GetStream(), fs); fs.Flush(); fs.Close(); } } } }
public static bool IsDacPac(FileInfo package) { try { using (Package opc = Package.Open(package.FullName, FileMode.Open, FileAccess.Read)) { var originPartUri = PackUriHelper.CreatePartUri(new Uri(Constants.OriginXmlUri, UriKind.Relative)); var originPart = opc.GetPart(originPartUri); var originDoc = XDocument.Load(XmlReader.Create(originPart.GetStream())); if (originDoc.Root == null || string.Compare(originDoc.Root.Name.NamespaceName, Constants.DacXsdUri, StringComparison.InvariantCulture) != 0) { return(false); } if (string.Compare(originDoc.Root.Name.LocalName, Constants.DacOriginElement, StringComparison.InvariantCulture) != 0) { return(false); } var productSchema = originDoc.Root.Descendants().Elements().FirstOrDefault(d => d.Name.LocalName == Constants.ProductSchemaElement); if (productSchema == null || string.Compare(productSchema.Value, Constants.DacXsdUri, StringComparison.InvariantCulture) != 0) { return(false); } return(true); } } catch (Exception) { return(false); } }
/// <summary> /// Creates a package zip file containing specified xml documents. /// </summary> public static void Zip(string outputZipFileName, string[] contentXmlFiles) { Dictionary <string, Uri> uris = new Dictionary <string, Uri>(); foreach (string file in contentXmlFiles) { Uri uri = PackUriHelper.CreatePartUri(new Uri(file, UriKind.Relative)); uris.Add(file, uri); } using (Package package = Package.Open(outputZipFileName, FileMode.Create)) { foreach (var f in uris) { // Create a package part PackagePart packagePartDocument = package.CreatePart(f.Value, System.Net.Mime.MediaTypeNames.Text.Xml); // Copy the data to the Document Part using (FileStream fileStream = new FileStream(f.Key, FileMode.Open)) { CopyStream(fileStream, packagePartDocument.GetStream()); } // Add a Package Relationship to the Document Part package.CreateRelationship(packagePartDocument.Uri, TargetMode.Internal, RelationshipType); } } }
GenerateUriForObfuscatedFont() { String uniqueUri = "/Resources/" + Guid.NewGuid().ToString() + XpsS0Markup.ObfuscatedFontExt; Uri uri = PackUriHelper.CreatePartUri(new Uri(uniqueUri, UriKind.Relative)); return(uri); }
async Task AddDirectoryToPackage(string path, Package package) { if (File.Exists(Path.Combine(path, NoBackupIndicatorFile))) { return; } foreach (var file in Directory.GetFiles(path, "*.*", SearchOption.TopDirectoryOnly)) { var relativePath = file.Replace(_storageService.DataPath, string.Empty, StringComparison.Ordinal); var partUri = PackUriHelper.CreatePartUri(new Uri(relativePath, UriKind.Relative)); var part = package.CreatePart(partUri, MediaTypeNames.Application.Octet, CompressionOption.NotCompressed); using (var fileStream = File.OpenRead(file)) using (var partStream = part.GetStream()) { await fileStream.CopyToAsync(partStream).ConfigureAwait(false); } } foreach (var directory in Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly)) { await AddDirectoryToPackage(directory, package).ConfigureAwait(false); } }
/// <summary> /// Creates a compressed zip file in a subfolder called "backup" /// </summary> /// <param name="files">KeyValuePair is FilePath, ArchivePath</param> /// <param name="archivePrefix">string that will prepend the archive filename</param> public static string CreatePackage(Dictionary <string, string> files, string archivePrefix) { // build the filepath for the destination archive string filepath = Helper.Epg123BackupFolder; if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } filepath += "\\" + archivePrefix + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".zip"; // create the zip and add the file(s) using (Package package = Package.Open(filepath, FileMode.Create)) { foreach (KeyValuePair <string, string> file in files) { PackagePart part = package.CreatePart(PackUriHelper.CreatePartUri(new Uri(file.Value, UriKind.Relative)), System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum); using (FileStream fileStream = new FileStream(file.Key, FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, part.GetStream()); } } } return(filepath); }
/// <summary> /// Stores meta data (i.e. data needed to decompress and test the file) for the compressed <paramref name="filePart" /> /// . /// </summary> /// <param name="filePart">The compressed file which meta data should be stored.</param> /// <param name="frequencyTable">The frequency table needed to restore the Huffman tree (for file decoding). </param> /// <param name="uncompressedHashSum">The hashsum needed to test file correctness after unpacking.</param> /// <param name="compressedHashSum">The hashsum needed to test compressed file correctness before unpacking.</param> /// <param name="ratio">The compression ratio shown to the user.</param> /// <param name="uncompressed">Size of the file before compression.</param> /// <param name="compressed">Size of the compressed file.</param> private void StoreMetaData(PackagePart filePart, FrequencyTable frequencyTable, byte[] uncompressedHashSum, byte[] compressedHashSum, double ratio, long uncompressed, long compressed, string name) { /* collect metadate into a class */ var meta = new FileMetaData { frequencyTable = frequencyTable, compressedHash = compressedHashSum, uncompressedHash = uncompressedHashSum, compressionRatio = ratio, uncompressedSize = uncompressed, compressedSize = compressed, filename = name }; /* create path (relating to the archive root) where the meta data will be stored */ var metaUri = PackUriHelper.CreatePartUri(new Uri(filePart.Uri + "META", UriKind.Relative)); /* create a package part in the path */ var metaPart = _archive.CreatePart(metaUri, "", CompressionOption.NotCompressed); filePart.CreateRelationship(metaUri, TargetMode.Internal, ".\\META"); using (var metaStream = new BufferedStream(metaPart.GetStream(), BufferSize)) { var formatter = new BinaryFormatter(); formatter.Serialize(metaStream, meta); } }
//TODO: Constructor is doing too much public MimetypeComponent() { _uriString = "mimetype"; _partUri = PackUriHelper.CreatePartUri(new Uri(UriString, UriKind.Relative)); BuildContent(); }
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); } }
private static void SendThumbnailsToClient(string keyword, string returnPath, string archiveInfoPath) { _currentId = 0; // used to create a unique name of a thumbnail string thumbnailPackPath = returnPath + "\\" + SharedLibrary.ThumbnailPackName; using (Package thumbnailPack = Package.Open(thumbnailPackPath, FileMode.Create)) { // The thumbnail package has an Info.xml part, which contains the // ID of thumbnails. Uri infoXmlUri = PackUriHelper.CreatePartUri( new Uri(SharedLibrary.InfoXmlName, UriKind.Relative)); PackagePart InfoXmlPart = thumbnailPack.CreatePart(infoXmlUri, SharedLibrary.InfoContentType, CompressionOption.Normal); // Creates a relationship for the thumbnail package, which points // to the Info.xml part. thumbnailPack.CreateRelationship(infoXmlUri, TargetMode.Internal, SharedLibrary.InfoRelationshipType); using (XmlTextWriter infoXmlWriter = new XmlTextWriter(InfoXmlPart.GetStream(), Encoding.UTF8)) { infoXmlWriter.WriteStartDocument(); infoXmlWriter.WriteStartElement("Thumbnails", SharedLibrary.Namespace); DirectoryInfo archiveInfoDir = new DirectoryInfo(archiveInfoPath); Console.WriteLine( "Retrieving thumbnails with keyword '{0}' from snapshot package(s).", keyword); Console.WriteLine("------------------------------------------------------------------------------"); foreach (FileInfo fi in archiveInfoDir.GetFiles("*" + SharedLibrary.PackageExt)) { Console.WriteLine("<Snapshot Package>:\n\t" + fi.FullName); ExtractThumbnailsByKeyword(fi, thumbnailPack, infoXmlWriter, keyword); } Console.WriteLine("------------------------------------------------------------------------------"); infoXmlWriter.WriteEndDocument(); } } Console.WriteLine("Successfully created a thumbnail package with retrieved thumbnails and sent it to the client."); Console.WriteLine("------------------------------------------------------------------------------"); Console.WriteLine("<Thumbnail Package>:\n\t" + thumbnailPackPath); Console.WriteLine("------------------------------------------------------------------------------"); }
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) } }); } }
private static Uri CopyThumbnail(Package destPackage, Package srcPackage, string srcThumnailPartName) { Uri srcThumbnailUri = new Uri(srcThumnailPartName, UriKind.Relative); if (!srcPackage.PartExists(srcThumbnailUri)) { Console.WriteLine(srcThumnailPartName + " doesn't exist!"); return(null); } PackagePart srcPart = srcPackage.GetPart(srcThumbnailUri); string extension = Path.GetExtension(srcThumnailPartName); Uri destPartUri = PackUriHelper.CreatePartUri( new Uri(CreateThumbnailName(extension), UriKind.Relative)); PackagePart destPart = destPackage.CreatePart(destPartUri, srcPart.ContentType); using (Stream srcStream = srcPart.GetStream(), destStream = destPart.GetStream()) { SharedLibrary.CopyStream(srcStream, destStream); } // end using (srcStream and destStream), close them. return(destPartUri); }
private static Uri GetPartUriFile(Uri rootUri, FileInfo file) { var uriFile = rootUri.MakeRelativeUri(new Uri(file.FullName, UriKind.Absolute)); var partUriFile = PackUriHelper.CreatePartUri(uriFile); return(partUriFile); }
public ImageContentComponent(string ImageUrl) { _originalUri = ImageUrl; Guid imgguid = Guid.NewGuid(); string imagename = imgguid.ToString("N"); _uriString = @"images/" + imagename.ToString(); _partUri = PackUriHelper.CreatePartUri(new Uri(UriString, UriKind.Relative)); try { WebClient wc = new WebClient(); _content = wc.DownloadData(ImageUrl); _mediaMimeType = wc.ResponseHeaders["Content-type"]; if (!(_content.Length > 0)) { throw new NotSupportedException("No image data found"); } } catch (Exception ex) { // Unable to retrieve image Console.WriteLine(ex.Message); _content = File.ReadAllBytes("not-found.gif"); _mediaMimeType = System.Net.Mime.MediaTypeNames.Image.Gif; } }
// -------------------------- CreatePackage -------------------------- /// <summary> /// Creates a package zip file containing specified /// content and resource files.</summary> /// <param name="packageFilename"> /// The filename of the Package to create.</param> private static void CreatePackage(String packageFilename) { // Create URIs for the parts that will be added to the Package. Uri uriDocument = new Uri(@"Content\Document.xml", UriKind.Relative); Uri uriResource = new Uri(@"Resources\Image1.jpg", UriKind.Relative); // CreatePartUri converts the content file names to part names. Uri partUriDocument = PackUriHelper.CreatePartUri(uriDocument); Uri partUriResource = PackUriHelper.CreatePartUri(uriResource); // Create the Package // (If the package file already exists, FileMode.Create will // automatically delete it first before creating a new one. // The 'using' keyword ensures that 'package' is // closed and disposed when it goes out of scope.) using (Package package = Package.Open(packageFilename, FileMode.Create)) { // Add a Document part to the Package. PackagePart packagePartDocument = package.CreatePart(partUriDocument, System.Net.Mime.MediaTypeNames.Text.Xml); // Add content to the Document Part. using (FileStream fileStream = new FileStream(uriDocument.ToString(), FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, packagePartDocument.GetStream()); } // Add a Package Relationship to the Document Part. package.CreateRelationship(packagePartDocument.Uri, TargetMode.Internal, _samplePackageRelationshipType); // Add a Resource Part to the Package. PackagePart packagePartResource = package.CreatePart(partUriResource, System.Net.Mime.MediaTypeNames.Image.Jpeg); // Add content to the Resource Part using (FileStream fileStream = new FileStream(uriResource.ToString(), FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, packagePartResource.GetStream()); } // Add a Relationship from the Document part to the Resource part packagePartDocument.CreateRelationship( new Uri(@"../Resources/Image1.jpg", UriKind.Relative), TargetMode.Internal, _sampleResourceRelationshipType); // Flush the package to ensure all data is written. package.Flush(); // Digitally sign all the Parts and Relationships in the Package. SignAllParts(package); } // end:using (package) - Close and dispose 'package' } // end:CreatePackage()
private static void PackFilesToZip(string logFolder, string yearMonth, List <string> logList) { string zipFilename = Path.Combine(logFolder, String.Format("{0}.log.zip", yearMonth)); using (Package zip = Package.Open(zipFilename, FileMode.OpenOrCreate)) { foreach (var l in logList) { string destFilename = Path.GetFileName(l); 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(l, FileMode.Open, FileAccess.Read)) { using (Stream dest = part.GetStream()) { CopyStream(fileStream, dest); } } } } logList.ForEach((x) => File.Delete(x)); }