コード例 #1
0
        public static EndpointAddress ReadEndpointAddress(DiscoveryVersion discoveryVersion, XmlReader reader)
        {
            Fx.Assert(discoveryVersion != null, "The discoveryVersion must be non null");
            Fx.Assert(reader != null, "The reader must be non null");

            if (discoveryVersion == DiscoveryVersion.WSDiscoveryApril2005 || discoveryVersion == DiscoveryVersion.WSDiscoveryCD1)
            {
                EndpointAddressAugust2004 endpoint = discoveryVersion.Implementation.EprSerializer.ReadObject(reader) as EndpointAddressAugust2004;
                if (endpoint == null)
                {
                    throw FxTrace.Exception.AsError(new XmlException(SR2.DiscoveryXmlEndpointNull));
                }
                return(endpoint.ToEndpointAddress());
            }
            else if (discoveryVersion == DiscoveryVersion.WSDiscovery11)
            {
                EndpointAddress10 endpoint = discoveryVersion.Implementation.EprSerializer.ReadObject(reader) as EndpointAddress10;
                if (endpoint == null)
                {
                    throw FxTrace.Exception.AsError(new XmlException(SR2.DiscoveryXmlEndpointNull));
                }
                return(endpoint.ToEndpointAddress());
            }
            else
            {
                Fx.Assert("The discoveryVersion parameter cannot be null.");
                return(null);
            }
        }
コード例 #2
0
        public void Serialize()
        {
            var serializer = new XmlSerializer(typeof(SubscribeRequestMessageBody));

            var message = new SubscribeRequestMessageBody();
            // Supply mock Delivery
            var delivery = new Mock <Delivery>(MockBehavior.Strict);

            delivery.As <IXmlSerializable>().Setup(item => item.WriteXml(It.IsAny <XmlWriter>()));
            message.Delivery = delivery.Object;
            message.EndTo    = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress("http://tempuri.org/endTo"));
            // Supply mock Expires
            var expires = new Mock <Expires>(MockBehavior.Strict);

            expires.As <IXmlSerializable>().Setup(item => item.WriteXml(It.IsAny <XmlWriter>()));
            message.Expires = expires.Object;
            message.Filter  = new XPathMessageFilter(@"/foo");

            XElement xml;

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(stream, message);
                stream.Position = 0;
                xml             = XElement.Load(stream);
            }
            var areEqual = XNode.DeepEquals(XElement.Parse("<wse:Subscribe xmlns:wse='http://schemas.xmlsoap.org/ws/2004/08/eventing'><wse:EndTo><Address xmlns='http://schemas.xmlsoap.org/ws/2004/08/addressing'>http://tempuri.org/endTo</Address></wse:EndTo><wse:Filter>/foo</wse:Filter></wse:Subscribe>"), xml.FirstNode);

            Assert.IsTrue(areEqual);
        }
コード例 #3
0
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (reader.IsStartElement("Delivery", Constants.WsEventing.Namespace) == false)
            {
                throw new XmlException("Invalid Element, it must be 'Delivery'");
            }

            String modeAsString = reader.GetAttribute("Mode", Constants.WsEventing.Namespace);

            this.DeliveryMode = String.IsNullOrEmpty(modeAsString) ? DeliveryMode = new Uri(Constants.WsEventing.DeliverModes.Push) : new Uri(modeAsString);

            reader.ReadToDescendant("NotifyTo", Constants.WsEventing.Namespace);
            this.NotifyTo = EndpointAddressAugust2004.FromEndpointAddress(EndpointAddress.ReadFrom(AddressingVersion.WSAddressingAugust2004, reader));
            if (this.NotifyTo == null)
            {
                throw new XmlException("Missing element 'NotifyTo'");
            }

            while (reader.NodeType != XmlNodeType.EndElement)
            {
                var additionalElement = XElement.Parse(reader.ReadOuterXml());
                this.additionalElements.Add(additionalElement);
            }

            reader.ReadEndElement();
        }
コード例 #4
0
        /// <summary>
        /// Replaces the <see cref="Identifier"/> value, if any, with the supplied <paramref name="id"/>, if any.
        /// </summary>
        /// <param name="id">The new identifier value to use, or clear if null.</param>
        public void CreateIdentifierHeader(Guid?id)
        {
            var builder = new EndpointAddressBuilder(this.EndpointAddress.ToEndpointAddress());
            var header  = builder.Headers.FirstOrDefault(a => a.Name == "Identifier" && a.Namespace == Constants.WsEventing.Namespace);

            if (id == null)
            {
                if (header == null)
                {
                    return;
                }

                var wasRemoved = builder.Headers.Remove(header);
                Debug.Assert(wasRemoved);
            }
            else
            {
                if (header != null)
                {
                    var wasRemoved = builder.Headers.Remove(header);
                    Debug.Assert(wasRemoved);
                }
                var uuid = new UniqueId(id.Value);
                header = AddressHeader.CreateAddressHeader("Identifier", Constants.WsEventing.Namespace, uuid.ToString());

                builder.Headers.Add(header);
            }

            this.epa = EndpointAddressAugust2004.FromEndpointAddress(builder.ToEndpointAddress());
        }
