private static bool TrySignPackagePart(PackagePart packagePart, string keyPath, string keyPassword, bool signedPackage) { if (packagePart.Uri.ToString().EndsWith(".exe") || packagePart.Uri.ToString().EndsWith(".dll")) { string tempPath = Path.GetTempFileName(); try { using (var stream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write)) { packagePart.GetStream().CopyTo(stream); } if (!SigningHelper.GetAssemblyInfo(tempPath).IsSigned) { signedPackage = true; SigningHelper.SignAssembly(tempPath, keyPath ?? string.Empty, keyPassword ?? string.Empty); using (var stream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Read)) { stream.CopyTo(packagePart.GetStream(FileMode.Create, FileAccess.Write)); } } } finally { File.Delete(tempPath); } } return signedPackage; }
internal ExcelPicture(ExcelDrawings drawings, XmlNode node) : base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/@name") { XmlNode picNode = node.SelectSingleNode("xdr:pic/xdr:blipFill/a:blip", drawings.NameSpaceManager); if (picNode != null) { RelPic = drawings.Part.GetRelationship(picNode.Attributes["r:embed"].Value); UriPic = PackUriHelper.ResolvePartUri(drawings.UriDrawing, RelPic.TargetUri); Part = drawings.Part.Package.GetPart(UriPic); FileInfo f = new FileInfo(UriPic.OriginalString); ContentType = GetContentType(f.Extension); _image = Image.FromStream(Part.GetStream()); ImageConverter ic=new ImageConverter(); var iby=(byte[])ic.ConvertTo(_image, typeof(byte[])); var ii = _drawings._package.LoadImage(iby, UriPic, Part); ImageHash = ii.Hash; string relID = GetXmlNodeString("xdr:pic/xdr:nvPicPr/xdr:cNvPr/a:hlinkClick/@r:id"); if (!string.IsNullOrEmpty(relID)) { HypRel = drawings.Part.GetRelationship(relID); if (HypRel.TargetUri.IsAbsoluteUri) { _hyperlink = new ExcelHyperLink(HypRel.TargetUri.AbsoluteUri); } else { _hyperlink = new ExcelHyperLink(HypRel.TargetUri.OriginalString, UriKind.Relative); } ((ExcelHyperLink)_hyperlink).ToolTip = GetXmlNodeString("xdr:pic/xdr:nvPicPr/xdr:cNvPr/a:hlinkClick/@tooltip"); } } }
protected override void UpdateServiceDescriptionPart(PackagePart serviceDescriptionPart) { var definitionSerializer = new XmlSerializer(typeof(ServiceDefinition)); var packageStream = serviceDescriptionPart.GetStream(FileMode.Open, FileAccess.ReadWrite); var serviceDefinition = definitionSerializer.Deserialize(packageStream) as ServiceDefinition; UpdateServiceDefinition(serviceDefinition); // rewind package stream packageStream.Seek(0, SeekOrigin.Begin); packageStream.SetLength(0); var writerSettings = new XmlWriterSettings() { Indent = true, CloseOutput = false }; // write back to output using (var writer = XmlWriter.Create(packageStream, writerSettings)) { definitionSerializer.Serialize(writer, serviceDefinition); } }
private void UpdatePackageManifest(Package package, PackagePart updatedPart) { if (package == null) throw new ArgumentNullException(nameof(package)); if (updatedPart == null) throw new ArgumentNullException(nameof(updatedPart)); if (package.FileOpenAccess != FileAccess.ReadWrite) throw new InvalidOperationException("Package must be open for reading and writing"); var manifestRelation = package.GetRelationship("MANIFEST"); var manifestPart = package.GetPart(manifestRelation.TargetUri); // parse manifest var manifest = new PackageManifest(manifestPart, null); // rehash updated part var csDefPart = manifest.Items.FirstOrDefault(i => i.PartUri == updatedPart.Uri); if (csDefPart == null) throw new InvalidOperationException(string.Format("Unable to find part '{0}' in package manifest", updatedPart.Uri)); csDefPart.Hash = manifest.HashAlgorithm.ComputeHash(updatedPart.GetStream(FileMode.Open, FileAccess.Read)); ; csDefPart.ModifiedDate = DateTime.UtcNow; var manifestStream = manifestPart.GetStream(FileMode.Open, FileAccess.Write); manifest.WriteToStream(manifestStream); }
private void SignPackagePart(PackagePart packagePart) { foreach (var signer in _signerRepository) { signer.TrySign(packagePart); } }
private static void ExtractContentFile(string rootFolder, PackagePart contentFile) { // Initially create file under the folder specified string contentFilePath = contentFile.Uri.OriginalString.Replace('/', Path.DirectorySeparatorChar); if (contentFilePath.StartsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))) { contentFilePath = contentFilePath.TrimStart(Path.DirectorySeparatorChar); } contentFilePath = Path.Combine(rootFolder, contentFilePath); //Check for the folder already exists. If not then create that folder if (!Directory.Exists(Path.GetDirectoryName(contentFilePath))) { Directory.CreateDirectory(Path.GetDirectoryName(contentFilePath)); } using (var newFileStream = File.Create(contentFilePath)) { newFileStream.Close(); var content = new byte[contentFile.GetStream().Length]; contentFile.GetStream().Read(content, 0, content.Length); File.WriteAllBytes(contentFilePath, content); } }
private static IconDef FromXml(XElement xml, PackagePart part) { var icon = xml.Attr<string>("icon"); if (icon != null) icon = part.GetRelationship(icon).TargetUri.OriginalString; return new IconDef { Icon = icon, Pattern = xml.Attr<string>("pattern")}; }
/// <summary> /// Returns the part contents in xml /// </summary> /// <param name="part">System.IO.Packaging.Packagepart</param> /// <returns></returns> static XElement GetContentsAsXml(PackagePart part) { XNamespace pkg = "http://schemas.microsoft.com/office/2006/xmlPackage"; if (part.ContentType.EndsWith("xml")) { using (Stream partstream = part.GetStream()) using (StreamReader streamReader = new StreamReader(partstream)) { string streamString = streamReader.ReadToEnd(); XElement newXElement = new XElement(pkg + "part", new XAttribute(pkg + "name", part.Uri), new XAttribute(pkg + "contentType", part.ContentType), new XElement(pkg + "xmlData", XElement.Parse(streamString))); return newXElement; } } else { using (Stream str = part.GetStream()) using (BinaryReader binaryReader = new BinaryReader(str)) { int len = (int)binaryReader.BaseStream.Length; byte[] byteArray = binaryReader.ReadBytes(len); // the following expression creates the base64String, then chunks // it to lines of 76 characters long string base64String = (System.Convert.ToBase64String(byteArray)) .Select ( (c, i) => new { Character = c, Chunk = i / 76 } ) .GroupBy(c => c.Chunk) .Aggregate( new StringBuilder(), (s, i) => s.Append( i.Aggregate( new StringBuilder(), (seed, it) => seed.Append(it.Character), sb => sb.ToString() ) ) .Append(Environment.NewLine), s => s.ToString() ); return new XElement(pkg + "part", new XAttribute(pkg + "name", part.Uri), new XAttribute(pkg + "contentType", part.ContentType), new XAttribute(pkg + "compression", "store"), new XElement(pkg + "binaryData", base64String) ); } } }
internal static SharedDef LoadFromXml(XElement xml, PackagePart part) { if (xml == null) return null; var res = new SharedDef(); res.LoadBaseXml(xml, part); return res; }
public static List<FontDef> LoadAllFromXml(XElement xml, PackagePart part) { if (xml == null) return new List<FontDef>(0); return xml.Elements("font") .Select(x => FromXml(x, part)) .ToList(); }
private static void CopyPart(PackagePart oldPart, PackagePart newPart) { using (Stream oldPartStream = oldPart.GetStream(), newPartStream = newPart.GetStream(FileMode.OpenOrCreate)) { oldPartStream.CopyTo(newPartStream); } }
internal static CardDef LoadFromXml(XElement xml, PackagePart part) { var backUri = xml.Attr<string>("back"); if (backUri != null) backUri = part.GetRelationship(backUri).TargetUri.OriginalString; var frontUri = xml.Attr<string>("front"); if (frontUri != null) frontUri = part.GetRelationship(frontUri).TargetUri.OriginalString; var cd = new CardDef { back = backUri, front = frontUri, Width = xml.Attr<int>("width"), Height = xml.Attr<int>("height"), CornerRadius = xml.Attr<int>("cornerRadius"), //Properties = xml.Elements(Defs.XmlnsOctgn + "property") // //.Select(PropertyDef.LoadFromXml) // .ToDictionary(x => x.Name) }; var list = xml.Elements(Defs.XmlnsOctgn + "property"); var proplist = new Dictionary<string,PropertyDef>(); foreach (var l in list) { var name = l.Attr<string>("name"); string kindStr = l.Attr("textKind", "Free"); PropertyTextKind kind; switch (kindStr) { case "Free": kind = PropertyTextKind.FreeText; break; case "Enum": kind = PropertyTextKind.Enumeration; break; case "Tokens": kind = PropertyTextKind.Tokens; break; default: throw new InvalidFileFormatException( string.Format("Unknown value '{0}' for textKind attribute (Property = {1})", kindStr, name)); } var prop = new PropertyDef { Name = name, Type = l.Attr<PropertyType>("type"), IgnoreText = l.Attr<bool>("ignoreText"), TextKind = kind, Hidden = l.Attr<bool>("hidden") }; proplist.Add(name,prop); } cd.Properties = proplist; return cd; }
private static bool CreateRelationshipAndTargetPart( System.IO.Packaging.Package package, System.IO.Packaging.PackagePart sourcePart, string sourceTargetFilePath, string targetUri, string targetMimeType, string relationshipTypeUri) { System.IO.Packaging.PackagePart targetPart; return(CreateRelationshipAndTargetPart( package, sourcePart, sourceTargetFilePath, targetUri, targetMimeType, relationshipTypeUri, out targetPart)); }
public static ScriptDef FromXml(XElement xml, PackagePart part) { string srcUri = part.GetRelationship(xml.Attr<string>("src")).TargetUri.OriginalString; PackagePart scriptPart = part.Package.GetPart(new Uri(srcUri, UriKind.Relative)); using (Stream stream = scriptPart.GetStream(FileMode.Open, FileAccess.Read)) using (var textReader = new StreamReader(stream)) return new ScriptDef {Python = textReader.ReadToEnd(), FileName = srcUri}; }
internal static PlayerDef LoadFromXml(XElement xml, PackagePart part) { var res = new PlayerDef { IndicatorsFormat = xml.Attr<string>("summary"), Hand = GroupDef.LoadFromXml(xml.Child("hand"), part, 0) }; res.LoadBaseXml(xml, part); return res; }
public ZipPackageAssemblyReference(PackagePart part) : base(part) { Debug.Assert(Path.StartsWith("lib", StringComparison.OrdinalIgnoreCase), "path doesn't start with lib"); // Get rid of the lib folder string path = Path.Substring(3).Trim(System.IO.Path.DirectorySeparatorChar); _targetFramework = VersionUtility.ParseFrameworkFolderName(path); }
internal Hyperlink(DocX document, PackagePart mainPart, XElement i) : base(document, i) { this.type = 0; this.id = i.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value; StringBuilder sb = new StringBuilder(); HelperFunctions.GetTextRecursive(i, ref sb); this.text = sb.ToString(); }
void ExtractPart(PackagePart part, string destinationPath) { fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(destinationPath)); using (var packageFileStream = part.GetStream()) using (var destinationFileStream = fileSystem.OpenFile(destinationPath, FileMode.Create)) { packageFileStream.CopyTo(destinationFileStream); destinationFileStream.Flush(); } }
protected void LoadBaseXml(XElement xml, PackagePart part) { int i = 1; Counters = xml.Elements(Defs.XmlnsOctgn + "counter") .Select(x => CounterDef.LoadFromXml(x, part, i++)) .ToArray(); i = 1; Groups = xml.Elements(Defs.XmlnsOctgn + "group") .Select(x => GroupDef.LoadFromXml(x, part, i++)) .ToArray(); }
public ZipPackageFile(PackagePart part) : base(UriUtility.GetPath(part.Uri)) { Debug.Assert(part != null, "part should not be null"); byte[] buffer; using (Stream partStream = part.GetStream()) { buffer = partStream.ReadAllBytes(); } _streamFactory = () => new MemoryStream(buffer); }
public bool TrySign(PackagePart packagePart) { if (!CanSign(packagePart)) return false; var digest = GetDigest(packagePart); var signedDigest = _keyVaultAgent.Sign(digest); InsertSignedDigest(packagePart, signedDigest); return true; }
public string GetFileHash(PackagePart part) { using (var inputStream = part.GetStream()) using (var md5 = new MD5CryptoServiceProvider()) { var hash = md5.ComputeHash(inputStream); var sb = new StringBuilder(); foreach (var b in hash) { sb.Append(string.Format("{0:X2}", b)); } return sb.ToString(); } }
public DocxReader(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); this.package = Package.Open(stream, FileMode.Open, FileAccess.Read); foreach (var relationship in this.package.GetRelationshipsByType(MainDocumentRelationshipType)) { this.mainDocumentPart = package.GetPart(PackUriHelper.CreatePartUri(relationship.TargetUri)); break; } }
public ZipPackageFile(PackagePart part) { Debug.Assert(part != null, "part should not be null"); byte[] buffer; using (Stream partStream = part.GetStream()) { using (var stream = new MemoryStream()) { partStream.CopyTo(stream); buffer = stream.ToArray(); } } _path = UriUtility.GetPath(part.Uri); _streamFactory = () => new MemoryStream(buffer); }
private static void ExtractPart(PackagePart packagePart, string pathToTarget) { string stringPart = packagePart.Uri.ToString().TrimStart('/'); Uri partUri = new Uri(stringPart, UriKind.Relative); Uri uriFullPartPath = new Uri(new Uri(pathToTarget, UriKind.Absolute), partUri); Directory.CreateDirectory( Path.GetDirectoryName(uriFullPartPath.LocalPath)); using (FileStream fileStream = new FileStream(uriFullPartPath.LocalPath, FileMode.Create)) { CopyStream(packagePart.GetStream(), fileStream); } }
private static bool CanSign(PackagePart packagePart) { if (!IsAssembly(packagePart)) { return false; } if (IsSigned(packagePart)) { return false; } return true; }
private void UpdateServiceDescriptionPackage(PackagePart servicePackageDescriptionPart) { // open service description package var descPackage = Package.Open(servicePackageDescriptionPart.GetStream(FileMode.Open, FileAccess.ReadWrite), FileMode.Open, FileAccess.ReadWrite); var descPackageRelation = descPackage.GetRelationship("SERVICEDESCRIPTION"); var descPackagePart = descPackage.GetPart(descPackageRelation.TargetUri); // update service description content UpdateServiceDescriptionPart(descPackagePart); // update inner package manifest UpdatePackageManifest(descPackage, descPackagePart); descPackage.Flush(); descPackage.Close(); }
internal static CounterDef LoadFromXml(XElement xml, PackagePart part, int index) { var icon = xml.Attr<string>("icon"); if (icon != null) icon = part.GetRelationship(icon).TargetUri.OriginalString; return new CounterDef { Id = (byte) index, Name = xml.Attr<string>("name"), Icon = icon, Start = xml.Attr<int>("default"), Reset = xml.Attr("reset", true) }; }
/// <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); } } } } }
/// <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 Extract(PackagePart part, string outPath) { string outFileName = Path.Combine(outPath, part.Uri.OriginalString.Substring(1)); if (!Directory.Exists(Path.GetDirectoryName(outFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(outFileName)); } using (System.IO.FileStream outFileStream = new System.IO.FileStream(outFileName, FileMode.Create)) { using (Stream inFileStream = part.GetStream()) { CopyStream(inFileStream, outFileStream); } } }
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(); }
/// <summary> /// Factory method that creates a new PackageDigitalSignature /// </summary> internal static PackageDigitalSignature Sign( PackageDigitalSignatureManager manager, PackagePart signaturePart, IEnumerable<Uri> parts, IEnumerable<PackageRelationshipSelector> relationshipSelectors, X509Certificate2 signer, String signatureId, bool embedCertificate, IEnumerable<System.Security.Cryptography.Xml.DataObject> signatureObjects, IEnumerable<System.Security.Cryptography.Xml.Reference> objectReferences) { // create XmlDigitalSignatureProcessor p = new XmlDigitalSignatureProcessor(manager, signaturePart); // and sign return p.Sign(parts, relationshipSelectors, signer, signatureId, embedCertificate, signatureObjects, objectReferences); }
public ExcelDrawings(ExcelPackage xlPackage, ExcelWorksheet sheet) { _drawingsXml = new XmlDocument(); _drawingsXml.PreserveWhitespace = true; _drawings = new Dictionary<int, ExcelDrawing>(); XmlNode node = sheet.WorksheetXml.SelectSingleNode("//d:drawing", sheet.NameSpaceManager); CreateNSM(); if (node != null) { PackageRelationship drawingRelation = sheet.Part.GetRelationship(node.Attributes["r:id"].Value); _uriDrawing = PackUriHelper.ResolvePartUri(sheet.WorksheetUri, drawingRelation.TargetUri); _part = xlPackage.Package.GetPart(_uriDrawing); _drawingsXml.Load(_part.GetStream()); AddDrawings(); } }
/// <summary> /// Constructor /// </summary> /// <remarks>For use by PackagePart</remarks> internal InternalRelationshipCollection(PackagePart part) : this(part.Package, part) { }
//------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// This method returns the list of selected PackageRelationships as per the /// given criteria, from a part in the Package provided /// </summary> /// <param name="package">Package object from which we get the relationships</param> /// <returns></returns> /// <exception cref="ArgumentNullException">If package parameter is null</exception> public List <PackageRelationship> Select(Package package) { if (package == null) { throw new ArgumentNullException(nameof(package)); } List <PackageRelationship> relationships = new List <PackageRelationship>(0); switch (SelectorType) { case PackageRelationshipSelectorType.Id: if (SourceUri.Equals(PackUriHelper.PackageRootUri)) { if (package.RelationshipExists(SelectionCriteria)) { relationships.Add(package.GetRelationship(SelectionCriteria)); } } else { if (package.PartExists(SourceUri)) { PackagePart part = package.GetPart(SourceUri); if (part.RelationshipExists(SelectionCriteria)) { relationships.Add(part.GetRelationship(SelectionCriteria)); } } } break; case PackageRelationshipSelectorType.Type: if (SourceUri.Equals(PackUriHelper.PackageRootUri)) { foreach (PackageRelationship r in package.GetRelationshipsByType(SelectionCriteria)) { relationships.Add(r); } } else { if (package.PartExists(SourceUri)) { foreach (PackageRelationship r in package.GetPart(SourceUri).GetRelationshipsByType(SelectionCriteria)) { relationships.Add(r); } } } break; default: //Debug.Assert is fine here since the parameters have already been validated. And all the properties are //readonly Debug.Assert(false, "This option should never be called"); break; } return(relationships); }
// Deserialize properties part. private void ParseCorePropertyPart(PackagePart part) { XmlReaderSettings xrs = new XmlReaderSettings(); xrs.NameTable = _nameTable; using (Stream stream = part.GetStream(FileMode.Open, FileAccess.Read)) // Create a reader that uses _nameTable so as to use the set of tag literals // in effect as a set of atomic identifiers. using (XmlReader reader = XmlReader.Create(stream, xrs)) { //This method expects the reader to be in ReadState.Initial. //It will make the first read call. PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader); //Note: After the previous method call the reader should be at the first tag in the markup. //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace //If the reader is currently at a content node then this function call is a no-op if (reader.MoveToContent() != XmlNodeType.Element || (object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.PackageCorePropertiesNamespace) || (object)reader.LocalName != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.CoreProperties)) { throw new XmlException(SR.CorePropertiesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // The schema is closed and defines no attributes on the root element. if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 0) { throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // Iterate through property elements until EOF. Note the proper closing of all // open tags is checked by the reader itself. // This loop deals only with depth-1 start tags. Handling of element content // is delegated to dedicated functions. int attributesCount; while (reader.Read() && reader.MoveToContent() != XmlNodeType.None) { // Ignore end-tags. We check element errors on opening tags. if (reader.NodeType == XmlNodeType.EndElement) { continue; } // Any content markup that is not an element here is unexpected. if (reader.NodeType != XmlNodeType.Element) { throw new XmlException(SR.PropertyStartTagExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // Any element below the root should open at level 1 exclusively. if (reader.Depth != 1) { throw new XmlException(SR.NoStructuredContentInsideProperties, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } attributesCount = PackagingUtilities.GetNonXmlnsAttributeCount(reader); // Property elements can occur in any order (xsd:all). object localName = reader.LocalName; PackageXmlEnum xmlStringIndex = PackageXmlStringTable.GetEnumOf(localName); String valueType = PackageXmlStringTable.GetValueType(xmlStringIndex); if (Array.IndexOf(s_validProperties, xmlStringIndex) == -1) // An unexpected element is an error. { throw new XmlException( SR.Format(SR.InvalidPropertyNameInCorePropertiesPart, reader.LocalName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } // Any element not in the valid core properties namespace is unexpected. // The following is an object comparison, not a string comparison. if ((object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlStringTable.GetXmlNamespace(xmlStringIndex))) { throw new XmlException(SR.UnknownNamespaceInCorePropertiesPart, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } if (String.CompareOrdinal(valueType, "String") == 0) { // The schema is closed and defines no attributes on this type of element. if (attributesCount != 0) { throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } RecordNewBinding(xmlStringIndex, GetStringData(reader), true /*initializing*/, reader); } else if (String.CompareOrdinal(valueType, "DateTime") == 0) { int allowedAttributeCount = (object)reader.NamespaceURI == PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace) ? 1 : 0; // The schema is closed and defines no attributes on this type of element. if (attributesCount != allowedAttributeCount) { throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition); } if (allowedAttributeCount != 0) { ValidateXsiType(reader, PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace), W3cdtf); } RecordNewBinding(xmlStringIndex, GetDateData(reader), true /*initializing*/, reader); } else // An unexpected element is an error. { Debug.Assert(false, "Unknown value type for properties"); } } } }
/// <summary> /// Parse PackageRelationship Stream /// </summary> /// <param name="part">relationship part</param> /// <exception cref="XmlException">Thrown if XML is malformed</exception> private void ParseRelationshipPart(PackagePart part) { //We can safely open the stream as FileAccess.Read, as this code //should only be invoked if the Package has been opened in Read or ReadWrite mode. Debug.Assert(_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite, "This method should only be called when FileAccess is Read or ReadWrite"); using (Stream s = part.GetStream(FileMode.Open, FileAccess.Read)) { // load from the relationship part associated with the given part using (XmlReader baseReader = XmlReader.Create(s)) { using (XmlCompatibilityReader reader = new XmlCompatibilityReader(baseReader, s_relationshipKnownNamespaces)) { //This method expects the reader to be in ReadState.Initial. //It will make the first read call. PackagingUtilities.PerformInitialReadAndVerifyEncoding(baseReader); //Note: After the previous method call the reader should be at the first tag in the markup. //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace //If the reader is currently at a content node then this function call is a no-op reader.MoveToContent(); // look for our tag and namespace pair - throw if other elements are encountered // Make sure that the current node read is an Element if (reader.NodeType == XmlNodeType.Element && (reader.Depth == 0) && (string.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0) && (string.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0)) { ThrowIfXmlBaseAttributeIsPresent(reader); //There should be a namespace Attribute present at this level. //Also any other attribute on the <Relationships> tag is an error including xml: and xsi: attributes if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0) { throw new XmlException(SR.RelationshipsTagHasExtraAttributes, null, reader.LineNumber, reader.LinePosition); } // start tag encountered for Relationships // now parse individual Relationship tags while (reader.Read()) { //Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace //If the reader is currently at a content node then this function call is a no-op reader.MoveToContent(); //If MoveToContent() takes us to the end of the content if (reader.NodeType == XmlNodeType.None) { continue; } if (reader.NodeType == XmlNodeType.Element && (reader.Depth == 1) && (string.CompareOrdinal(s_relationshipTagName, reader.LocalName) == 0) && (string.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0)) { ThrowIfXmlBaseAttributeIsPresent(reader); int expectedAttributesCount = 3; string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName); if (targetModeAttributeValue != null) { expectedAttributesCount++; } //check if there are expected number of attributes. //Also any other attribute on the <Relationship> tag is an error including xml: and xsi: attributes if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) == expectedAttributesCount) { ProcessRelationshipAttributes(reader); //Skip the EndElement for Relationship if (!reader.IsEmptyElement) { ProcessEndElementForRelationshipTag(reader); } } else { throw new XmlException(SR.RelationshipTagDoesntMatchSchema, null, reader.LineNumber, reader.LinePosition); } } else if (!(string.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0 && (reader.NodeType == XmlNodeType.EndElement))) { throw new XmlException(SR.UnknownTagEncountered, null, reader.LineNumber, reader.LinePosition); } } } else { throw new XmlException(SR.ExpectedRelationshipsElementTag, null, reader.LineNumber, reader.LinePosition); } } } } }
/// <summary> /// Cache version of GetResponseStream /// </summary> /// <returns></returns> internal Stream GetResponseStream() { // prevent concurrent access to GetPart() which is not thread-safe lock (_cacheEntry) { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Getting response stream"); #endif // only one copy if (_parent._responseStream == null) { // full container request? if (_parent._partName == null) { Debug.Assert(false, "Cannot return full-container stream from cached container object"); } else { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Getting part " + _parent._partName); #endif // open the requested stream PackagePart p = _cacheEntry.GetPart(_parent._partName); #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Getting part stream "); #endif Stream s = p.GetStream(FileMode.Open, FileAccess.Read); // Unless package is thread-safe, wrap the returned stream so that // package access is serialized if (!_cachedPackageIsThreadSafe) { // Return a stream that provides thread-safe access // to the cached package by locking on the cached Package s = new SynchronizingStream(s, _cacheEntry); } #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Getting part contenttype"); #endif _parent._mimeType = new MS.Internal.ContentType(p.ContentType); // cache this in case they ask for it after the stream has been closed _parent._lengthAvailable = s.CanSeek; if (s.CanSeek) { #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Length is available from stream"); #endif _parent._fullStreamLength = s.Length; } #if DEBUG else { if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "CachedResponse - Length is not available from stream" + _parent._partName); } #endif // re-use existing member variable _parent._responseStream = s; } } } return _parent._responseStream; }
public override Stream GetResponseStream() { CheckDisposed(); // redirect if (FromPackageCache) return _cachedResponse.GetResponseStream(); EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXGetStreamBegin); #if DEBUG if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse - GetResponseStream()"); #endif // create and return only a single stream for multiple calls if (_responseStream == null) { // can't do this until the response is available WaitForResponse(); // after this call, we have a viable _fullResponse object because WaitForResponse would have thrown otherwise // determine content length long streamLength = _fullResponse.ContentLength; #if DEBUG if (_forceWebResponseLengthFailureSwitch.Enabled) streamLength = -1; // special handling for servers that won't or can't give us the length of the resource - byte-range downloading is impossible if (streamLength <= 0) { if (PackWebRequestFactory._traceSwitch.Enabled) System.Diagnostics.Trace.TraceInformation( DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " + System.Threading.Thread.CurrentThread.ManagedThreadId + ": " + "PackWebResponse - GetResponseStream() - stream length not available - disabling progressive download"); } #endif // Start reading data from the response stream. _responseStream = _fullResponse.GetResponseStream(); // require NetStream for progressivity and for network streams that don't // directly support seeking. if (!_responseStream.CanSeek || !_innerUri.IsFile) { // Create a smart stream that will spawn byte-range requests as needed // and support seeking. Each read has overhead of Mutex and many of the // reads come through asking for 4 bytes at a time _responseStream = new NetStream( _responseStream, streamLength, _innerUri, _webRequest, _fullResponse); // wrap our stream for efficiency (short reads are expanded) _responseStream = new BufferedStream(_responseStream); } // handle degenerate case where there is no part name if (_partName == null) { _fullStreamLength = streamLength; // entire container _mimeType = WpfWebRequestHelper.GetContentType(_fullResponse); // pass this so that ResponseStream holds a reference to us until the stream is closed _responseStream = new ResponseStream(_responseStream, this); } else { // open container on netStream Package c = Package.Open(_responseStream); if (!c.PartExists(_partName)) throw new WebException(SR.Get(SRID.WebResponsePartNotFound)); PackagePart p = c.GetPart(_partName); Stream s = p.GetStream(FileMode.Open, FileAccess.Read); _mimeType = new MS.Internal.ContentType(p.ContentType); // save this for use in ContentType property - may still be null _fullStreamLength = s.Length; // just this stream // Wrap in a ResponseStream so that this container will be released // when the stream is closed _responseStream = new ResponseStream(s, this, _responseStream, c); } // length available? (-1 means the server chose not to report it) if (_fullStreamLength >= 0) { _lengthAvailable = true; } } EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXGetStreamEnd); return _responseStream; }