void IDispatchMessageFormatter.DeserializeRequest(System.ServiceModel.Channels.Message message, object[] parameters)
        {
            int paramCounter = 0;

            XmlDictionaryReader bodyContentReader = message.GetReaderAtBodyContents();

            bodyContentReader.ReadStartElement(XmlRpcProtocol.Params);
            if (parameters.Length > 0)
            {
                while (bodyContentReader.IsStartElement(XmlRpcProtocol.Param) && paramCounter < parameters.Length)
                {
                    bodyContentReader.ReadStartElement();
                    if (bodyContentReader.IsStartElement(XmlRpcProtocol.Value))
                    {
                        bodyContentReader.ReadStartElement();
                        bodyContentReader.MoveToContent();
                        if (bodyContentReader.NodeType == XmlNodeType.Text)
                        {
                            parameters[paramCounter] = bodyContentReader.ReadContentAs(_parameterInfo[paramCounter].ParameterType, null);
                        }
                        else
                        {
                            parameters[paramCounter] = XmlRpcDataContractSerializationHelper.Deserialize(bodyContentReader, _parameterInfo[paramCounter].ParameterType);
                        }
                        bodyContentReader.ReadEndElement();
                    }
                    bodyContentReader.ReadEndElement();
                    bodyContentReader.MoveToContent();
                    paramCounter++;
                }
            }
            bodyContentReader.ReadEndElement();
            bodyContentReader.Close();
        }
        object IClientMessageFormatter.DeserializeReply(System.ServiceModel.Channels.Message message, object[] parameters)
        {
            object returnValue = null;

            XmlDictionaryReader bodyContentReader = message.GetReaderAtBodyContents();

            bodyContentReader.ReadStartElement(XmlRpcProtocol.MethodResponse);
            bodyContentReader.ReadStartElement(XmlRpcProtocol.Params);
            if (bodyContentReader.IsStartElement(XmlRpcProtocol.Param))
            {
                bodyContentReader.ReadStartElement();
                if (bodyContentReader.IsStartElement(XmlRpcProtocol.Value))
                {
                    bodyContentReader.ReadStartElement();
                    if (bodyContentReader.NodeType == XmlNodeType.Text)
                    {
                        returnValue = bodyContentReader.ReadContentAs(_returnParameter.ParameterType, null);
                    }
                    else
                    {
                        returnValue = XmlRpcDataContractSerializationHelper.Deserialize(bodyContentReader, _returnParameter.ParameterType);
                    }
                    bodyContentReader.ReadEndElement();
                }
                bodyContentReader.ReadEndElement();
                bodyContentReader.ReadEndElement();
            }
            bodyContentReader.Close();
            return(returnValue);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Enables inspection or modification of a message after a reply message is received but prior to passing it back to the client application.
        /// </summary>
        /// <param name="reply">The message to be transformed into types and handed back to the client application.</param>
        /// <param name="correlationState">Correlation state data.</param>
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            HttpResponseMessageProperty property = null;

            if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
            {
                property = (reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty);
            }
            if (property != null)
            {
                var errorStatus = property.Headers[NewtonsoftJsonErrorHandler.ClientHeader];
                if (errorStatus != null)
                {
                    XmlDictionaryReader            bodyReader = reply.GetReaderAtBodyContents();
                    Newtonsoft.Json.JsonSerializer serializer = endpoint.NewtonsoftSettings().JsonSerializer;
                    bodyReader.ReadStartElement("Binary");
                    byte[] body = bodyReader.ReadContentAsBase64();
                    using (MemoryStream ms = new MemoryStream(body)) {
                        using (StreamReader sr = new StreamReader(ms)) {
                            var result = (CommonFault)serializer.Deserialize(sr, typeof(CommonFault));
                            throw new FaultException <CommonFault>(result, result.Error);
                        }
                    }
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets the method message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns>WCF Method Message</returns>
        public WCFMethodMessage GetMethodMessage(ref System.ServiceModel.Channels.Message message)
        {
            string           action        = message.Headers.Action;
            WCFMethodMessage methodMessage = null;

            if (!string.IsNullOrEmpty(action))
            {
                if (this.Methods.ContainsKey(action))
                {
                    methodMessage = this.Methods[action];
                }
            }

            if (methodMessage == null)
            {
                try
                {
                    XmlDictionaryReader bodyReader  = message.GetReaderAtBodyContents();
                    string           root           = bodyReader.LocalName;
                    WCFMethodMessage methodMessage2 = this.Methods.Values.FirstOrDefault(s => string.Compare(s.Input, root, true) == 0);
                    if (methodMessage2 != null)
                    {
                        methodMessage = methodMessage2;
                        Message message2 = Message.CreateMessage(message.Version, methodMessage2.Action, bodyReader);
                        message = message2;
                    }
                }
                finally
                {
                }
            }

            return(methodMessage);
        }
Ejemplo n.º 5
0
        public string SelectOperation(ref System.ServiceModel.Channels.Message message)

        {
            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            XmlQualifiedName lookupQName = new XmlQualifiedName(bodyReader.LocalName, bodyReader.NamespaceURI);

            message = CreateMessageCopy(message, bodyReader);



            var operationName = dispatchDictionary.FirstOrDefault(e => lookupQName.Name.ToLower().Contains(e.ToLower()));



            if (operationName != null)

            {
                return(operationName);
            }



            return(defaultOperationName);
        }
        void ValidateMessageBody(ref System.ServiceModel.Channels.Message message, bool isRequest)
        {
            if (!message.IsFault)
            {
                XmlDictionaryReaderQuotas quotas  = new XmlDictionaryReaderQuotas();
                XmlReader         bodyReader      = message.GetReaderAtBodyContents().ReadSubtree();
                XmlReaderSettings wrapperSettings = new XmlReaderSettings();
                wrapperSettings.CloseInput              = true;
                wrapperSettings.Schemas                 = schemaSet;
                wrapperSettings.ValidationFlags         = XmlSchemaValidationFlags.None;
                wrapperSettings.ValidationType          = ValidationType.Schema;
                wrapperSettings.ValidationEventHandler +=
                    new ValidationEventHandler(InspectionValidationHandler);
                XmlReader wrappedReader = XmlReader.Create(bodyReader, wrapperSettings);

                // pull body into a memory backed writer to validate
                this.isRequest = isRequest;
                MemoryStream        memStream = new MemoryStream();
                XmlDictionaryWriter xdw       = XmlDictionaryWriter.CreateBinaryWriter(memStream);
                xdw.WriteNode(wrappedReader, false);
                xdw.Flush(); memStream.Position = 0;
                XmlDictionaryReader xdr = XmlDictionaryReader.CreateBinaryReader(memStream, quotas);

                // reconstruct the message with the validated body
                Message replacedMessage = Message.CreateMessage(message.Version, null, xdr);
                replacedMessage.Headers.CopyHeadersFrom(message.Headers);
                replacedMessage.Properties.CopyProperties(message.Properties);
                message = replacedMessage;
            }
        }
Ejemplo n.º 7
0
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            Debug.WriteLine("Apply receive reply");

            XElement body = (XElement)XElement.ReadFrom(reply.GetReaderAtBodyContents());

            body.Add(new XAttribute(XNamespace.Xmlns + "xsd", XsdNamespace));

            XName XsiTypeAttirbute = XsiNamespace + "type";

            IEnumerable <XElement> asmxTypes = body.DescendantsAndSelf().Where <XElement>(
                x => x.Attributes().Any <XAttribute>(
                    y => y.Name.Equals(XsiTypeAttirbute) &&
                    (y.Value.EndsWith(":char") || y.Value.EndsWith(":guid"))));

            if (asmxTypes.Count <XElement>() != 0)//later change this to Any()
            {
                XName WcfNamespaceAttribute = XNamespace.Xmlns + "wcf";

                foreach (XElement e in asmxTypes)
                {
                    e.SetAttributeValue(WcfNamespaceAttribute, WcfNamespace);
                    XAttribute typeAttribute = e.Attribute(XsiTypeAttirbute);
                    typeAttribute.Value = "wcf:" + typeAttribute.Value.Split(':')[1];
                }
            }

            Message newMessage = Message.CreateMessage(reply.Version, null, body.CreateReader());

            newMessage.Headers.CopyHeadersFrom(reply.Headers);
            newMessage.Properties.CopyProperties(reply.Properties);

            reply = newMessage;
        }
        /// <summary>
        /// Enables inspection or modification of a message before a request message is sent to a service.
        /// </summary>
        /// <param name="request">The message to be sent to the service.</param>
        /// <param name="channel">The  client object channel.</param>
        /// <returns>
        /// The object that is returned as the <paramref name="correlationState " />argument of the <see cref="M:System.ServiceModel.Dispatcher.IClientMessageInspector.AfterReceiveReply(System.ServiceModel.Channels.Message@,System.Object)" /> method. This is null if no correlation state is used.The best practice is to make this a <see cref="T:System.Guid" /> to ensure that no two <paramref name="correlationState" /> objects are the same.
        /// </returns>
        protected object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            XmlDocument document = new XmlDocument();

            using (XmlDictionaryReader reader1 = request.GetReaderAtBodyContents())
            {
                document.Load(reader1);
                //We will look at all the Elements in the document
                //Any that have an xsi:type attribute we will add the XSD namespace
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
                nsmgr.AddNamespace("olsa", "http://www.skillsoft.com/services/olsa_v1_0/");
                nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

                XmlNodeList xnList = document.SelectNodes("//*[@xsi:type]", nsmgr);
                foreach (XmlNode xn in xnList)
                {
                    var attr = document.CreateAttribute("xmlns", "xsd", "http://www.w3.org/2000/xmlns/");
                    attr.Value = "http://www.w3.org/2001/XMLSchema";
                    xn.Attributes.Append(attr);
                }
            }

            //Create a new message from the modified document body
            Message replacedMessage = Message.CreateMessage(request.Version, null, new XmlNodeReader(document));

            replacedMessage.Headers.CopyHeadersFrom(request.Headers);
            replacedMessage.Properties.CopyProperties(request.Properties);
            request = replacedMessage;

            document = null;
            return(null);
        }
Ejemplo n.º 9
0
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (correlationState != null && correlationState is string)
            {
                //     if we have a $metadata response then buffer the response
                //     and merge it with the updated items
                if (mdataresponse == string.Empty)
                {
                    XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
                    reader.ReadStartElement();
                    string content = MetadataInspector.encoding.GetString(reader.ReadContentAsBase64());

                    string filename = ((string)correlationState).Replace(@"/$", ".").Substring(1) + ".xml";
                    string fullpath = AppDomain.CurrentDomain.BaseDirectory + filename;

                    File.WriteAllText(fullpath, content);

                    mdataresponse = content;

                    //mdataresponse = MetadataConverter.Convert(content);
                }

                Message newreply = Message.CreateMessage(MessageVersion.None, "", new Writer(mdataresponse));
                newreply.Properties.CopyProperties(reply.Properties);

                reply = newreply;
            }
        }
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (reply == null)
            {
                throw new ArgumentNullException("reply");
            }

            if (correlationState != null && correlationState is string)
            {
                // if we have a JSONP callback then buffer the response, wrap it with the callback call and then re-create the response message
                string callback = (string)correlationState;

                XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
                reader.ReadStartElement();
                string content = JSONPSupportInspector.encoding.GetString(reader.ReadContentAsBase64());

                content = callback + "(" + content + ");";

                using (Message newreply = Message.CreateMessage(MessageVersion.None, "", new Writer(content)))
                {
                    newreply.Properties.CopyProperties(reply.Properties);

                    reply = newreply;

                    // change response content type to text/javascript if the JSON (only done when wrapped in a callback)
                    var replyProperties = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
                    replyProperties.Headers["Content-Type"] = replyProperties.Headers["Content-Type"].Replace("application/json", "text/javascript");
                }
            }
        }
        public string SelectOperation(ref System.ServiceModel.Channels.Message message)
        {
            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            message = CreateMessageCopy(message, bodyReader);
            message.Headers.Action = bodyReader.NamespaceURI + @"/" + bodyReader.LocalName;
            return(bodyReader.LocalName);
        }