コード例 #5
0
        private static EndpointAddress ProcessAppliesToElement(XmlReader xr)
        {
            if (xr == null)
            {
                throw new ArgumentNullException("xr");
            }
            if (xr.IsEmptyElement)
            {
                throw new ArgumentException("wsp:AppliesTo element was empty. Unable to create EndpointAddress object");
            }
            int             depth  = xr.Depth;
            EndpointAddress result = null;

            while (xr.Read())
            {
                if ("EndpointReference" == xr.LocalName && "http://www.w3.org/2005/08/addressing" == xr.NamespaceURI && !xr.IsEmptyElement && XmlNodeType.Element == xr.NodeType)
                {
                    DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(EndpointAddress10));
                    EndpointAddress10      endpointAddress        = (EndpointAddress10)dataContractSerializer.ReadObject(xr, false);
                    result = endpointAddress.ToEndpointAddress();
                }
                else if ("EndpointReference" == xr.LocalName && "http://schemas.xmlsoap.org/ws/2004/08/addressing" == xr.NamespaceURI && !xr.IsEmptyElement && XmlNodeType.Element == xr.NodeType)
                {
                    DataContractSerializer    dataContractSerializer2 = new DataContractSerializer(typeof(EndpointAddressAugust2004));
                    EndpointAddressAugust2004 endpointAddressAugust   = (EndpointAddressAugust2004)dataContractSerializer2.ReadObject(xr, false);
                    result = endpointAddressAugust.ToEndpointAddress();
                }
                if ("AppliesTo" == xr.LocalName && "http://schemas.xmlsoap.org/ws/2004/09/policy" == xr.NamespaceURI && xr.Depth == depth && XmlNodeType.EndElement == xr.NodeType)
                {
                    break;
                }
            }
            return(result);
        }
コード例 #6
0
        /// <summary>
        /// Converts and EndpointReferenceType to an EndpointAddressAugust2004
        /// </summary>
        /// <returns>Returns an EndpointAddressAugust2004 object</returns>
        public EndpointAddressAugust2004 ToEndpointReference()
        {
            var builder = new StringBuilder();

            using (var writer = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(builder, new XmlWriterSettings()
            {
                Indent = false, OmitXmlDeclaration = true
            })))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(EndpointReferenceType));

                serializer.Serialize(writer, this);
            }

            using (var reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(new StringReader(builder.ToString()), new XmlReaderSettings()
            {
                IgnoreWhitespace = true
            })))
            {
                builder.Clear();

                var address = EndpointAddress.ReadFrom(AddressingVersion.WSAddressingAugust2004, reader);

                return(EndpointAddressAugust2004.FromEndpointAddress(address));
            }
        }
 public VolatileEnlistmentInDoubtRecordSchema10(Guid enlistmentId, EndpointAddress replyTo) : base(enlistmentId)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/VolatileEnlistmentInDoubtTraceRecord";
     if (replyTo != null)
     {
         this.replyTo = EndpointAddressAugust2004.FromEndpointAddress(replyTo);
     }
 }
コード例 #8
0
 public RegistrationCoordinatorResponseInvalidMetadataSchema10(CoordinationContext context, ControlProtocol protocol, EndpointAddress coordinatorService) : base(context, protocol)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RegistrationCoordinatorResponseInvalidMetadataTraceRecord";
     if (coordinatorService != null)
     {
         this.coordinatorService = EndpointAddressAugust2004.FromEndpointAddress(coordinatorService);
     }
 }
コード例 #9
0
 public RecoverCoordinatorRecordSchema10(string transactionId, EndpointAddress coordinatorService) : base(transactionId)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RecoverCoordinatorTraceRecord";
     if (coordinatorService != null)
     {
         this.coordinatorService = EndpointAddressAugust2004.FromEndpointAddress(coordinatorService);
     }
 }
