public WstRequestSecurityToken Read() { reader.MoveToContent(); reader.ReadStartElement("RequestSecurityToken", Constants.WstNamespace); do { reader.MoveToContent(); switch (reader.NodeType) { case XmlNodeType.EndElement: reader.Read(); // consume RequestSecurityToken end element. return(req); case XmlNodeType.Element: ReadTokenContent(); break; default: throw new XmlException(String.Format("Unexpected request XML {0} node, name {1}{2}", reader.NodeType, reader.Name, LineInfo())); } } while (true); }
public static byte[] MessageToBytes(Message rawMessage) { XmlDictionaryReader bodyReader = rawMessage.GetReaderAtBodyContents(); bodyReader.MoveToContent(); if (bodyReader.NodeType == XmlNodeType.Element && bodyReader.Name == "Binary") { bodyReader.Read(); return(bodyReader.ReadContentAsBase64()); } else { throw new ArgumentException( string.Format( "Message is not a binary message: current node: {0} - {1} - {2}", bodyReader.NodeType, bodyReader.Name, bodyReader.Value)); } }
internal static AddressHeaderCollection ReadServiceParameters(XmlDictionaryReader reader, bool isReferenceProperty) { reader.MoveToContent(); if (reader.IsEmptyElement) { reader.Skip(); return(null); } else { reader.ReadStartElement(); List <AddressHeader> headerList = new List <AddressHeader>(); while (reader.IsStartElement()) { headerList.Add(new BufferedAddressHeader(reader, isReferenceProperty)); } reader.ReadEndElement(); return(new AddressHeaderCollection(headerList)); } }
public T GetDetail <T>(XmlObjectSerializer serializer) { if (serializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(serializer)); } XmlDictionaryReader reader = GetReaderAtDetailContents(); T value = (T)serializer.ReadObject(reader); if (!reader.EOF) { reader.MoveToContent(); if (reader.NodeType != XmlNodeType.EndElement && !reader.EOF) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.ExtraContentIsPresentInFaultDetail)); } } return(value); }
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { reader.ReadFullStartElement(); Dictionary <string, string> r = new Dictionary <string, string>(); while (reader.IsStartElement("property")) { reader.ReadFullStartElement("property"); reader.ReadFullStartElement("key"); string key = reader.ReadContentAsString(); reader.ReadEndElement(); reader.ReadFullStartElement("value"); string value = reader.ReadContentAsString(); reader.ReadEndElement(); r.Add(key, value); reader.ReadEndElement(); reader.MoveToContent(); } return(r); }
public void ReadXml1() { SamlSerializer ser = new SamlSerializer(); string xml = String.Format("<saml:AuthorizationDecisionStatement Decision=\"Deny\" Resource=\"resource\" xmlns:saml=\"{0}\"><saml:Subject><saml:NameIdentifier Format=\"myFormat\" NameQualifier=\"myQualifier\">myName</saml:NameIdentifier></saml:Subject><saml:Action>myAction</saml:Action><saml:Evidence><saml:AssertionIDReference>myID</saml:AssertionIDReference></saml:Evidence></saml:AuthorizationDecisionStatement>", SamlConstants.Namespace); XmlDictionaryReader reader = CreateReader(xml); reader.MoveToContent(); SamlAuthorizationDecisionStatement s = new SamlAuthorizationDecisionStatement(); s.ReadXml(reader, ser, null, null); Assert.AreEqual(SamlAccessDecision.Deny, s.AccessDecision, "#1"); Assert.IsNotNull(s.SamlSubject, "#2"); Assert.AreEqual(1, s.SamlActions.Count, "#3"); Assert.AreEqual("myAction", s.SamlActions [0].Action, "#4"); Assert.IsNotNull(s.Evidence, "#5"); Assert.AreEqual(1, s.Evidence.AssertionIdReferences.Count, "#6"); Assert.AreEqual("myID", s.Evidence.AssertionIdReferences [0], "#7"); Assert.AreEqual("resource", s.Resource, "#8"); }
public XmlDictionaryReader GetReaderAtHeader(int index) { if (index >= l.Count) { throw new ArgumentOutOfRangeException(String.Format("Index is out of range. Current header count is {0}", index)); } MessageHeader item = (MessageHeader)l [index]; XmlReader reader = item is MessageHeader.RawMessageHeader ? ((MessageHeader.RawMessageHeader)item).CreateReader() : XmlReader.Create( new StringReader(item.ToString()), reader_settings); reader.MoveToContent(); XmlDictionaryReader dr = XmlDictionaryReader.CreateDictionaryReader(reader); dr.MoveToContent(); return(dr); }
// FIXME: should be internal public object ReadObject(XmlDictionaryReader r) { try { r.MoveToContent(); if (!r.IsStartElement("root", String.Empty)) { throw new SerializationException( String.Format("Expected element was '{0}', but the actual input element was '{1}' in namespace '{2}'", "root", r.LocalName, r.NamespaceURI)); } return(new JsonSerializationReader(this, r, type, true).ReadRoot()); } catch (FieldAccessException fae) { throw new SecurityException("Deserialization has failed", fae); } catch (MethodAccessException mae) { throw new SecurityException("Deserialization has failed", mae); } catch (SerializationException) { throw; } catch (Exception ex) { throw new SerializationException("Deserialization has failed", ex); } }
public static ReceivedFault CreateFault11(XmlDictionaryReader reader, int maxBufferSize) { reader.ReadStartElement(XD.MessageDictionary.Fault, XD.Message11Dictionary.Namespace); string ns; string name; reader.ReadStartElement(XD.Message11Dictionary.FaultCode, XD.Message11Dictionary.FaultNamespace); XmlUtil.ReadContentAsQName(reader, out name, out ns); FaultCode code = new FaultCode(name, ns); reader.ReadEndElement(); string xmlLang = reader.XmlLang; reader.MoveToContent(); // Don't do IsStartElement. FaultString is required, so let the reader throw. string text = reader.ReadElementContentAsString(XD.Message11Dictionary.FaultString.Value, XD.Message11Dictionary.FaultNamespace.Value); FaultReasonText translation = new FaultReasonText(text, xmlLang); string actor = ""; if (reader.IsStartElement(XD.Message11Dictionary.FaultActor, XD.Message11Dictionary.FaultNamespace)) { actor = reader.ReadElementContentAsString(); } XmlBuffer detail = null; if (reader.IsStartElement(XD.Message11Dictionary.FaultDetail, XD.Message11Dictionary.FaultNamespace)) { detail = new XmlBuffer(maxBufferSize); XmlDictionaryWriter writer = detail.OpenSection(reader.Quotas); writer.WriteNode(reader, false); detail.CloseSection(); detail.Close(); } reader.ReadEndElement(); FaultReason reason = new FaultReason(translation); return(new ReceivedFault(code, reason, actor, actor, detail, EnvelopeVersion.Soap11)); }
public void GetReaderAtHeader() { Message m = Message.CreateMessage(MessageVersion.Default, "test", 1); XmlDictionaryReader r = m.Headers.GetReaderAtHeader(0); XmlDictionaryReader r2 = m.Headers.GetReaderAtHeader(0); using (XmlWriter x = XmlWriter.Create(TextWriter.Null)) { r2.MoveToContent(); while (!r2.EOF) { x.WriteNode(r2, false); } } /* * // Seems like there is some attribute order differences * // in XmlDictionaryReader or XmlWriter, so don't compare * // XML in raw strings. * * StringWriter sw = new StringWriter (); * XmlWriterSettings settings = new XmlWriterSettings (); * settings.OmitXmlDeclaration = true; * settings.ConformanceLevel = ConformanceLevel.Fragment; * XmlWriter w = XmlWriter.Create (sw, settings); * Assert.AreEqual (ReadState.Interactive, r.ReadState, "#1-1"); * Assert.AreEqual (XmlNodeType.Element, r.NodeType, "#1-2"); * while (!r.EOF) * w.WriteNode (r, false); * w.Flush (); * Assert.AreEqual ("<Action a:mustUnderstand=\"1\" xmlns=\"http://www.w3.org/2005/08/addressing\" xmlns:a=\"http://www.w3.org/2003/05/soap-envelope\">test</Action>", sw.ToString (), "#2"); */ Assert.AreEqual(ReadState.Interactive, r.ReadState, "#1-1"); Assert.AreEqual(XmlNodeType.Element, r.NodeType, "#1-2"); Assert.AreEqual("Action", r.LocalName, "#1-3"); Assert.AreEqual("http://www.w3.org/2005/08/addressing", r.NamespaceURI, "#1-4"); Assert.AreEqual("1", r.GetAttribute("mustUnderstand", "http://www.w3.org/2003/05/soap-envelope"), "#1-5"); Assert.AreEqual("test", r.ReadElementContentAsString(), "#1-6"); }
protected override XmlDictionaryReader OnGetReaderAtBodyContents() { if (this.state == BodyState.Created) { return(base.InnerMessage.GetReaderAtBodyContents()); } if (this.bodyDecrypted) { this.EnsureDecryptedBodyStatusDetermined(); } if (this.cachedDecryptedBodyContentReader != null) { XmlDictionaryReader cachedDecryptedBodyContentReader = this.cachedDecryptedBodyContentReader; this.cachedDecryptedBodyContentReader = null; return(cachedDecryptedBodyContentReader); } XmlDictionaryReader reader2 = this.CreateFullBodyReader(); reader2.ReadStartElement(); reader2.MoveToContent(); return(reader2); }
public void WriteBodyToSignThenEncrypt(Stream canonicalStream, EncryptedData encryptedData, SymmetricAlgorithm algorithm) { XmlBuffer buffer = new XmlBuffer(0x7fffffff); XmlDictionaryWriter writer = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); this.WriteBodyToSignThenEncryptWithFragments(canonicalStream, false, null, encryptedData, algorithm, writer); ((IFragmentCapableXmlDictionaryWriter)writer).WriteFragment(this.startBodyFragment.GetBuffer(), 0, (int)this.startBodyFragment.Length); ((IFragmentCapableXmlDictionaryWriter)writer).WriteFragment(this.endBodyFragment.GetBuffer(), 0, (int)this.endBodyFragment.Length); buffer.CloseSection(); buffer.Close(); this.startBodyFragment = null; this.endBodyFragment = null; XmlDictionaryReader reader = buffer.GetReader(0); reader.MoveToContent(); this.bodyPrefix = reader.Prefix; if (reader.HasAttributes) { this.bodyAttributes = System.IdentityModel.XmlAttributeHolder.ReadAttributes(reader); } reader.Close(); }
/// <summary> /// Reads an <see cref="EndpointReference"/> from xml dictionary reader. The addressing version is defaulted to /// <see cref="WSAddressing10Constants.Elements.Address"/>. /// </summary> /// <param name="reader">The xml dictionary reader.</param> /// <returns>An <see cref="EndpointReference"/> instance.</returns> public static EndpointReference ReadFrom(XmlDictionaryReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } reader.ReadFullStartElement(); reader.MoveToContent(); if (reader.IsNamespaceUri(WSAddressing10Constants.NamespaceUri) || reader.IsNamespaceUri(WSAddressing200408Constants.NamespaceUri)) { if (reader.IsStartElement(WSAddressing10Constants.Elements.Address, WSAddressing10Constants.NamespaceUri) || reader.IsStartElement(WSAddressing10Constants.Elements.Address, WSAddressing200408Constants.NamespaceUri)) { EndpointReference er = new EndpointReference(reader.ReadElementContentAsString()); while (reader.IsStartElement()) { bool emptyElement = reader.IsEmptyElement; XmlReader subtreeReader = reader.ReadSubtree(); XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.Load(subtreeReader); er._details.Add(doc.DocumentElement); if (!emptyElement) { reader.ReadEndElement(); } } reader.ReadEndElement(); return(er); } } return(null); }
/// <summary> /// Reads the string as XML and looks for the an element <see cref="SamlConstants.Assertion"/> with namespace <see cref="SamlConstants.Saml11Namespace"/>. /// </summary> /// <param name="securityToken">The securitytoken.</param> /// <returns><see cref="XmlDictionaryReader.IsStartElement"/> (<see cref="SamlConstants.Assertion"/>, <see cref="SamlConstants.Saml11Namespace"/>).</returns> public override bool CanReadToken(string securityToken) { if (string.IsNullOrWhiteSpace(securityToken) || securityToken.Length > MaximumTokenSizeInBytes) { return(false); } using (StringReader sr = new StringReader(securityToken)) { using (XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr))) { try { reader.MoveToContent(); } catch (XmlException) { return(false); } return(reader.IsStartElement(SamlConstants.Assertion, SamlConstants.Saml11Namespace)); } } }
public void WriteXml(XmlWriter xmlWriter) { StringWriter w = new StringWriter(CultureInfo.InvariantCulture); XmlTextWriter writer = new XmlTextWriter(w); this.schema.Write(writer); writer.Flush(); byte[] bytes = new UTF8Encoding().GetBytes(w.ToString()); XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas { MaxDepth = 0x20, MaxStringContentLength = 0x2000, MaxArrayLength = 0x4000, MaxBytesPerRead = 0x1000, MaxNameTableCharCount = 0x4000 }; XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(bytes, 0, bytes.GetLength(0), null, quotas, null); if ((reader.MoveToContent() == XmlNodeType.Element) && (reader.Name == "xs:schema")) { xmlWriter.WriteNode(reader, false); } reader.Close(); }
private void OnEndOfRootElement() { this.elementCount--; if ((this.elementCount == 0) && (this.endFragment.Length == 0L)) { ((IFragmentCapableXmlDictionaryWriter)this.effectiveWriter).EndFragment(); ((IFragmentCapableXmlDictionaryWriter)this.effectiveWriter).StartFragment(this.endFragment, false); this.effectiveWriter.WriteEndElement(); ((IFragmentCapableXmlDictionaryWriter)this.effectiveWriter).EndFragment(); this.effectiveWriter.EndCanonicalization(); ((IFragmentCapableXmlDictionaryWriter)this.effectiveWriter).StartFragment(this.signatureFragment, false); this.callback.OnEndOfRootElement(this); } else if (this.elementCount == 0) { this.effectiveWriter.WriteEndElement(); ((IFragmentCapableXmlDictionaryWriter)this.effectiveWriter).EndFragment(); ((IFragmentCapableXmlDictionaryWriter)this.effectiveWriter).WriteFragment(this.startFragment.GetBuffer(), 0, (int)this.startFragment.Length); ((IFragmentCapableXmlDictionaryWriter)this.effectiveWriter).WriteFragment(this.signatureFragment.GetBuffer(), 0, (int)this.signatureFragment.Length); ((IFragmentCapableXmlDictionaryWriter)this.effectiveWriter).WriteFragment(this.endFragment.GetBuffer(), 0, (int)this.endFragment.Length); this.startFragment.Close(); this.signatureFragment.Close(); this.endFragment.Close(); this.writerStream.Position = 0L; XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(this.writerStream, this.dictionary, XmlDictionaryReaderQuotas.Max); reader.MoveToContent(); this.innerWriter.WriteNode(reader, false); this.innerWriter.Flush(); reader.Close(); this.writerStream.Close(); this.effectiveWriter.Close(); } else { this.effectiveWriter.WriteEndElement(); } }
public void WriteBodyToSignThenEncrypt(Stream canonicalStream, EncryptedData encryptedData, SymmetricAlgorithm algorithm) { XmlBuffer buffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter fragmentingWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); WriteBodyToSignThenEncryptWithFragments(canonicalStream, false, null, encryptedData, algorithm, fragmentingWriter); ((IFragmentCapableXmlDictionaryWriter)fragmentingWriter).WriteFragment(_startBodyFragment.GetBuffer(), 0, (int)_startBodyFragment.Length); ((IFragmentCapableXmlDictionaryWriter)fragmentingWriter).WriteFragment(_endBodyFragment.GetBuffer(), 0, (int)_endBodyFragment.Length); buffer.CloseSection(); buffer.Close(); _startBodyFragment = null; _endBodyFragment = null; XmlDictionaryReader reader = buffer.GetReader(0); reader.MoveToContent(); _bodyPrefix = reader.Prefix; if (reader.HasAttributes) { _bodyAttributes = XmlAttributeHolder.ReadAttributes(reader); } reader.Close(); }
protected override XmlDictionaryReader OnGetReaderAtBodyContents() { if (_state == BodyState.Created) { return(InnerMessage.GetReaderAtBodyContents()); } if (_bodyDecrypted) { EnsureDecryptedBodyStatusDetermined(); } if (_cachedDecryptedBodyContentReader != null) { XmlDictionaryReader result = _cachedDecryptedBodyContentReader; _cachedDecryptedBodyContentReader = null; return(result); } else { XmlDictionaryReader reader = CreateFullBodyReader(); reader.ReadStartElement(); reader.MoveToContent(); return(reader); } }
public void WriteXml(XmlWriter xmlWriter) { if (this.wsdl != null) { using (MemoryStream stream = new MemoryStream()) { this.wsdl.Write(stream); XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas { MaxDepth = 0x20, MaxStringContentLength = 0x2000, MaxArrayLength = 0x4000, MaxBytesPerRead = 0x1000, MaxNameTableCharCount = 0x4000 }; stream.Seek(0L, SeekOrigin.Begin); XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, null, quotas, null); if ((reader.MoveToContent() == XmlNodeType.Element) && (reader.Name == "wsdl:definitions")) { xmlWriter.WriteNode(reader, false); } reader.Close(); } } }
internal static EndpointIdentity ReadIdentity(XmlDictionaryReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } reader.MoveToContent(); if (reader.IsEmptyElement) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnexpectedEmptyElementExpectingClaim, XD.AddressingDictionary.Identity.Value, XD.AddressingDictionary.IdentityExtensionNamespace.Value))); } reader.ReadStartElement(XD.AddressingDictionary.Identity, XD.AddressingDictionary.IdentityExtensionNamespace); if (reader.IsStartElement(XD.AddressingDictionary.Spn, XD.AddressingDictionary.IdentityExtensionNamespace)) { throw ExceptionHelper.PlatformNotSupported("EndpointIdentity.ReadIdentity SpnEndpointIdentity is not supported."); } else if (reader.IsStartElement(XD.AddressingDictionary.Upn, XD.AddressingDictionary.IdentityExtensionNamespace)) { throw ExceptionHelper.PlatformNotSupported("EndpointIdentity.ReadIdentity UpnEndpointIdentity is not supported."); } else if (reader.IsStartElement(XD.AddressingDictionary.Dns, XD.AddressingDictionary.IdentityExtensionNamespace)) { throw ExceptionHelper.PlatformNotSupported("EndpointIdentity.ReadIdentity DnsEndpointIdentity is not supported."); } else if (reader.IsStartElement(XD.XmlSignatureDictionary.KeyInfo, XD.XmlSignatureDictionary.Namespace)) { reader.ReadStartElement(); if (reader.IsStartElement(XD.XmlSignatureDictionary.X509Data, XD.XmlSignatureDictionary.Namespace)) { throw ExceptionHelper.PlatformNotSupported("EndpointIdentity.ReadIdentity X509CertificateEndpointIdentity is not supported."); } else if (reader.IsStartElement(XD.XmlSignatureDictionary.RsaKeyValue, XD.XmlSignatureDictionary.Namespace)) { throw ExceptionHelper.PlatformNotSupported("EndpointIdentity.ReadIdentity RsaEndpointIdentity is not supported."); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnrecognizedIdentityType, reader.Name, reader.NamespaceURI))); } throw ExceptionHelper.PlatformNotSupported("EndpointIdentity.ReadIdentity RsaEndpointIdentity is not supported."); } else if (reader.NodeType == XmlNodeType.Element) { // // Something unknown // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnrecognizedIdentityType, reader.Name, reader.NamespaceURI))); } else { // // EndpointIdentity element is empty or some other invalid xml // throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.InvalidIdentityElement)); } throw ExceptionHelper.PlatformNotSupported("EndpointIdentity.ReadIdentity RsaEndpointIdentity is not supported."); }
// this function has a side-effect on the reader (MoveToContent) static bool Done(XmlDictionaryReader reader) { reader.MoveToContent(); return(reader.NodeType == XmlNodeType.EndElement || reader.EOF); }
public override int Read(byte[] buffer, int offset, int count) { EnsureStreamIsOpen(); if (buffer == null) { throw TraceUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)), _message); } if (offset < 0) { throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), offset, SR.ValueMustBeNonNegative), _message); } if (count < 0) { throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), count, SR.ValueMustBeNonNegative), _message); } if (buffer.Length - offset < count) { throw TraceUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.SFxInvalidStreamOffsetLength, offset + count)), _message); } try { if (_reader == null) { _reader = _message.GetReaderAtBodyContents(); if (_wrapperName != null) { _reader.MoveToContent(); _reader.ReadStartElement(_wrapperName, _wrapperNs); } _reader.MoveToContent(); if (_reader.NodeType == XmlNodeType.EndElement) { return(0); } _reader.ReadStartElement(_elementName, _elementNs); } if (_reader.MoveToContent() != XmlNodeType.Text) { Exhaust(_reader); return(0); } int bytesRead = _reader.ReadContentAsBase64(buffer, offset, count); _position += bytesRead; if (bytesRead == 0) { Exhaust(_reader); } return(bytesRead); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new IOException(SR.SFxStreamIOException, ex)); } }
public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) { throw new ArgumentNullException("reader"); } if (samlSerializer == null) { throw new ArgumentNullException("samlSerializer"); } string decision = reader.GetAttribute("Decision"); switch (decision) { case "Permit": AccessDecision = SamlAccessDecision.Permit; break; case "Deny": AccessDecision = SamlAccessDecision.Deny; break; case "Indeterminate": AccessDecision = SamlAccessDecision.Indeterminate; break; default: throw new SecurityTokenException(String.Format("AccessDecision value is wrong: {0}", decision)); } Resource = reader.GetAttribute("Resource"); reader.ReadStartElement("AuthorizationDecisionStatement", SamlConstants.Namespace); reader.MoveToContent(); SamlSubject = new SamlSubject(); SamlSubject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); SamlActions.Clear(); for (reader.MoveToContent(); reader.LocalName == "Action" && reader.NamespaceURI == SamlConstants.Namespace; reader.MoveToContent()) { SamlAction action = new SamlAction(); action.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); SamlActions.Add(action); } if (reader.LocalName == "Evidence" && reader.NamespaceURI == SamlConstants.Namespace) { Evidence = new SamlEvidence(); Evidence.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); reader.MoveToContent(); } reader.ReadEndElement(); // verify contents if (SamlActions.Count == 0) { throw new SecurityTokenException("SAML AuthorizationDecisionStatement must contain at least one Action."); } if (SamlSubject == null) { throw new SecurityTokenException("SAML Subject must be set to SAML AuthorizationDecisionStatement before being written."); } if (Resource == null || Resource.Length == 0) { throw new SecurityTokenException("non-zero string must be set to Resource on SAML AuthorizationDecisionStatement."); } }
public override void ReadExtensions(XmlDictionaryReader reader) { reader.MoveToContent(); if (reader.IsStartElement(XmlEncryptionConstants.Elements.ReferenceList, XmlEncryptionConstants.Namespace)) { reader.ReadStartElement(); // could have data or key references. these are the only two possible elements sec 3.6 xml enc. // 3.6 The ReferenceList Element specifies there is a choice. Once one is chosen, it is fixed. if (reader.IsStartElement(XmlEncryptionConstants.Elements.DataReference, XmlEncryptionConstants.Namespace)) { while (reader.IsStartElement()) { if (reader.IsStartElement(XmlEncryptionConstants.Elements.DataReference, XmlEncryptionConstants.Namespace)) { string dataRef = reader.GetAttribute(XmlEncryptionConstants.Attributes.Uri); if (!string.IsNullOrEmpty(dataRef)) { _dataReferences.Add(dataRef); } reader.Skip(); } else if (reader.IsStartElement(XmlEncryptionConstants.Elements.KeyReference, XmlEncryptionConstants.Namespace)) { throw DiagnosticUtility.ThrowHelperXml(reader, SR.GetString(SR.ID4189)); } else { string xml = reader.ReadOuterXml(); if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceString(System.Diagnostics.TraceEventType.Warning, SR.GetString(SR.ID8024, reader.Name, reader.NamespaceURI, xml)); } } } } else if (reader.IsStartElement(XmlEncryptionConstants.Elements.KeyReference, XmlEncryptionConstants.Namespace)) { while (reader.IsStartElement()) { if (reader.IsStartElement(XmlEncryptionConstants.Elements.KeyReference, XmlEncryptionConstants.Namespace)) { string keyRef = reader.GetAttribute(XmlEncryptionConstants.Attributes.Uri); if (!string.IsNullOrEmpty(keyRef)) { _keyReferences.Add(keyRef); } reader.Skip(); } else if (reader.IsStartElement(XmlEncryptionConstants.Elements.DataReference, XmlEncryptionConstants.Namespace)) { throw DiagnosticUtility.ThrowHelperXml(reader, SR.GetString(SR.ID4190)); } else { string xml = reader.ReadOuterXml(); if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceString(System.Diagnostics.TraceEventType.Warning, SR.GetString(SR.ID8024, reader.Name, reader.NamespaceURI, xml)); } } } } else { // there must be at least one reference. throw DiagnosticUtility.ThrowHelperXml(reader, SR.GetString(SR.ID4191)); } reader.MoveToContent(); if (reader.IsStartElement(XmlEncryptionConstants.Elements.CarriedKeyName, XmlEncryptionConstants.Namespace)) { reader.ReadStartElement(); _carriedName = reader.ReadString(); reader.ReadEndElement(); } // </ReferenceList> reader.ReadEndElement(); } }
/// <summary> /// Reads the body of an object /// </summary> public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } reader.MoveToContent(); bool isSelfClosed = reader.IsEmptyElement, isNil = reader.GetAttribute("nil") == "true"; reader.ReadStartElement(PROTO_ELEMENT); // explicitly null if (isNil) { if (!isSelfClosed) { reader.ReadEndElement(); } return(null); } if (isSelfClosed) // no real content { if (isList || isEnum) { return(model.Deserialize(Stream.Null, null, type, null)); } ProtoReader protoReader = null; try { protoReader = ProtoReader.Create(Stream.Null, model, null, ProtoReader.TO_EOF); return(model.Deserialize(key, null, protoReader)); } finally { ProtoReader.Recycle(protoReader); } } object result; Helpers.DebugAssert(reader.CanReadBinaryContent, "CanReadBinaryContent"); using (MemoryStream ms = new MemoryStream(reader.ReadContentAsBase64())) { if (isList || isEnum) { result = model.Deserialize(ms, null, type, null); } else { ProtoReader protoReader = null; try { protoReader = ProtoReader.Create(ms, model, null, ProtoReader.TO_EOF); result = model.Deserialize(key, null, protoReader); } finally { ProtoReader.Recycle(protoReader); } } } reader.ReadEndElement(); return(result); }
public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader")); } if (samlSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer")); } SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary; this.resource = reader.GetAttribute(samlDictionary.Resource, null); if (string.IsNullOrEmpty(this.resource)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionStatementMissingResourceAttributeOnRead"))); } string attribute = reader.GetAttribute(samlDictionary.Decision, null); if (string.IsNullOrEmpty(attribute)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionStatementMissingDecisionAttributeOnRead"))); } if (attribute.Equals(SamlAccessDecision.Deny.ToString(), StringComparison.OrdinalIgnoreCase)) { this.accessDecision = SamlAccessDecision.Deny; } else if (attribute.Equals(SamlAccessDecision.Permit.ToString(), StringComparison.OrdinalIgnoreCase)) { this.accessDecision = SamlAccessDecision.Permit; } else { this.accessDecision = SamlAccessDecision.Indeterminate; } reader.MoveToContent(); reader.Read(); if (!reader.IsStartElement(samlDictionary.Subject, samlDictionary.Namespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionStatementMissingSubjectOnRead"))); } SamlSubject subject = new SamlSubject(); subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); base.SamlSubject = subject; while (reader.IsStartElement()) { if (reader.IsStartElement(samlDictionary.Action, samlDictionary.Namespace)) { SamlAction item = new SamlAction(); item.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); this.actions.Add(item); } else { if (!reader.IsStartElement(samlDictionary.Evidence, samlDictionary.Namespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.AuthorizationDecisionStatement }))); } if (this.evidence != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionHasMoreThanOneEvidence"))); } this.evidence = new SamlEvidence(); this.evidence.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver); } } if (this.actions.Count == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionShouldHaveOneActionOnRead"))); } reader.MoveToContent(); reader.ReadEndElement(); }
private void RunValidationTests(SecurityTokenDescriptor tokenDescriptor, SecurityToken securityToken, SecurityKey key, int iterations, bool display = true) { // Create jwts using wif // Create Saml2 tokens // Create Saml tokens DateTime started; string validating = "Validating, signed: '{0}', '{1}' Tokens. Time: '{2}'"; SetReturnSecurityTokenResolver str = new Test.SetReturnSecurityTokenResolver(securityToken, key); SecurityTokenHandlerConfiguration tokenHandlerConfiguration = new SecurityTokenHandlerConfiguration() { IssuerTokenResolver = str, SaveBootstrapContext = true, CertificateValidator = AlwaysSucceedCertificateValidator.New, AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never), IssuerNameRegistry = new SetNameIssuerNameRegistry(Issuers.GotJwt), }; Saml2SecurityTokenHandler samlTokenHandler = new Saml2SecurityTokenHandler(); Saml2SecurityToken token = samlTokenHandler.CreateToken(tokenDescriptor) as Saml2SecurityToken; StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb); samlTokenHandler.WriteToken(writer, token); writer.Flush(); writer.Close(); string tokenXml = sb.ToString(); samlTokenHandler.Configuration = tokenHandlerConfiguration; started = DateTime.UtcNow; for (int i = 0; i < iterations; i++) { StringReader sr = new StringReader(tokenXml); XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr)); reader.MoveToContent(); SecurityToken saml2Token = samlTokenHandler.ReadToken(reader); samlTokenHandler.ValidateToken(saml2Token); } if (display) { Console.WriteLine(string.Format(validating, "Saml2SecurityTokenHandler", iterations, DateTime.UtcNow - started)); } JwtSecurityTokenHandler jwtTokenHandler = new JwtSecurityTokenHandler(); JwtSecurityToken jwt = jwtTokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken; jwtTokenHandler.Configuration = tokenHandlerConfiguration; started = DateTime.UtcNow; for (int i = 0; i < iterations; i++) { jwtTokenHandler.ValidateToken(jwt.RawData); } if (display) { Console.WriteLine(string.Format(validating, "JwtSecurityTokenHandle - ValidateToken( jwt.RawData )", iterations, DateTime.UtcNow - started)); } jwt = jwtTokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken; sb = new StringBuilder(); writer = XmlWriter.Create(sb); jwtTokenHandler.WriteToken(writer, jwt); writer.Flush(); writer.Close(); tokenXml = sb.ToString(); started = DateTime.UtcNow; for (int i = 0; i < iterations; i++) { StringReader sr = new StringReader(tokenXml); XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr)); reader.MoveToContent(); SecurityToken jwtToken = jwtTokenHandler.ReadToken(reader); jwtTokenHandler.ValidateToken(jwtToken); } if (display) { Console.WriteLine(string.Format(validating, "JwtSecurityTokenHandle - ReadToken( reader ), ValidateToken( jwtToken )", iterations, DateTime.UtcNow - started)); } started = DateTime.UtcNow; for (int i = 0; i < iterations; i++) { StringReader sr = new StringReader(tokenXml); XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(sr)); reader.MoveToContent(); JwtSecurityToken jwtToken = jwtTokenHandler.ReadToken(reader) as JwtSecurityToken; jwtTokenHandler.ValidateToken(jwtToken.RawData); } if (display) { Console.WriteLine(string.Format(validating, "JwtSecurityTokenHandle - ReadToken( reader ), ValidateToken( jwtToken.RawData )", iterations, DateTime.UtcNow - started)); } }
protected override void ExecuteMessageProtectionPass(bool hasAtLeastOneSupportingTokenExpectedToBeSigned) { bool flag8; bool flag9; SignatureTargetIdManager idManager = base.StandardsManager.IdManager; MessagePartSpecification specification = base.RequiredEncryptionParts ?? MessagePartSpecification.NoParts; MessagePartSpecification signatureParts = base.RequiredSignatureParts ?? MessagePartSpecification.NoParts; bool checkForTokensAtHeaders = hasAtLeastOneSupportingTokenExpectedToBeSigned; bool doSoapAttributeChecks = !signatureParts.IsBodyIncluded; bool encryptBeforeSignMode = base.EncryptBeforeSignMode; SignedInfo signedInfo = (this.pendingSignature != null) ? this.pendingSignature.Signature.SignedInfo : null; SignatureConfirmations sentSignatureConfirmations = base.GetSentSignatureConfirmations(); if (((sentSignatureConfirmations != null) && (sentSignatureConfirmations.Count > 0)) && sentSignatureConfirmations.IsMarkedForEncryption) { base.VerifySignatureEncryption(); } MessageHeaders headers = base.SecurityVerifiedMessage.Headers; XmlDictionaryReader readerAtFirstHeader = base.SecurityVerifiedMessage.GetReaderAtFirstHeader(); bool atLeastOneHeaderOrBodyEncrypted = false; for (int i = 0; i < headers.Count; i++) { if (readerAtFirstHeader.NodeType != XmlNodeType.Element) { readerAtFirstHeader.MoveToContent(); } if (i == base.HeaderIndex) { readerAtFirstHeader.Skip(); } else { bool flag6; bool flag5 = false; string str = idManager.ExtractId(readerAtFirstHeader); if (str != null) { flag5 = this.TryDeleteReferenceListEntry(str); } if (!flag5 && readerAtFirstHeader.IsStartElement("EncryptedHeader", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd")) { XmlDictionaryReader readerAtHeader = headers.GetReaderAtHeader(i); readerAtHeader.ReadStartElement("EncryptedHeader", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"); if (readerAtHeader.IsStartElement(EncryptedData.ElementName, System.ServiceModel.XD.XmlEncryptionDictionary.Namespace)) { string attribute = readerAtHeader.GetAttribute(System.ServiceModel.XD.XmlEncryptionDictionary.Id, null); if ((attribute != null) && this.TryDeleteReferenceListEntry(attribute)) { flag5 = true; } } } base.ElementManager.VerifyUniquenessAndSetHeaderId(str, i); MessageHeaderInfo info = headers[i]; if (!flag5 && specification.IsHeaderIncluded(info.Name, info.Namespace)) { base.SecurityVerifiedMessage.OnUnencryptedPart(info.Name, info.Namespace); } if ((!flag5 || encryptBeforeSignMode) && (str != null)) { flag6 = this.EnsureDigestValidityIfIdMatches(signedInfo, str, readerAtFirstHeader, doSoapAttributeChecks, signatureParts, info, checkForTokensAtHeaders); } else { flag6 = false; } if (flag5) { XmlDictionaryReader reader = flag6 ? headers.GetReaderAtHeader(i) : readerAtFirstHeader; DecryptedHeader header = this.DecryptHeader(reader, this.pendingDecryptionToken); info = header; str = header.Id; base.ElementManager.VerifyUniquenessAndSetDecryptedHeaderId(str, i); headers.ReplaceAt(i, header); if (!object.ReferenceEquals(reader, readerAtFirstHeader)) { reader.Close(); } if (!encryptBeforeSignMode && (str != null)) { XmlDictionaryReader headerReader = header.GetHeaderReader(); flag6 = this.EnsureDigestValidityIfIdMatches(signedInfo, str, headerReader, doSoapAttributeChecks, signatureParts, info, checkForTokensAtHeaders); headerReader.Close(); } } if (!flag6 && signatureParts.IsHeaderIncluded(info.Name, info.Namespace)) { base.SecurityVerifiedMessage.OnUnsignedPart(info.Name, info.Namespace); } if (flag6 && flag5) { base.VerifySignatureEncryption(); } if (flag5 && !flag6) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(System.ServiceModel.SR.GetString("EncryptedHeaderNotSigned", new object[] { info.Name, info.Namespace }))); } if (!flag6 && !flag5) { readerAtFirstHeader.Skip(); } atLeastOneHeaderOrBodyEncrypted |= flag5; } } readerAtFirstHeader.ReadEndElement(); if (readerAtFirstHeader.NodeType != XmlNodeType.Element) { readerAtFirstHeader.MoveToContent(); } string id = idManager.ExtractId(readerAtFirstHeader); base.ElementManager.VerifyUniquenessAndSetBodyId(id); base.SecurityVerifiedMessage.SetBodyPrefixAndAttributes(readerAtFirstHeader); bool flag7 = specification.IsBodyIncluded || this.HasPendingDecryptionItem(); if ((!flag7 || encryptBeforeSignMode) && (id != null)) { flag8 = this.EnsureDigestValidityIfIdMatches(signedInfo, id, readerAtFirstHeader, false, null, null, false); } else { flag8 = false; } if (flag7) { XmlDictionaryReader reader5 = flag8 ? base.SecurityVerifiedMessage.CreateFullBodyReader() : readerAtFirstHeader; reader5.ReadStartElement(); string str4 = idManager.ExtractId(reader5); base.ElementManager.VerifyUniquenessAndSetBodyContentId(str4); flag9 = (str4 != null) && this.TryDeleteReferenceListEntry(str4); if (flag9) { this.DecryptBody(reader5, this.pendingDecryptionToken); } if (!object.ReferenceEquals(reader5, readerAtFirstHeader)) { reader5.Close(); } if ((!encryptBeforeSignMode && (signedInfo != null)) && signedInfo.HasUnverifiedReference(id)) { reader5 = base.SecurityVerifiedMessage.CreateFullBodyReader(); flag8 = this.EnsureDigestValidityIfIdMatches(signedInfo, id, reader5, false, null, null, false); reader5.Close(); } } else { flag9 = false; } if (flag8 && flag9) { base.VerifySignatureEncryption(); } readerAtFirstHeader.Close(); if (this.pendingSignature != null) { this.pendingSignature.CompleteSignatureVerification(); this.pendingSignature = null; } this.pendingDecryptionToken = null; atLeastOneHeaderOrBodyEncrypted |= flag9; if (!flag8 && signatureParts.IsBodyIncluded) { base.SecurityVerifiedMessage.OnUnsignedPart(System.ServiceModel.XD.MessageDictionary.Body.Value, base.Version.Envelope.Namespace); } if (!flag9 && specification.IsBodyIncluded) { base.SecurityVerifiedMessage.OnUnencryptedPart(System.ServiceModel.XD.MessageDictionary.Body.Value, base.Version.Envelope.Namespace); } base.SecurityVerifiedMessage.OnMessageProtectionPassComplete(atLeastOneHeaderOrBodyEncrypted); }
public static object Deserialize(XmlDictionaryReader reader, Type targetType) { object returnValue = null; if (reader.IsStartElement()) { switch (reader.LocalName) { case XmlRpcProtocol.Nil: returnValue = null; break; case XmlRpcProtocol.Bool: returnValue = Convert.ChangeType((reader.ReadElementContentAsInt() == 1), targetType); break; case XmlRpcProtocol.ByteArray: if (targetType == typeof(Stream)) { returnValue = new MemoryStream(reader.ReadElementContentAsBase64()); } else { returnValue = Convert.ChangeType(reader.ReadElementContentAsBase64(), targetType); } break; case XmlRpcProtocol.DateTime: returnValue = Convert.ChangeType(reader.ReadElementContentAsDateTime(), targetType); break; case XmlRpcProtocol.Double: returnValue = Convert.ChangeType(reader.ReadElementContentAsDouble(), targetType); break; case XmlRpcProtocol.Int32: case XmlRpcProtocol.Integer: returnValue = Convert.ChangeType(reader.ReadElementContentAsString(), targetType); break; case XmlRpcProtocol.String: if (targetType == typeof(Uri)) { returnValue = new Uri(reader.ReadElementContentAsString()); } else { returnValue = Convert.ChangeType(reader.ReadElementContentAsString(), targetType); } break; case XmlRpcProtocol.Struct: returnValue = DeserializeStruct(reader, targetType); break; case XmlRpcProtocol.Array: if (targetType.IsArray || targetType is IEnumerable || targetType is IList || targetType is ICollection) { reader.ReadStartElement(XmlRpcProtocol.Array); ArrayList arrayData = new ArrayList(); reader.ReadStartElement(XmlRpcProtocol.Data); reader.MoveToContent(); while (reader.IsStartElement(XmlRpcProtocol.Value)) { reader.ReadStartElement(); arrayData.Add(Deserialize(reader, targetType.GetElementType())); reader.ReadEndElement(); reader.MoveToContent(); } if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == XmlRpcProtocol.Data) { reader.ReadEndElement(); } reader.ReadEndElement(); if (targetType is IEnumerable || targetType is IList || targetType is ICollection) { returnValue = arrayData; } else { returnValue = arrayData.ToArray(targetType.GetElementType()); } } else { throw new InvalidOperationException(); } break; } } return(returnValue); }
protected void ReadSignature(XmlDictionaryReader reader, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver, SamlSerializer samlSerializer) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } if (samlSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlSerializer"); } if (this.signature != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SAMLSignatureAlreadyRead))); } // If the reader cannot canonicalize then buffer the signature element to a canonicalizing reader. XmlDictionaryReader effectiveReader = reader; if (!effectiveReader.CanCanonicalize) { MemoryStream stream = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream, samlSerializer.DictionaryManager.ParentDictionary); writer.WriteNode(effectiveReader, false); writer.Flush(); stream.Position = 0; effectiveReader = XmlDictionaryReader.CreateBinaryReader(stream.GetBuffer(), 0, (int)stream.Length, samlSerializer.DictionaryManager.ParentDictionary, reader.Quotas); effectiveReader.MoveToContent(); writer.Close(); } SignedXml signedXml = new SignedXml(new StandardSignedInfo(samlSerializer.DictionaryManager), samlSerializer.DictionaryManager, keyInfoSerializer); signedXml.TransformFactory = ExtendedTransformFactory.Instance; signedXml.ReadFrom(effectiveReader); SecurityKeyIdentifier securityKeyIdentifier = signedXml.Signature.KeyIdentifier; SecurityKeyIdentifierClause securityKeyIdentifierClause = null; if (securityKeyIdentifier.Count < 2 || LocalAppContextSwitches.ProcessMultipleSecurityKeyIdentifierClauses) { this.verificationKey = SamlSerializer.ResolveSecurityKey(securityKeyIdentifier, outOfBandTokenResolver); } else { this.verificationKey = ResolveSecurityKey(securityKeyIdentifier, outOfBandTokenResolver, out securityKeyIdentifierClause); } if (this.verificationKey == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToResolveSignatureKey, this.issuer))); } this.signature = signedXml; if (securityKeyIdentifier.Count < 2 || LocalAppContextSwitches.ProcessMultipleSecurityKeyIdentifierClauses) { this.signingToken = SamlSerializer.ResolveSecurityToken(securityKeyIdentifier, outOfBandTokenResolver); } else { this.signingToken = SamlSerializer.ResolveSecurityToken(new SecurityKeyIdentifier(securityKeyIdentifierClause), outOfBandTokenResolver); } if (this.signingToken == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SamlSigningTokenNotFound))); } if (!ReferenceEquals(reader, effectiveReader)) { effectiveReader.Close(); } }