Ejemplo n.º 12
0
        public string SelectOperation(ref System.ServiceModel.Channels.Message message)
        {
            // When WCF throw "This message cannot support the operation because it has been read" exception, see the following link to fix.
            //http://stackoverflow.com/a/11170390/2814166
            XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();

            //XmlQualifiedName lookupQName = new XmlQualifiedName(bodyReader.LocalName, bodyReader.NamespaceURI);
            message = CreateMessageCopy(message, bodyReader);
            return(bodyReader.LocalName);
        }
Ejemplo n.º 13
0
 public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
 {
     if (reply != null && reply.Version == MessageVersion.Soap11)
     {
         if (reply.IsFault)
         {
             throw new RawFaultException(reply.GetReaderAtBodyContents());
         }
     }
 }
Ejemplo n.º 14
0
        Message IDocumentRegistry.PatientRegistryRecordAdded(System.ServiceModel.Channels.Message input)
        {
            Message     msgResult      = null;
            XmlDocument xmlDocRequest  = null;
            XmlDocument xmlDocResponse = null;
            XDSResponse xdsResponse    = null;
            PatientIdentityFeedLogic  patientFeedLogic          = null;
            PatientIdentityFeedRecord patientIdentityFeedRecord = null;
            RegistryLogic             objRegistryLogic          = null;
            string eventOutcomeIndicator = "0";
            string sourceUserID          = string.Empty;
            string destinationUserID     = string.Empty;

            try
            {
                //ATNA Event - Active Participant Source UserID
                sourceUserID = GetSourceUserID();

                //ATNA Event - Active Participant Destination UserID
                destinationUserID = GetDestinationUserID();

                xmlDocRequest = new XmlDocument();
                xmlDocRequest.Load(input.GetReaderAtBodyContents());

                objRegistryLogic = new RegistryLogic();
                patientFeedLogic = new PatientIdentityFeedLogic();
                xdsResponse      = patientFeedLogic.PatientRegistryRecordAdded(xmlDocRequest);

                xmlDocResponse        = xdsResponse.XDSResponseDocument;
                eventOutcomeIndicator = xdsResponse.AtnaParameters["$EventIdentification.EventOutcomeIndicator$"];

                //ATNA
                patientIdentityFeedRecord = patientFeedLogic.GetPatient(xmlDocRequest);
            }
            catch (Exception)
            {
                //Log Error
                objRegistryLogic.CreateRegistryLogEntry(xmlDocRequest.InnerXml, GlobalValues.CONST_RESPONSE_STATUS_TYPE_FAILURE, DateTime.Now);

                //ATNA Event Failure Indicator
                eventOutcomeIndicator = "8";
            }

            //Log ATNA Event
            if (patientIdentityFeedRecord != null)
            {
                patientFeedLogic.ProcessPatientRecordAddATNAEvent(patientIdentityFeedRecord.PatientUID, sourceUserID, destinationUserID, eventOutcomeIndicator);
            }

            //Create Soap Message
            msgResult = Message.CreateMessage(input.Headers.MessageVersion, GlobalValues.CONST_ACTION_PatientIdentityFeedResponse, new XmlNodeReader(xmlDocResponse));


            return(msgResult);
        }