コード例 #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SubscriptionManager"/> class from the supplied <paramref name="address"/> and <paramref name="id"/>.
        /// </summary>
        /// <remarks>
        /// This overload is used in similar fashion to <see cref="SubscriptionManager(Uri, WsEventing.Identifier)">this constructor</see> with the
        /// variation of supplying a full set of WSA reference parameters in the created EPA. This can be used to perform the direct creation or
        /// manipulation of the EPA (including the presence of an <see cref="WsEventing.Identifier"/> element).
        /// </remarks>
        /// <param name="address">The endpoint address of the subscription manager used by the event sink to manage subscriptions for this event source.</param>
        /// <param name="headers">A collection of <see cref="AddressHeader">headers</see> that re contained as part of the WSA reference parameters in the created EPA.</param>
        public SubscriptionManager(Uri address, IEnumerable <AddressHeader> headers)
        {
            Contract.Requires(address != null, "address");
            Contract.Requires(headers != null, "headers");
            Contract.Requires(Contract.ForAll(headers, item => item != null));

            this.epa = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress(address, headers.ToArray()));
        }
 public RegisterFailureRecordSchema10(string transactionId, ControlProtocol protocol, EndpointAddress protocolService, string reason) : base(transactionId, protocol, reason)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RegisterFailureTraceRecord";
     if (protocolService != null)
     {
         this.protocolService = EndpointAddressAugust2004.FromEndpointAddress(protocolService);
     }
 }
 public RegisterParticipantRecordSchema10(string transactionId, Guid enlistmentId, ControlProtocol protocol, EndpointAddress participantService) : base(transactionId, enlistmentId, protocol)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RegisterParticipantTraceRecord";
     if (participantService != null)
     {
         this.participantService = EndpointAddressAugust2004.FromEndpointAddress(participantService);
     }
 }
コード例 #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Delivery"/> class with the suppleid <paramref name="mode"/> and <paramref name="notifyTo"/> <see cref="Uri"/> parameter values.
        /// </summary>
        /// <param name="mode">A <see cref="Uri"/> containing the <see cref="DeliveryMode"/> value.</param>
        /// <param name="notifyTo">An <see cref="EndpointAddress"/> containing the location to notify an event message to.</param>
        public Delivery(Uri mode, EndpointAddress notifyTo)
        {
            Contract.Requires <ArgumentNullException>(mode != null, "mode");
            Contract.Requires <ArgumentNullException>(notifyTo != null, "notifyTo");

            this.mode               = mode;
            this.notifyTo           = EndpointAddressAugust2004.FromEndpointAddress(notifyTo);
            this.additionalElements = new Collection <XElement>();
        }
コード例 #14
0
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            this.epa = EndpointAddressAugust2004.FromEndpointAddress(System.ServiceModel.EndpointAddress.ReadFrom(AddressingVersion.WSAddressingAugust2004, reader, "SubscriptionManager", Constants.WsEventing.Namespace));
        }
コード例 #15
0
        public static XmlQualifiedName EnsureProbeMatchSchema(DiscoveryVersion discoveryVersion, XmlSchemaSet schemaSet)
        {
            Fx.Assert(schemaSet != null, "The schemaSet must be non null.");
            Fx.Assert(discoveryVersion != null, "The discoveryVersion must be non null.");

            // ensure that EPR is added to the schema.
            if (discoveryVersion == DiscoveryVersion.WSDiscoveryApril2005 || discoveryVersion == DiscoveryVersion.WSDiscoveryCD1)
            {
                EndpointAddressAugust2004.GetSchema(schemaSet);
            }
            else if (discoveryVersion == DiscoveryVersion.WSDiscovery11)
            {
                EndpointAddress10.GetSchema(schemaSet);
            }
            else
            {
                Fx.Assert("The discoveryVersion is not supported.");
            }

            // do not add/find Probe related schema items
            SchemaTypes    typesFound    = SchemaTypes.ProbeType | SchemaTypes.ResolveType;
            SchemaElements elementsFound = SchemaElements.None;

            XmlSchema   discoverySchema  = null;
            ICollection discoverySchemas = schemaSet.Schemas(discoveryVersion.Namespace);

            if ((discoverySchemas == null) || (discoverySchemas.Count == 0))
            {
                discoverySchema = CreateSchema(discoveryVersion);
                AddImport(discoverySchema, discoveryVersion.Implementation.WsaNamespace);
                schemaSet.Add(discoverySchema);
            }
            else
            {
                foreach (XmlSchema schema in discoverySchemas)
                {
                    discoverySchema = schema;
                    if (schema.SchemaTypes.Contains(discoveryVersion.Implementation.QualifiedNames.ProbeMatchType))
                    {
                        typesFound |= SchemaTypes.ProbeMatchType;
                        break;
                    }

                    LocateSchemaTypes(discoveryVersion, schema, ref typesFound);
                    LocateSchemaElements(discoveryVersion, schema, ref elementsFound);
                }
            }

            if ((typesFound & SchemaTypes.ProbeMatchType) != SchemaTypes.ProbeMatchType)
            {
                AddSchemaTypes(discoveryVersion, typesFound, discoverySchema);
                AddElements(discoveryVersion, elementsFound, discoverySchema);
                schemaSet.Reprocess(discoverySchema);
            }

            return(discoveryVersion.Implementation.QualifiedNames.ProbeMatchType);
        }
