public static RequestSecurityToken CreateRequest(XmlReader reader, WSTrustSerializationContext context, WSTrustRequestSerializer requestSerializer, WSTrustConstantsAdapter trustConstants)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (requestSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestSerializer");
            }

            if (trustConstants == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustConstants");
            }

            if (!reader.IsStartElement(trustConstants.Elements.RequestSecurityToken, trustConstants.NamespaceURI))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3032, reader.LocalName, reader.NamespaceURI, trustConstants.Elements.RequestSecurityToken, trustConstants.NamespaceURI)));
            }

            bool isEmptyElement = reader.IsEmptyElement;
            RequestSecurityToken rst = requestSerializer.CreateRequestSecurityToken();
            rst.Context = reader.GetAttribute(trustConstants.Attributes.Context);
            reader.Read();
            if (!isEmptyElement)
            {
                while (reader.IsStartElement())
                {
                    requestSerializer.ReadXmlElement(reader, rst, context);
                }

                reader.ReadEndElement();
            }

            requestSerializer.Validate(rst);

            return rst;
        }
        /// <summary>
        /// Constructor for the WSTrustRequestBodyWriter.
        /// </summary>
        /// <param name="requestSecurityToken">The RequestSecurityToken object to be serialized in the outgoing Message.</param>
        /// <param name="serializer">Serializer is responsible for writting the requestSecurityToken into a XmlDictionaryWritter.</param>
        /// <param name="serializationContext">Context for the serialization.</param>
        /// <exception cref="ArgumentNullException">The 'requestSecurityToken' is null.</exception>
        /// <exception cref="ArgumentNullException">The 'serializer' is null.</exception>
        /// <exception cref="ArgumentNullException">The 'serializationContext' is null.</exception>
        public WSTrustRequestBodyWriter(System.IdentityModel.Protocols.WSTrust.RequestSecurityToken requestSecurityToken, WSTrustRequestSerializer serializer, WSTrustSerializationContext serializationContext)
            : base(true)
        {
            if (requestSecurityToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestSecurityToken");
            }

            if (serializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
            }

            if (serializationContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializationContext");
            }

            _requestSecurityToken = requestSecurityToken;
            _serializer = serializer;
            _serializationContext = serializationContext;
        }
        /// <summary>
        /// Handles Asynchronous call to the STS.
        /// </summary>
        /// <param name="requestMessage">Incoming Request message.</param>
        /// <param name="requestSerializer">Trust Request Serializer.</param>
        /// <param name="responseSerializer">Trust Response Serializer.</param>
        /// <param name="requestAction">Request SOAP action.</param>
        /// <param name="responseAction">Response SOAP action.</param>
        /// <param name="trustNamespace">Namespace URI of the trust version of the incoming request.</param>
        /// <param name="callback">Callback that gets invoked when the Asynchronous call ends.</param>
        /// <param name="state">state information of the Asynchronous call.</param>
        /// <returns>IAsyncResult that should be passed back to the End method to complete the Asynchronous call.</returns>
        /// <exception cref="ArgumentNullException">One of the argument is null.</exception>
        protected virtual IAsyncResult BeginProcessCore(Message requestMessage, WSTrustRequestSerializer requestSerializer, WSTrustResponseSerializer responseSerializer, string requestAction, string responseAction, string trustNamespace, AsyncCallback callback, object state)
        {
            if (requestMessage == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }

            if (requestSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestSerializer");
            }

            if (responseSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("responseSerializer");
            }

            if (String.IsNullOrEmpty(requestAction))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestAction");
            }

            if (String.IsNullOrEmpty(responseAction))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("responseAction");
            }

            if (String.IsNullOrEmpty(trustNamespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustNamespace");
            }

            IAsyncResult result = null;
            try
            {
                Fx.Assert(OperationContext.Current != null, "");
                Fx.Assert(OperationContext.Current.RequestContext != null, "");

                //
                // Create the Serialization and Dispatch context objects.
                //
                WSTrustSerializationContext serializationContext = CreateSerializationContext();

                DispatchContext dispatchContext = CreateDispatchContext(requestMessage,
                                                                         requestAction,
                                                                         responseAction,
                                                                         trustNamespace,
                                                                         requestSerializer,
                                                                         responseSerializer,
                                                                         serializationContext);

                //
                // Validate the dispatch context.
                //
                ValidateDispatchContext(dispatchContext);

                //
                // Dispatch the message asynchronously.
                //
                result = new ProcessCoreAsyncResult(this,
                                                     dispatchContext,
                                                     OperationContext.Current.RequestContext.RequestMessage.Version,
                                                     responseSerializer,
                                                     serializationContext,
                                                     callback,
                                                     state);
            }
            catch (Exception ex)
            {
                if (!HandleException(ex, trustNamespace, requestAction, requestMessage.Version.Envelope))
                {
                    throw;
                }
            }

            return result;
        }
        /// <summary>
        /// Creates a <see cref="DispatchContext"/> object for use by the <see cref="DispatchRequest"/> method.
        /// </summary>
        /// <param name="requestMessage">The incoming request message.</param>
        /// <param name="requestAction">The SOAP action of the request.</param>
        /// <param name="responseAction">The default SOAP action of the response.</param>
        /// <param name="trustNamespace">Namespace URI of the trust version of the incoming request.</param>
        /// <param name="requestSerializer">The <see cref="WSTrustRequestSerializer"/> used to deserialize 
        /// incoming RST messages.</param>
        /// <param name="responseSerializer">The <see cref="WSTrustResponseSerializer"/> used to deserialize 
        /// incoming RSTR messages.</param>
        /// <param name="serializationContext">The <see cref="WSTrustSerializationContext"/> to use 
        /// when deserializing incoming messages.</param>
        /// <returns>A <see cref="DispatchContext"/> object.</returns>
        protected virtual DispatchContext CreateDispatchContext(Message requestMessage,
                                                                 string requestAction,
                                                                 string responseAction,
                                                                 string trustNamespace,
                                                                 WSTrustRequestSerializer requestSerializer,
                                                                 WSTrustResponseSerializer responseSerializer,
                                                                 WSTrustSerializationContext serializationContext)
        {
            DispatchContext dispatchContext = new DispatchContext()
            {
                Principal = OperationContext.Current.ClaimsPrincipal as ClaimsPrincipal,
                RequestAction = requestAction,
                ResponseAction = responseAction,
                TrustNamespace = trustNamespace
            };

            XmlReader requestBodyReader = requestMessage.GetReaderAtBodyContents();
            //
            // Take a peek at the request with the serializers to figure out if this is a standard incoming
            // RST or if this is an instance of a challenge-response style message pattern where an RSTR comes in.
            //
            if (requestSerializer.CanRead(requestBodyReader))
            {
                dispatchContext.RequestMessage = requestSerializer.ReadXml(requestBodyReader, serializationContext);
            }
            else if (responseSerializer.CanRead(requestBodyReader))
            {
                dispatchContext.RequestMessage = responseSerializer.ReadXml(requestBodyReader, serializationContext);
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidRequestException(SR.GetString(SR.ID3114)));
            }

            //
            // CAUTION: Don't create the STS until after the RST or RSTR is deserialized or the test team
            //          has major infrastructure problems.
            //          
            dispatchContext.SecurityTokenService = CreateSTS();
            return dispatchContext;
        }
        /// <summary>
        /// Handles Synchronous calls to the STS.
        /// </summary>
        /// <param name="requestMessage">Incoming Request message.</param>
        /// <param name="requestSerializer">Trust Request Serializer.</param>
        /// <param name="responseSerializer">Trust Response Serializer.</param>
        /// <param name="requestAction">Request SOAP action.</param>
        /// <param name="responseAction">Response SOAP action.</param>
        /// <param name="trustNamespace">Namespace URI of the trust version of the incoming request.</param>
        /// <returns>Response message that contains the serialized RSTR.</returns>
        /// <exception cref="ArgumentNullException">One of the argument is null.</exception>
        protected virtual Message ProcessCore(Message requestMessage, WSTrustRequestSerializer requestSerializer, WSTrustResponseSerializer responseSerializer, string requestAction, string responseAction, string trustNamespace)
        {
            if (requestMessage == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestMessage");
            }

            if (requestSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestSerializer");
            }

            if (responseSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("responseSerializer");
            }

            if (String.IsNullOrEmpty(requestAction))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestAction");
            }

            if (String.IsNullOrEmpty(responseAction))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("responseAction");
            }

            if (String.IsNullOrEmpty(trustNamespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustNamespace");
            }

            Message response = null;
            try
            {
                Fx.Assert(OperationContext.Current != null, "");
                Fx.Assert(OperationContext.Current.RequestContext != null, "");

                //
                // Create the Serialization and Dispatch context objects.
                //
                WSTrustSerializationContext serializationContext = CreateSerializationContext();

                DispatchContext dispatchContext = CreateDispatchContext(requestMessage,
                                                                         requestAction,
                                                                         responseAction,
                                                                         trustNamespace,
                                                                         requestSerializer,
                                                                         responseSerializer,
                                                                         serializationContext);

                //
                // Validate the dispatch context.
                //
                ValidateDispatchContext(dispatchContext);

                //
                // Dispatch the STS message.
                //
                DispatchRequest(dispatchContext);

                //
                // Create the response Message object with the appropriate action.
                //
                response = Message.CreateMessage(OperationContext.Current.RequestContext.RequestMessage.Version,
                                                  dispatchContext.ResponseAction,
                                                  new WSTrustResponseBodyWriter(dispatchContext.ResponseMessage, responseSerializer, serializationContext));
            }
            catch (Exception ex)
            {
                if (!HandleException(ex, trustNamespace, requestAction, requestMessage.Version.Envelope))
                {
                    throw;
                }
            }

            return response;
        }
        public static void WriteKnownRequestElement(RequestSecurityToken rst, XmlWriter writer, WSTrustSerializationContext context, WSTrustRequestSerializer requestSerializer, WSTrustConstantsAdapter trustConstants)
        {
            if (rst == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rst");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (requestSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestSerializer");
            }

            if (trustConstants == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustConstants");
            }

            if (rst.AppliesTo != null)
            {
                requestSerializer.WriteXmlElement(writer, WSPolicyConstants.ElementNames.AppliesTo, rst.AppliesTo, rst, context);
            }

            if (rst.Claims.Count > 0)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.Claims, rst.Claims, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.ComputedKeyAlgorithm))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.ComputedKeyAlgorithm, rst.ComputedKeyAlgorithm, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.SignWith))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.SignWith, rst.SignWith, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.EncryptWith))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.EncryptWith, rst.EncryptWith, rst, context);
            }

            if (rst.Entropy != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.Entropy, rst.Entropy, rst, context);
            }

            if (rst.KeySizeInBits.HasValue)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.KeySize, rst.KeySizeInBits, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.KeyType))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.KeyType, rst.KeyType, rst, context);
            }

            if (rst.Lifetime != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.Lifetime, rst.Lifetime, rst, context);
            }

            if (rst.RenewTarget != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.RenewTarget, rst.RenewTarget, rst, context);
            }

            if (rst.OnBehalfOf != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.OnBehalfOf, rst.OnBehalfOf, rst, context);
            }

            if (rst.ActAs != null)
            {
                requestSerializer.WriteXmlElement(writer, WSTrust14Constants.ElementNames.ActAs, rst.ActAs, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.RequestType))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.RequestType, rst.RequestType, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.TokenType))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.TokenType, rst.TokenType, rst, context);
            }

            if (rst.UseKey != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.UseKey, rst.UseKey, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.AuthenticationType))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.AuthenticationType, rst.AuthenticationType, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.EncryptionAlgorithm))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.EncryptionAlgorithm, rst.EncryptionAlgorithm, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.CanonicalizationAlgorithm))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.CanonicalizationAlgorithm, rst.CanonicalizationAlgorithm, rst, context);
            }

            if (!string.IsNullOrEmpty(rst.SignatureAlgorithm))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.SignatureAlgorithm, rst.SignatureAlgorithm, rst, context);
            }

            if (rst.BinaryExchange != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.BinaryExchange, rst.BinaryExchange, rst, context);
            }

            if (rst.Issuer != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.Issuer, rst.Issuer, rst, context);
            }

            if (rst.ProofEncryption != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.ProofEncryption, rst.ProofEncryption, rst, context);
            }

            if (rst.Encryption != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.Encryption, rst.Encryption, rst, context);
            }

            if (rst.DelegateTo != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.DelegateTo, rst.DelegateTo, rst, context);
            }

            if (rst.Forwardable != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.Forwardable, rst.Forwardable.Value, rst, context);
            }

            if (rst.Delegatable != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.Delegatable, rst.Delegatable.Value, rst, context);
            }

            if (rst.AllowPostdating)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.AllowPostdating, rst.AllowPostdating, rst, context);
            }

            if (rst.Renewing != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.Renewing, rst.Renewing, rst, context);
            }

            if (rst.CancelTarget != null)
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.CancelTarget, rst.CancelTarget, rst, context);
            }

            if ((rst.Participants != null) && ((rst.Participants.Primary != null) || (rst.Participants.Participant.Count > 0)))
            {
                requestSerializer.WriteXmlElement(writer, trustConstants.Elements.Participants, rst.Participants, rst, context);
            }

            if (rst.AdditionalContext != null)
            {
                requestSerializer.WriteXmlElement(writer, WSAuthorizationConstants.Elements.AdditionalContext, rst.AdditionalContext, rst, context);
            }
        }
        public static void WriteRequest(RequestSecurityToken rst, XmlWriter writer, WSTrustSerializationContext context, WSTrustRequestSerializer requestSerializer, WSTrustConstantsAdapter trustConstants)
        {
            if (rst == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rst");
            }

            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            if (requestSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestSerializer");
            }

            if (trustConstants == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustConstants");
            }

            requestSerializer.Validate(rst);

            writer.WriteStartElement(trustConstants.Prefix, trustConstants.Elements.RequestSecurityToken, trustConstants.NamespaceURI);

            // Step 2: Write the first class attribute, i.e. Context
            // IDFX beta work item: use the handler to write out the context as well
            if (rst.Context != null)
            {
                writer.WriteAttributeString(trustConstants.Attributes.Context, (string)rst.Context);
            }

            // Step 3: Write the custom attributes here from the Attributes bag.
            // IDFX beta work item bug 878

            // Step 4: Write the first class Element here
            requestSerializer.WriteKnownRequestElement(rst, writer, context);

            // Step 5: Write the custom elements here from the Elements bag
            foreach (KeyValuePair<string, object> messageParam in rst.Properties)
            {
                requestSerializer.WriteXmlElement(writer, messageParam.Key, messageParam.Value, rst, context);
            }

            // Step 6: close the RST element
            writer.WriteEndElement();
        }