Ejemplo n.º 15
0
        private string GetResponse(string stsUrl, string realm)
        {
            RequestSecurityToken rst = new RequestSecurityToken();

            //rst.RequestType = WSTrustFeb2005Constants.RequestTypes.Issue;
            rst.RequestType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue";


            //bearer token, no encryption
            rst.AppliesTo = new EndpointReference(realm);
            //rst.KeyType = WSTrustFeb2005Constants.KeyTypes.Bearer;
            rst.KeyType = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";


            //WSTrustFeb2005RequestSerializer trustSerializer = new WSTrustFeb2005RequestSerializer();
            WSTrust13RequestSerializer trustSerializer = new WSTrust13RequestSerializer();
            WSHttpBinding binding = new WSHttpBinding();

            binding.Security.Mode = SecurityMode.Transport;

            binding.Security.Message.ClientCredentialType     = MessageCredentialType.None;
            binding.Security.Message.EstablishSecurityContext = false;

            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
            EndpointAddress address = new EndpointAddress(stsUrl);
            //WSTrustFeb2005ContractClient trustClient = new WSTrustFeb2005ContractClient(binding, address);
            WSTrust13ContractClient trustClient = new WSTrust13ContractClient(binding, address);

            trustClient.ClientCredentials.Windows.AllowNtlm = true;
            trustClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;

            // Does this need updating to include custom creds?
            //
            //
            //
            //trustClient.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
            trustClient.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(txtUserName.Text, txtPassword.Text, txtDomain.Text);
            //
            //
            //
            //


            System.ServiceModel.Channels.Message response =
                trustClient.EndIssue(trustClient.BeginIssue(
                                         System.ServiceModel.Channels.Message.CreateMessage(
                                             //MessageVersion.Default, WSTrustFeb2005Constants.Actions.Issue,
                                             MessageVersion.Default, "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue",
                                             new RequestBodyWriter(trustSerializer, rst)), null, null));
            trustClient.Close();

            XmlDictionaryReader reader = response.GetReaderAtBodyContents();

            return(reader.ReadOuterXml());
        }
        public static MessageFault CreateFault(Message message, int maxBufferSize)
        {
            MessageFault fault2;

            if (message == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
            }
            XmlDictionaryReader readerAtBodyContents = message.GetReaderAtBodyContents();
            XmlDictionaryReader reader2 = readerAtBodyContents;

            try
            {
                MessageFault    fault;
                EnvelopeVersion envelope = message.Version.Envelope;
                if (envelope == EnvelopeVersion.Soap12)
                {
                    fault = ReceivedFault.CreateFault12(readerAtBodyContents, maxBufferSize);
                }
                else if (envelope == EnvelopeVersion.Soap11)
                {
                    fault = ReceivedFault.CreateFault11(readerAtBodyContents, maxBufferSize);
                }
                else
                {
                    if (envelope != EnvelopeVersion.None)
                    {
                        throw TraceUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("EnvelopeVersionUnknown", new object[] { envelope.ToString() })), message);
                    }
                    fault = ReceivedFault.CreateFaultNone(readerAtBodyContents, maxBufferSize);
                }
                message.ReadFromBodyContentsToEnd(readerAtBodyContents);
                fault2 = fault;
            }
            catch (InvalidOperationException exception)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorDeserializingFault"), exception));
            }
            catch (FormatException exception2)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorDeserializingFault"), exception2));
            }
            catch (XmlException exception3)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SFxErrorDeserializingFault"), exception3));
            }
            finally
            {
                if (reader2 != null)
                {
                    reader2.Dispose();
                }
            }
            return(fault2);
        }