コード例 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SubscribeRequestMessageBody"/> class with the supplied <paramref name="delivery"/> and optional <see cref="EndpointAddress"/> to send a notice if a subscription is terminated.
        /// </summary>
        /// <param name="delivery">The <see cref="Delivery"/> value.</param>
        /// <param name="endTo">An optional <see cref="EndpointAddress"/> containing the EPR that should be used when to send a notice if a subscription is terminated.</param>
        public SubscribeRequestMessageBody(Delivery delivery, EndpointAddress endTo = null)
        {
            Contract.Requires <ArgumentNullException>(delivery != null, "delivery");

            this.delivery = delivery;
            if (endTo == null)
            {
                return;
            }
            this.endTo = EndpointAddressAugust2004.FromEndpointAddress(endTo);
        }
コード例 #17
0
        public void ReadFromAugust2004Error2()
        {
            //Missing <Address> element
            string xml = @"<a:ReplyTo xmlns:a='http://schemas.xmlsoap.org/ws/2004/08/addressing'>http://www.w3.org/2005/08/addressing/anonymous</a:ReplyTo>";

            XmlReader           src    = XmlReader.Create(new StringReader(xml));
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateDictionaryReader(src);

            EndpointAddressAugust2004 e2k4 = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress("http://test"));

            ((IXmlSerializable)e2k4).ReadXml(reader);
        }
コード例 #18
0
        public void ReadFromAugust2004Error()
        {
            //Reading address from EndpointAddress10 namespace with EndpointAddressAugust2004
            string xml = @"<a:ReplyTo xmlns:a='http://www.w3.org/2005/08/addressing'><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>";

            XmlReader           src    = XmlReader.Create(new StringReader(xml));
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateDictionaryReader(src);

            EndpointAddressAugust2004 e2k4 = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress("http://test"));

            ((IXmlSerializable)e2k4).ReadXml(reader);
        }
コード例 #19
0
        /// <summary>
        /// Adds an <see cref="XmlSchema"/> instance for this type to the supplied <see cref="XmlSchemaSet"/>.
        /// </summary>
        /// <param name="xs">The <see cref="XmlSchemaSet"/> to add an <see cref="XmlSchema"/> to.</param>
        /// <returns>An <see cref="XmlQualifiedName"/> for the current object.</returns>
        public static XmlQualifiedName AcquireSchema(XmlSchemaSet xs)
        {
            if (xs == null)
            {
                throw new ArgumentNullException("xs");
            }

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("CommonContracts.WsEventing.DeliveryType.xsd"))
            {
                Debug.Assert(stream != null, "Resource Stream 'CommonContracts.WsEventing.DeliveryType.xsd' was not able to be opened");

                var schema = XmlSchema.Read(stream, null);
                xs.Add(schema);
            }
            EndpointAddressAugust2004.GetSchema(xs);
            return(new XmlQualifiedName("DeliveryType", Constants.WsEventing.Namespace));
        }
コード例 #20
0
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (reader.IsStartElement("Subscribe", Constants.WsEventing.Namespace) == false)
            {
                throw new XmlException("Invalid Element, it must be 'Subscribe'");
            }

            reader.ReadStartElement("Subscribe", Constants.WsEventing.Namespace);
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                if (reader.IsStartElement("EndTo", Constants.WsEventing.Namespace))
                {
                    this.EndTo = EndpointAddressAugust2004.FromEndpointAddress(EndpointAddress.ReadFrom(AddressingVersion.WSAddressingAugust2004, reader));
                }
                else if (reader.IsStartElement("Delivery", Constants.WsEventing.Namespace))
                {
                    this.Delivery = new Delivery(reader);
                }
                else if (reader.IsStartElement("Expires", Constants.WsEventing.Namespace))
                {
                    this.Expires = new Expires(reader);
                }
                else if (reader.IsStartElement("Filter", Constants.WsEventing.Namespace))
                {
                    String dialect = reader.GetAttribute("Dialect");
                    if (String.IsNullOrEmpty(dialect) || dialect == Constants.WsEventing.Dialects.XPath)
                    {
                        this.Filter        = new XPathMessageFilter(reader);
                        this.filterDialect = Constants.WsEventing.Dialects.XPath;
                    }
                    else
                    {
                        reader.Skip();
                        this.filterDialect = dialect;
                    }
                }
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }
コード例 #21
0
        public void ReadFromAugust2004()
        {
            string xml = @"<a:ReplyTo xmlns:a='http://schemas.xmlsoap.org/ws/2004/08/addressing'><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>";

            XmlReader           src    = XmlReader.Create(new StringReader(xml));
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateDictionaryReader(src);

            EndpointAddressAugust2004 e2k4 = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress("http://test"));

            ((IXmlSerializable)e2k4).ReadXml(reader);
            Console.WriteLine(e2k4.ToEndpointAddress().Uri.AbsoluteUri);

            EndpointAddress a = e2k4.ToEndpointAddress();

            Assert.AreEqual("http://www.w3.org/2005/08/addressing/anonymous", a.Uri.AbsoluteUri, "#1");
            Assert.IsFalse(a.IsAnonymous, "#2");
        }