Ejemplo n.º 17
0
 public static XmlReader GetXmlReaderAtWebBodyContents(this System.ServiceModel.Channels.Message message)
 {
     // see https://blogs.msdn.microsoft.com/endpoint/2011/04/23/wcf-extensibility-message-inspectors/,
     return(message.GetWebContentFormat() switch {
         // see https://docs.microsoft.com/en-us/archive/blogs/endpoint/wcf-extensibility-message-inspectors, MessageToString
         WebContentFormat.Default or WebContentFormat.Xml => message.GetReaderAtBodyContents(),
         WebContentFormat.Raw => message.GetXmlReaderAtRawBodyContents(),
         var format => throw new ArgumentException(
             $"Unsupported {nameof(WebContentFormat)}.'{format}' message, only {WebContentFormat.Raw} and {WebContentFormat.Xml} are supported.",
             nameof(message))
     });
Ejemplo n.º 18
0
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            var soapAction = request.Headers.Action;
            XmlDictionaryReader bodyReader  = request.GetReaderAtBodyContents();
            var             soapXml         = bodyReader.ReadOuterXml();
            DafV4BodyWriter newBody         = new DafV4BodyWriter(soapXml);
            Message         replacedMessage = Message.CreateMessage(request.Version, soapAction, newBody);

            replacedMessage.Properties.CopyProperties(request.Properties);
            request        = replacedMessage;
            LastRequestXML = request.ToString();
            return(request);
        }
Ejemplo n.º 19
0
        public static MessageFault CreateFault(Message message, int maxBufferSize)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(message)));
            }

            XmlDictionaryReader reader = message.GetReaderAtBodyContents();

            using (reader)
            {
                try
                {
                    EnvelopeVersion envelopeVersion = message.Version.Envelope;
                    MessageFault    fault;
                    if (envelopeVersion == EnvelopeVersion.Soap12)
                    {
                        fault = ReceivedFault.CreateFault12(reader, maxBufferSize);
                    }
                    else if (envelopeVersion == EnvelopeVersion.Soap11)
                    {
                        fault = ReceivedFault.CreateFault11(reader, maxBufferSize);
                    }
                    else if (envelopeVersion == EnvelopeVersion.None)
                    {
                        fault = ReceivedFault.CreateFaultNone(reader, maxBufferSize);
                    }
                    else
                    {
                        throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.EnvelopeVersionUnknown, envelopeVersion.ToString())), message);
                    }
                    message.ReadFromBodyContentsToEnd(reader);
                    return(fault);
                }
                catch (InvalidOperationException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                                                                                  SR.SFxErrorDeserializingFault, e));
                }
                catch (FormatException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                                                                                  SR.SFxErrorDeserializingFault, e));
                }
                catch (XmlException e)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(
                                                                                  SR.SFxErrorDeserializingFault, e));
                }
            }
        }