コード例 #22
0
        public static void WriteEndPointAddress(DiscoveryVersion discoveryVersion, EndpointAddress endpointAddress, XmlWriter writer)
        {
            Fx.Assert(discoveryVersion != null, "The discoveryVersion must be non null");
            Fx.Assert(writer != null, "The writer must be non null");

            if (discoveryVersion == DiscoveryVersion.WSDiscoveryApril2005 || discoveryVersion == DiscoveryVersion.WSDiscoveryCD1)
            {
                EndpointAddressAugust2004 endpoint = EndpointAddressAugust2004.FromEndpointAddress(endpointAddress);
                discoveryVersion.Implementation.EprSerializer.WriteObject(writer, endpoint);
            }
            else if (discoveryVersion == DiscoveryVersion.WSDiscovery11)
            {
                EndpointAddress10 endpoint = EndpointAddress10.FromEndpointAddress(endpointAddress);
                discoveryVersion.Implementation.EprSerializer.WriteObject(writer, endpoint);
            }
            else
            {
                Fx.Assert("The discoveryVersion parameter cannot be null.");
            }
        }
コード例 #23
0
        void AddEndpointAddressHeader(string name, string ns, EndpointAddress address)
        {
            if (address == null)
            {
                return;
            }
            if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressing10))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddress10.FromEndpointAddress(address)));
            }
#if !MOBILE
            else if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressingAugust2004))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddressAugust2004.FromEndpointAddress(address)));
            }
#endif
            else
            {
                throw new InvalidOperationException("WS-Addressing header is not allowed for AddressingVersion.None");
            }
        }
コード例 #24
0
ファイル: source.cs プロジェクト: ruo2012/samples-1
        public static void Main()
        {
            // <Snippet1>
            // Create an EndpointAddress with a specified address.
            EndpointAddress epa1 = new EndpointAddress("http://localhost/ServiceModelSamples");

            Console.WriteLine("The URI of the EndpointAddress is {0}:", epa1.Uri);
            Console.WriteLine();

            //Initialize an EndpointAddressAugust2004 from the endpointAddress.
            EndpointAddressAugust2004 epaA4 = EndpointAddressAugust2004.FromEndpointAddress(epa1);

            //Serialize and then deserializde the EndpointAugust2004 type.

            //Convert the EndpointAugust2004 back into an EndpointAddress.
            EndpointAddress epa2 = epaA4.ToEndpointAddress();

            Console.WriteLine("The URI of the EndpointAddress is still {0}:", epa2.Uri);
            Console.WriteLine();
            // </Snippet1>
        }
コード例 #25
0
ファイル: MessageHeaders.cs プロジェクト: raj581/Marvin
        void AddEndpointAddressHeader(string name, string ns, EndpointAddress address)
        {
            RemoveAll("FaultTo", Constants.WsaNamespace);
            if (address == null)
            {
                return;
            }
            if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressing10))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddress10.FromEndpointAddress(address)));
            }
#if !NET_2_1
            else if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressingAugust2004))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddressAugust2004.FromEndpointAddress(address)));
            }
#endif
            else
            {
                throw new InvalidOperationException("WS-Addressing header is not allowed for AddressingVersion.None");
            }
        }
コード例 #26
0
        /// <summary>
        /// Converts and EndpointAddressAugust2004 to an EndpointReferenceType.
        /// </summary>
        /// <returns>Returns an EndpointReferenceType object</returns>
        public static EndpointReferenceType FromEndpointReference(EndpointAddressAugust2004 epr)
        {
            var builder = new StringBuilder();

            using (var writer = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(builder, new XmlWriterSettings()
            {
                Indent = false, OmitXmlDeclaration = true
            })))
            {
                epr.ToEndpointAddress().WriteTo(AddressingVersion.WSAddressingAugust2004, writer);
            }

            using (var reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(new StringReader(builder.ToString()), new XmlReaderSettings()
            {
                IgnoreWhitespace = true
            })))
            {
                builder.Clear();

                var serializer = new XmlSerializer(typeof(EndpointReferenceType));

                return((EndpointReferenceType)serializer.Deserialize(reader));
            }
        }