Ejemplo n.º 20
0
        [MethodImpl(MethodImplOptions.Synchronized)] //QC 1446. Resolved threading issue with XSD validation
        void ValidateMessageBody(ref System.ServiceModel.Channels.Message message, bool isRequest)
        {
            if (!message.IsFault)
            {
                FailedValidation           = false;
                MessageDetailErrors.Length = 0;

                XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();

                using (XmlReader bodyReader = message.GetReaderAtBodyContents().ReadSubtree())
                {
                    XmlReaderSettings wrapperSettings = new XmlReaderSettings();
                    wrapperSettings.CloseInput = true;
                    wrapperSettings.Schemas    = schemaSet;
                    //wrapperSettings.ValidationFlags = XmlSchemaValidationFlags.None;
                    wrapperSettings.ValidationFlags         = XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.AllowXmlAttributes;
                    wrapperSettings.ValidationType          = ValidationType.Schema;
                    wrapperSettings.ValidationEventHandler +=
                        new ValidationEventHandler(InspectionValidationHandler);
                    using (XmlReader wrappedReader = XmlReader.Create(bodyReader, wrapperSettings))

                    {
                        // pull body into a memory backed writer to validate
                        this.isRequest = isRequest;

                        MemoryStream memStream = new MemoryStream();

                        XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateBinaryWriter(memStream);
                        xdw.WriteNode(wrappedReader, false);
                        xdw.Flush(); memStream.Position = 0;
                        XmlDictionaryReader xdr = XmlDictionaryReader.CreateBinaryReader(memStream, quotas);

                        // reconstruct the message with the validated body
                        Message replacedMessage = Message.CreateMessage(message.Version, null, xdr);
                        replacedMessage.Headers.CopyHeadersFrom(message.Headers);
                        replacedMessage.Properties.CopyProperties(message.Properties);
                        message = replacedMessage;
                    }
                }

                if (isRequest && FailedValidation)
                {
                    throw new ServiceRequestValidationException(MessageDetailErrors.ToString());
                }

                if (!isRequest && FailedValidation)
                {
                    throw new ServiceReplyValidationException(MessageDetailErrors.ToString());
                }
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Converts a generic WCF <see cref="Message"/> to an an <see cref="XmlMessage"/>.
 /// </summary>
 /// <typeparam name="TResponse">
 /// The type of the resulting converted <see cref="XmlMessage"/>.
 /// </typeparam>
 /// <param name="response">
 /// The generic WCF <see cref="Message"/> to convert.
 /// </param>
 /// <returns>
 /// The converted <see cref="XmlMessage"/>.
 /// </returns>
 public TResponse CreateXmlResponseFromMessageResponse <TResponse>(System.ServiceModel.Channels.Message response)
     where TResponse : XmlMessage, new()
 {
     if (response == null)
     {
         throw new ArgumentNullException(nameof(response));
     }
     using (var xmlReader = response.GetReaderAtBodyContents())
     {
         var xmlResponse = new TResponse();
         xmlResponse.ReadXml(xmlReader);
         return(xmlResponse);
     }
 }
Ejemplo n.º 22
0
        static MessageFault CreateFault11(Message message, int maxBufferSize)
        {
            FaultCode           fc      = null;
            FaultReason         fr      = null;
            object              details = null;
            XmlDictionaryReader r       = message.GetReaderAtBodyContents();

            r.ReadStartElement("Fault", message.Version.Envelope.Namespace);
            r.MoveToContent();

            while (r.NodeType != XmlNodeType.EndElement)
            {
                switch (r.LocalName)
                {
                case "faultcode":
                    fc = ReadFaultCode11(r);
                    break;

                case "faultstring":
                    fr = new FaultReason(r.ReadElementContentAsString());
                    break;

                case "detail":
                    //BUGBUG: Handle children of type other than ExceptionDetail, in order to comply with
                    //        FaultContractAttribute.
                    r.ReadStartElement();
                    r.MoveToContent();
                    details = new DataContractSerializer(typeof(ExceptionDetail)).ReadObject(r);
                    break;

                case "faultactor":
                default:
                    throw new NotImplementedException();
                }
                r.MoveToContent();
            }
            r.ReadEndElement();

            if (fr == null)
            {
                throw new XmlException("Reason is missing in the Fault message");
            }

            if (details == null)
            {
                return(CreateFault(fc, fr));
            }
            return(CreateFault(fc, fr, details));
        }
Ejemplo n.º 23
0
        public string SelectOperation(ref System.ServiceModel.Channels.Message message)
        {
            XmlDictionaryReader bodyReader  = message.GetReaderAtBodyContents();
            XmlQualifiedName    lookupQName = new XmlQualifiedName(bodyReader.LocalName, bodyReader.NamespaceURI);

            message = CreateMessageCopy(message, bodyReader);
            if (dispatchDictionary.ContainsKey(lookupQName))
            {
                return(dispatchDictionary[lookupQName]);
            }
            else
            {
                return(defaultOperationName);
            }
        }
Ejemplo n.º 24
0
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (correlationState != null && correlationState is string)
            {
                // if we have a JSONP callback then buffer the response, wrap it with the
                // callback call and then re-create the response message
                string callback = (string)correlationState;

                bool bodyIsText = false;
                HttpResponseMessageProperty response = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
                if (response != null)
                {
                    string contentType = response.Headers["Content-Type"];
                    if (contentType != null)
                    {
                        // Check the response type and change it to text/javascript if we know how.
                        if (contentType.StartsWith("text/plain", StringComparison.InvariantCultureIgnoreCase))
                        {
                            bodyIsText = true;
                            response.Headers["Content-Type"] = "text/javascript;charset=utf-8";
                        }
                        else if (contentType.StartsWith("application/json", StringComparison.InvariantCultureIgnoreCase))
                        {
                            response.Headers["Content-Type"] = contentType.Replace("application/json", "text/javascript");
                        }
                    }
                }

                XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
                reader.ReadStartElement();

                string content = JSONPSupportInspector.encoding.GetString(reader.ReadContentAsBase64());
                if (bodyIsText)
                {
                    // Escape the body as a string literal.
                    content = "\"" + QuoteJScriptString(content) + "\"";
                }

                content = callback + "(" + content + ")";

                System.ServiceModel.Channels.Message newreply = System.ServiceModel.Channels.Message.CreateMessage(MessageVersion.None, "", new Writer(content));
                newreply.Properties.CopyProperties(reply.Properties);

                reply = newreply;
            }
        }
        public static CloseSequenceInfo ReadMessage(MessageVersion messageVersion, Message message, MessageHeaders headers)
        {
            CloseSequenceInfo info;

            if (message.IsEmpty)
            {
                string str = System.ServiceModel.SR.GetString("NonEmptyWsrmMessageIsEmpty", new object[] { "http://docs.oasis-open.org/ws-rx/wsrm/200702/CloseSequence" });
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(str));
            }
            using (XmlDictionaryReader reader = message.GetReaderAtBodyContents())
            {
                info = CloseSequence.Create(reader);
                message.ReadFromBodyContentsToEnd(reader);
            }
            info.SetMessageId(messageVersion, headers);
            info.SetReplyTo(messageVersion, headers);
            return(info);
        }
        public static PeerHashToken CreateHashTokenFrom(Message message)
        {
            PeerHashToken        invalid = PeerHashToken.Invalid;
            RequestSecurityToken token2  = RequestSecurityToken.CreateFrom(message.GetReaderAtBodyContents());

            if (token2.RequestSecurityTokenXml != null)
            {
                foreach (System.Xml.XmlNode node in token2.RequestSecurityTokenXml.ChildNodes)
                {
                    XmlElement child = (XmlElement)node;
                    if ((child != null) && CompareWithNS(child.LocalName, child.NamespaceURI, "RequestedSecurityToken", "http://schemas.xmlsoap.org/ws/2005/02/trust"))
                    {
                        invalid = PeerHashToken.CreateFrom(child);
                    }
                }
            }
            return(invalid);
        }
Ejemplo n.º 27
0
        static MessageFault CreateFault11(Message message, int maxBufferSize)
        {
            FaultCode           fc      = null;
            FaultReason         fr      = null;
            object              details = null;
            XmlDictionaryReader r       = message.GetReaderAtBodyContents();

            r.ReadStartElement("Fault", message.Version.Envelope.Namespace);
            r.MoveToContent();

            while (r.NodeType != XmlNodeType.EndElement)
            {
                switch (r.LocalName)
                {
                case "faultcode":
                    fc = ReadFaultCode11(r);
                    break;

                case "faultstring":
                    fr = new FaultReason(r.ReadElementContentAsString());
                    break;

                case "detail":
                    return(new XmlReaderDetailMessageFault(message, r, fc, fr, null, null));

                case "faultactor":
                default:
                    throw new NotImplementedException();
                }
                r.MoveToContent();
            }
            r.ReadEndElement();

            if (fr == null)
            {
                throw new XmlException("Reason is missing in the Fault message");
            }

            if (details == null)
            {
                return(CreateFault(fc, fr));
            }
            return(CreateFault(fc, fr, details));
        }
Ejemplo n.º 28
0
        static MessageFault CreateFault11(Message message, int maxBufferSize)
        {
            FaultCode           fc    = null;
            FaultReason         fr    = null;
            string              actor = null;
            XmlDictionaryReader r     = message.GetReaderAtBodyContents();

            r.ReadStartElement("Fault", message.Version.Envelope.Namespace);
            r.MoveToContent();

            while (r.NodeType != XmlNodeType.EndElement)
            {
                switch (r.LocalName)
                {
                case "faultcode":
                    fc = ReadFaultCode11(r);
                    break;

                case "faultstring":
                    fr = new FaultReason(r.ReadElementContentAsString());
                    break;

                case "faultactor":
                    actor = r.ReadElementContentAsString();
                    break;

                case "detail":
                    return(new XmlReaderDetailMessageFault(message, r, fc, fr, actor, null));

                default:
                    throw new XmlException(String.Format("Unexpected node {0} name {1}", r.NodeType, r.Name));
                }
                r.MoveToContent();
            }
            r.ReadEndElement();

            if (fr == null)
            {
                throw new XmlException("Reason is missing in the Fault message");
            }

            return(new SimpleMessageFault(fc, fr, false, null, null, actor, null));
        }