コード例 #27
0
        /// <summary>
        /// Reads a wsp:AppliesTo element
        /// </summary>
        /// <param name="xr">An XmlReader positioned on the start tag of wsp:AppliesTo</param>
        /// <returns>An EndpointAddress</returns>
        private static EndpointAddress ProcessAppliesToElement(XmlReader xr)
        {
            // If provided XmlReader is null, throw an exception
            if (xr == null)
            {
                throw new ArgumentNullException("xr");
            }

            // If the wsp:AppliesTo element is empty, then throw an exception.
            if (xr.IsEmptyElement)
            {
                throw new ArgumentException("wsp:AppliesTo element was empty. Unable to create EndpointAddress object");
            }

            // Store the initial depth so we can exit this function when we reach the corresponding end-tag
            int initialDepth = xr.Depth;

            // Set our return value to null
            EndpointAddress ea = null;

            // Enter a read loop...
            while (xr.Read())
            {
                // Look for a WS-Addressing 1.0 Endpoint Reference...
                if (Constants.Addressing.Elements.EndpointReference == xr.LocalName &&
                    Constants.Addressing.NamespaceUri == xr.NamespaceURI &&
                    !xr.IsEmptyElement &&
                    XmlNodeType.Element == xr.NodeType)
                {
                    // Create a DataContractSerializer for an EndpointAddress10
                    DataContractSerializer dcs = new DataContractSerializer(typeof(EndpointAddress10));
                    // Read the EndpointAddress10 from the DataContractSerializer
                    EndpointAddress10 ea10 = (EndpointAddress10)dcs.ReadObject(xr, false);
                    // Convert the EndpointAddress10 into an EndpointAddress
                    ea = ea10.ToEndpointAddress();
                }
                // Look for a WS-Addressing 2004/08 Endpoint Reference...
                else if (Constants.Addressing.Elements.EndpointReference == xr.LocalName &&
                         Constants.Addressing.NamespaceUriAugust2004 == xr.NamespaceURI &&
                         !xr.IsEmptyElement &&
                         XmlNodeType.Element == xr.NodeType)
                {
                    // Create a DataContractSerializer for an EndpointAddressAugust2004
                    DataContractSerializer dcs = new DataContractSerializer(typeof(EndpointAddressAugust2004));
                    // Read the EndpointAddressAugust2004 from the DataContractSerializer
                    EndpointAddressAugust2004 eaAugust2004 = (EndpointAddressAugust2004)dcs.ReadObject(xr, false);
                    // Convert the EndpointAddressAugust2004 into an EndpointAddress
                    ea = eaAugust2004.ToEndpointAddress();
                }

                // Look for the end-tag that corresponds to the start-tag the reader was positioned
                // on when the method was called. When we find it, break out of the read loop.
                if (Constants.Policy.Elements.AppliesTo == xr.LocalName &&
                    Constants.Policy.NamespaceUri == xr.NamespaceURI &&
                    xr.Depth == initialDepth &&
                    XmlNodeType.EndElement == xr.NodeType)
                {
                    break;
                }
            }

            // Return the EndpointAddress
            return(ea);
        }
コード例 #28
0
        private async ValueTask <BodyWriter> ProcessNegotiationAsync(SspiNegotiationTokenAuthenticatorState negotiationState, Message incomingMessage, BinaryNegotiation incomingNego)
        {
            ISspiNegotiation sspiNegotiation = negotiationState.SspiNegotiation;

            byte[] outgoingBlob = sspiNegotiation.GetOutgoingBlob(incomingNego.GetNegotiationData(),
                                                                  SecurityUtils.GetChannelBindingFromMessage(incomingMessage),
                                                                  ExtendedProtectionPolicy);

            if (sspiNegotiation.IsValidContext == false)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.InvalidSspiNegotiation)), incomingMessage);
            }
            // if there is no blob to send back the nego must be complete from the server side
            if (outgoingBlob == null && sspiNegotiation.IsCompleted == false)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.NoBinaryNegoToSend)), incomingMessage);
            }
            BinaryNegotiation outgoingBinaryNegotiation;

            if (outgoingBlob != null)
            {
                outgoingBinaryNegotiation = GetOutgoingBinaryNegotiation(sspiNegotiation, outgoingBlob);
            }
            else
            {
                outgoingBinaryNegotiation = null;
            }
            BodyWriter replyBody;

            if (sspiNegotiation.IsCompleted)
            {
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = await ValidateSspiNegotiationAsync(sspiNegotiation);

                SecurityContextSecurityToken serviceToken;
                WrappedKeySecurityToken      proofToken;
                int issuedKeySize;
                IssueServiceToken(negotiationState, authorizationPolicies, out serviceToken, out proofToken, out issuedKeySize);
                negotiationState.SetServiceToken(serviceToken);

                SecurityKeyIdentifierClause externalTokenReference = IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
                SecurityKeyIdentifierClause internalTokenReference = IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);

                RequestSecurityTokenResponse dummyRstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    Context   = negotiationState.Context,
                    KeySize   = issuedKeySize,
                    TokenType = SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    dummyRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                dummyRstr.RequestedUnattachedReference = externalTokenReference;
                dummyRstr.RequestedAttachedReference   = internalTokenReference;
                dummyRstr.SetLifetime(serviceToken.ValidFrom, serviceToken.ValidTo);
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        dummyRstr.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(
                                                                       negotiationState.AppliesTo),
                                                                   negotiationState.AppliesToSerializer);
                    }
                    else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        dummyRstr.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(
                                                                               negotiationState.AppliesTo),
                                                                           negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
                    }
                }
                dummyRstr.MakeReadOnly();
                AddToDigest(negotiationState, dummyRstr, false);
                RequestSecurityTokenResponse negotiationRstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    RequestedSecurityToken = serviceToken,

                    RequestedProofToken = proofToken,
                    Context             = negotiationState.Context,
                    KeySize             = issuedKeySize,
                    TokenType           = SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    negotiationRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                negotiationRstr.RequestedAttachedReference   = internalTokenReference;
                negotiationRstr.RequestedUnattachedReference = externalTokenReference;
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        negotiationRstr.SetAppliesTo <EndpointAddress10>(
                            EndpointAddress10.FromEndpointAddress(negotiationState.AppliesTo),
                            negotiationState.AppliesToSerializer);
                    }
                    else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        negotiationRstr.SetAppliesTo <EndpointAddressAugust2004>(
                            EndpointAddressAugust2004.FromEndpointAddress(negotiationState.AppliesTo),
                            negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
                    }
                }
                negotiationRstr.MakeReadOnly();

                byte[] authenticator = ComputeAuthenticator(negotiationState, serviceToken.GetKeyBytes());
                RequestSecurityTokenResponse authenticatorRstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    Context = negotiationState.Context
                };
                authenticatorRstr.SetAuthenticator(authenticator);
                authenticatorRstr.MakeReadOnly();

                List <RequestSecurityTokenResponse> rstrList = new List <RequestSecurityTokenResponse>(2)
                {
                    negotiationRstr,
                    authenticatorRstr
                };
                replyBody = new RequestSecurityTokenResponseCollection(rstrList, StandardsManager);
            }
            else
            {
                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    Context = negotiationState.Context
                };
                rstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                rstr.MakeReadOnly();
                AddToDigest(negotiationState, rstr, false);
                replyBody = rstr;
            }

            return(replyBody);
        }