Ejemplo n.º 29
0
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (correlationState != null && correlationState is string)
            {
                // if we have a JSONP callback then buffer the response, wrap it with the
                // callback call and then re-create the response message

                string callback = (string)correlationState;

                XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
                reader.ReadStartElement();
                string content = JSONPSupportInspector.encoding.GetString(reader.ReadContentAsBase64());

                content = callback + "(" + content + ")";

                Message newreply = Message.CreateMessage(MessageVersion.None, "", new Writer(content));
                newreply.Properties.CopyProperties(reply.Properties);

                reply = newreply;
            }
        }
        public static TerminateSequenceResponseInfo ReadMessage(MessageVersion messageVersion, Message message, MessageHeaders headers)
        {
            TerminateSequenceResponseInfo info;

            if (headers.RelatesTo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageHeaderException(System.ServiceModel.SR.GetString("MissingRelatesToOnWsrmResponseReason", new object[] { DXD.Wsrm11Dictionary.TerminateSequenceResponse }), messageVersion.Addressing.Namespace, "RelatesTo", false));
            }
            if (message.IsEmpty)
            {
                string str = System.ServiceModel.SR.GetString("NonEmptyWsrmMessageIsEmpty", new object[] { WsrmIndex.GetTerminateSequenceResponseActionString(ReliableMessagingVersion.WSReliableMessaging11) });
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(str));
            }
            using (XmlDictionaryReader reader = message.GetReaderAtBodyContents())
            {
                info = TerminateSequenceResponse.Create(reader);
                message.ReadFromBodyContentsToEnd(reader);
            }
            info.relatesTo = headers.RelatesTo;
            return(info);
        }
Ejemplo n.º 31
0
        /// <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;
        }