コード例 #29
0
            protected override BodyWriter GetFirstOutgoingMessageBody(FederatedTokenProviderState negotiationState, out MessageProperties messageProperties)
            {
                messageProperties = null;
                RequestSecurityToken rst = new RequestSecurityToken(this.StandardsManager);

                if (this.addTargetServiceAppliesTo)
                {
                    if (this.MessageVersion.Addressing == AddressingVersion.WSAddressing10)
                    {
                        rst.SetAppliesTo <EndpointAddress10>(
                            EndpointAddress10.FromEndpointAddress(negotiationState.TargetAddress),
                            DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph));
                    }
                    else if (this.MessageVersion.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        rst.SetAppliesTo <EndpointAddressAugust2004>(
                            EndpointAddressAugust2004.FromEndpointAddress(negotiationState.TargetAddress),
                            DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph));
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, this.MessageVersion.Addressing)));
                    }
                }
                rst.Context = negotiationState.Context;
                if (!this.isKeySizePresentInRstProperties)
                {
                    rst.KeySize = this.keySize;
                }
                Collection <XmlElement> newRequestProperties = new Collection <XmlElement>();

                if (this.requestProperties != null)
                {
                    for (int i = 0; i < this.requestProperties.Count; ++i)
                    {
                        newRequestProperties.Add(this.requestProperties[i]);
                    }
                }
                if (!isKeyTypePresentInRstProperties)
                {
                    XmlElement keyTypeElement = this.StandardsManager.TrustDriver.CreateKeyTypeElement(this.keyType);
                    newRequestProperties.Insert(0, keyTypeElement);
                }
                if (this.keyType == SecurityKeyType.SymmetricKey)
                {
                    byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
                    rst.SetRequestorEntropy(requestorEntropy);
                }
                else if (this.keyType == SecurityKeyType.AsymmetricKey)
                {
                    RsaKeyIdentifierClause rsaClause     = new RsaKeyIdentifierClause(negotiationState.Rsa);
                    SecurityKeyIdentifier  keyIdentifier = new SecurityKeyIdentifier(rsaClause);
                    newRequestProperties.Add(this.StandardsManager.TrustDriver.CreateUseKeyElement(keyIdentifier, this.StandardsManager));
                    RsaSecurityTokenParameters rsaParameters = new RsaSecurityTokenParameters();
                    rsaParameters.InclusionMode      = SecurityTokenInclusionMode.Never;
                    rsaParameters.RequireDerivedKeys = false;
                    SupportingTokenSpecification rsaSpec = new SupportingTokenSpecification(negotiationState.RsaSecurityToken, EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, rsaParameters);
                    messageProperties = new MessageProperties();
                    SecurityMessageProperty security = new SecurityMessageProperty();
                    security.OutgoingSupportingTokens.Add(rsaSpec);
                    messageProperties.Security = security;
                }
                if (this.keyType == SecurityKeyType.SymmetricKey && this.KeyEntropyMode == SecurityKeyEntropyMode.CombinedEntropy)
                {
                    newRequestProperties.Add(this.StandardsManager.TrustDriver.CreateComputedKeyAlgorithmElement(this.StandardsManager.TrustDriver.ComputedKeyAlgorithm));
                }
                rst.RequestProperties = newRequestProperties;
                rst.MakeReadOnly();
                return(rst);
            }
        protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out NegotiationTokenAuthenticatorState negotiationState)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            if (requestSecurityToken == null)
            {
                throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
            }
            try
            {
                if (requestSecurityToken.RequestType != null && requestSecurityToken.RequestType != this.StandardsManager.TrustDriver.RequestTypeIssue)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.InvalidRstRequestType, requestSecurityToken.RequestType)), request);
                }
                if (requestSecurityToken.TokenType != null && requestSecurityToken.TokenType != this.SecurityContextTokenUri)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.CannotIssueRstTokenType, requestSecurityToken.TokenType)), request);
                }

                EndpointAddress        appliesTo;
                DataContractSerializer appliesToSerializer;
                string appliesToName;
                string appliesToNamespace;
                requestSecurityToken.GetAppliesToQName(out appliesToName, out appliesToNamespace);
                if (appliesToName == AddressingStrings.EndpointReference && appliesToNamespace == request.Version.Addressing.Namespace)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddress10>(appliesToSerializer).ToEndpointAddress();
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddressAugust2004>(appliesToSerializer).ToEndpointAddress();
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                else
                {
                    appliesTo           = null;
                    appliesToSerializer = null;
                }
                if (this.shouldMatchRstWithEndpointFilter)
                {
                    SecurityUtils.MatchRstWithEndpointFilter(request, this.EndpointFilterTable, this.ListenUri);
                }
                int           issuedKeySize;
                byte[]        issuerEntropy;
                byte[]        proofKey;
                SecurityToken proofToken;
                WSTrust.Driver.ProcessRstAndIssueKey(requestSecurityToken, null, this.KeyEntropyMode, this.SecurityAlgorithmSuite,
                                                     out issuedKeySize, out issuerEntropy, out proofKey, out proofToken);
                UniqueId contextId      = SecurityUtils.GenerateUniqueId();
                string   id             = SecurityUtils.GenerateId();
                DateTime effectiveTime  = DateTime.UtcNow;
                DateTime expirationTime = TimeoutHelper.Add(effectiveTime, this.ServiceTokenLifetime);
                // ensure that a SecurityContext is present in the message
                SecurityMessageProperty securityProperty = request.Properties.Security;
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;
                if (securityProperty != null)
                {
                    authorizationPolicies = SecuritySessionSecurityTokenAuthenticator.CreateSecureConversationPolicies(securityProperty, expirationTime);
                }
                else
                {
                    authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
                }
                SecurityContextSecurityToken serviceToken = this.IssueSecurityContextToken(contextId, id, proofKey, effectiveTime, expirationTime, authorizationPolicies,
                                                                                           this.EncryptStateInServiceToken);
                if (this.preserveBootstrapTokens)
                {
                    serviceToken.BootstrapMessageProperty = (securityProperty == null) ? null : (SecurityMessageProperty)securityProperty.CreateCopy();
                    SecurityUtils.ErasePasswordInUsernameTokenIfPresent(serviceToken.BootstrapMessageProperty);
                }
                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(this.StandardsManager);
                rstr.Context = requestSecurityToken.Context;
                rstr.KeySize = issuedKeySize;
                rstr.RequestedUnattachedReference = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
                rstr.RequestedAttachedReference   = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);
                rstr.TokenType = this.SecurityContextTokenUri;
                rstr.RequestedSecurityToken = serviceToken;
                if (issuerEntropy != null)
                {
                    rstr.SetIssuerEntropy(issuerEntropy);
                    rstr.ComputeKey = true;
                }
                if (proofToken != null)
                {
                    rstr.RequestedProofToken = proofToken;
                }
                if (appliesTo != null)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        rstr.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        rstr.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                rstr.MakeReadOnly();
                negotiationState = new NegotiationTokenAuthenticatorState();
                negotiationState.SetServiceToken(serviceToken);

                if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
                {
                    return(rstr);
                }
                else if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversation13)
                {
                    List <RequestSecurityTokenResponse> rstrList = new List <RequestSecurityTokenResponse>(1);
                    rstrList.Add(rstr);
                    RequestSecurityTokenResponseCollection rstrCollection = new RequestSecurityTokenResponseCollection(rstrList, this.StandardsManager);
                    return(rstrCollection);
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
            }
            finally
            {
                SecuritySessionSecurityTokenAuthenticator.RemoveCachedTokensIfRequired(request.Properties.Security);
            }
        }