protected IAsyncResult BeginInvoke (string methodName, object[] parameters, AsyncCallback callback, object asyncState)
		{
			SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (methodName);

			SoapWebClientAsyncResult ainfo = null;
			try
			{
				SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
				message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);
				
				WebRequest request = GetRequestForMessage (uri, message);
				
				ainfo = new SoapWebClientAsyncResult (request, callback, asyncState);
				ainfo.Message = message;
				ainfo.Extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);

				ainfo.Request.BeginGetRequestStream (new AsyncCallback (AsyncGetRequestStreamDone), ainfo);
			}
			catch (Exception ex)
			{
				if (ainfo != null)
					ainfo.SetCompleted (null, ex, false);
			}

			return ainfo;
		}
        protected virtual XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize)
        {
            Encoding enc = message.SoapVersion == SoapProtocolVersion.Soap12 ? RequestResponseUtils.GetEncoding2(message.ContentType) : RequestResponseUtils.GetEncoding(message.ContentType);

            if (bufferSize < 512)
            {
                bufferSize = 512;
            }
            XmlTextReader reader;

            if (enc != null)
            {
                reader = new XmlTextReader(new StreamReader(message.Stream, enc, true, bufferSize));
            }
            else
            {
                //
                reader = new XmlTextReader(message.Stream);
            }

            reader.DtdProcessing = DtdProcessing.Prohibit;
            reader.Normalization = true;
            reader.XmlResolver   = null;

            return(reader);
        }
Beispiel #3
0
        protected object[] Invoke(string method_name, object[] parameters)
        {
            SoapMethodStubInfo msi = (SoapMethodStubInfo)type_info.GetMethod(method_name);

            SoapClientMessage message = new SoapClientMessage(this, msi, Url, parameters);

            message.CollectHeaders(this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);

            SoapExtension[] extensions = SoapExtension.CreateExtensionChain(type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);

            WebResponse response;

            try
            {
                WebRequest request = GetRequestForMessage(uri, message);
                SendRequest(request.GetRequestStream(), message, extensions);
                response = GetWebResponse(request);
            }
            catch (WebException ex)
            {
                response = ex.Response;
                HttpWebResponse http_response = response as HttpWebResponse;
                if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
                {
                    throw ex;
                }
            }

            try {
                return(ReceiveResponse(response, message, extensions));
            }
            finally {
                response.Close();
            }
        }
Beispiel #4
0
        protected IAsyncResult BeginInvoke(string methodName, object[] parameters, AsyncCallback callback, object asyncState)
        {
            SoapMethodStubInfo msi = (SoapMethodStubInfo)type_info.GetMethod(methodName);

            SoapWebClientAsyncResult ainfo = null;

            try
            {
                SoapClientMessage message = new SoapClientMessage(this, msi, Url, parameters);
                message.CollectHeaders(this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);

                WebRequest request = GetRequestForMessage(uri, message);

                ainfo            = new SoapWebClientAsyncResult(request, callback, asyncState);
                ainfo.Message    = message;
                ainfo.Extensions = SoapExtension.CreateExtensionChain(type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);

                ainfo.Request.BeginGetRequestStream(new AsyncCallback(AsyncGetRequestStreamDone), ainfo);
                RegisterMapping(asyncState, ainfo);
            }
            catch (Exception ex)
            {
                if (ainfo != null)
                {
                    ainfo.SetCompleted(null, ex, false);
                }
            }

            return(ainfo);
        }
Beispiel #5
0
        void SerializeRequest(Stream s, SoapClientMessage message, SoapExtension[] extensions)
        {
            try {
                if (extensions != null)
                {
                    s = (Stream)ReflectionHelper.ExecuteStaticMethod(SoapExtensionType, "ExecuteChainStream", null, extensions, s);
                    ReflectionHelper.ExecuteMethod(message, "SetStage", null, SoapMessageStage.BeforeSerialize);
                    ReflectionHelper.ExecuteStaticMethod(SoapExtensionType, "ExecuteProcessMessage", null, extensions, message, s, true);
                }

                using (XmlTextWriter xtw = new XmlTextWriter(s, new UTF8Encoding(false))) {
                    var methodStubInfo = ReflectionHelper.GetFieldValue(message, "MethodStubInfo");
                    var parameters     = ReflectionHelper.GetFieldValue(message, "Parameters");
                    var isSoap12Bool   = (bool)ReflectionHelper.GetPropertyValue(message, "IsSoap12");

                    WriteSoapMessage(xtw, methodStubInfo, SoapHeaderDirection.In, parameters, message.Headers, isSoap12Bool);

                    if (extensions != null)
                    {
                        ReflectionHelper.ExecuteMethod(message, "SetStage", SoapMessageStage.AfterSerialize);
                        ReflectionHelper.ExecuteStaticMethod(SoapExtensionType, "ExecuteProcessMessage", null, extensions, message, s, true);
                    }

                    xtw.Flush();
                    xtw.Close();
                }
            } catch (Exception ex) {
                Console.Write(ex);
                throw ex;
            }
        }
Beispiel #6
0
 protected virtual XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize)
 {
     if (bufferSize < 0x200)
     {
         bufferSize = 0x200;
     }
     return(new XmlTextWriter(new StreamWriter(message.Stream, (base.RequestEncoding != null) ? base.RequestEncoding : new UTF8Encoding(false), bufferSize)));
 }
Beispiel #7
0
        internal override void AsyncBufferedSerialize(WebRequest request, Stream requestStream, object internalAsyncState)
        {
            InvokeAsyncState  invokeState = (InvokeAsyncState)internalAsyncState;
            SoapClientMessage message     = invokeState.Message;

            message.SetStream(requestStream);
            Serialize(invokeState.Message);
        }
Beispiel #8
0
 protected virtual XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize)
 {
     if (bufferSize < 512)
     {
         bufferSize = 512;
     }
     return((XmlWriter) new XmlTextWriter((TextWriter) new StreamWriter(message.Stream, this.RequestEncoding != null ? this.RequestEncoding : (Encoding) new UTF8Encoding(false), bufferSize)));
 }
        void Serialize(SoapClientMessage message)
        {
            Stream           stream    = message.Stream;
            SoapClientMethod method    = message.Method;
            bool             isEncoded = method.use == SoapBindingUse.Encoded;

            // Serialize the message.
            string envelopeNs = EnvelopeNs;
            string encodingNs = EncodingNs;

            XmlWriter writer = GetWriterForMessage(message, 1024);

            if (writer == null)
            {
                throw new InvalidOperationException(Res.GetString(Res.WebNullWriterForMessage));
            }

            writer.WriteStartDocument();
            writer.WriteStartElement(Soap.Prefix, Soap.Element.Envelope, envelopeNs);
            writer.WriteAttributeString("xmlns", Soap.Prefix, null, envelopeNs);
            if (isEncoded)
            {
                writer.WriteAttributeString("xmlns", "soapenc", null, encodingNs);
                writer.WriteAttributeString("xmlns", "tns", null, clientType.serviceNamespace);
                writer.WriteAttributeString("xmlns", "types", null, SoapReflector.GetEncodedNamespace(clientType.serviceNamespace, clientType.serviceDefaultIsEncoded));
            }
            writer.WriteAttributeString("xmlns", "xsi", null, XmlSchema.InstanceNamespace);
            writer.WriteAttributeString("xmlns", "xsd", null, XmlSchema.Namespace);
            SoapHeaderHandling.WriteHeaders(writer, method.inHeaderSerializer, message.Headers, method.inHeaderMappings, SoapHeaderDirection.In, isEncoded, clientType.serviceNamespace, clientType.serviceDefaultIsEncoded, envelopeNs);
            writer.WriteStartElement(Soap.Element.Body, envelopeNs);
            if (isEncoded && version != SoapProtocolVersion.Soap12) // don't write encodingStyle on soap:Body for soap 1.2
            {
                writer.WriteAttributeString("soap", Soap.Attribute.EncodingStyle, null, encodingNs);
            }

            object[]    parameters = message.GetParameterValues();
            TraceMethod caller     = Tracing.On ? new TraceMethod(this, "Serialize") : null;

            if (Tracing.On)
            {
                Tracing.Enter(Tracing.TraceId(Res.TraceWriteRequest), caller, new TraceMethod(method.parameterSerializer, "Serialize", writer, parameters, null, isEncoded ? encodingNs : null));
            }
            method.parameterSerializer.Serialize(writer, parameters, null, isEncoded ? encodingNs : null);
            if (Tracing.On)
            {
                Tracing.Exit(Tracing.TraceId(Res.TraceWriteRequest), caller);
            }

            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();

            // run the after serialize extension pass.
            message.SetStage(SoapMessageStage.AfterSerialize);
            message.RunExtensions(message.initializedExtensions, true);
        }
Beispiel #10
0
        /// <summary>
        /// Invokes the webservice, the only twist here is an optional parameter to skip my implementation and use the old and original one. can be useful in some cases.
        /// I reapplied all the WS stuff originally found in the invoke methods and his siblongs, so all your extensions, headers and assorted ws-stuff should also work here.
        /// </summary>
        /// <param name="methodName">Method name.</param>
        /// <param name="parameters">Parameters.</param>
        /// <param name="legacyClient">If set to <c>true</c> uses the original SOAP client as implemented in Mono.</param>
        protected new object[] Invoke(string methodName, object[] parameters, bool legacyClient = false)
        {
            //skips the goodies!
            if (legacyClient)
            {
                return(base.Invoke(methodName, parameters));
            }

            try {
                object            theTypeInfoObject  = ReflectionHelper.GetFieldValue(this, "type_info");
                object            soapMethodStubInfo = ReflectionHelper.ExecuteMethod(theTypeInfoObject, "GetMethod", null, methodName);
                SoapClientMessage soapClientMessage  = (SoapClientMessage)ReflectionHelper.CreateInstance("System.Web.Services", "System.Web.Services.Protocols.SoapClientMessage", this, soapMethodStubInfo, base.Url, parameters);
                object            methodStubInfo     = ReflectionHelper.GetFieldValue(soapClientMessage, "MethodStubInfo");
                object            headers            = ReflectionHelper.GetFieldValue(methodStubInfo, "Headers");


                ReflectionHelper.ExecuteMethod(soapClientMessage, "CollectHeaders", null, this, headers, SoapHeaderDirection.In);

                object[] ClassConfiguredExtensions  = (object[])ReflectionHelper.GetFieldValue(theTypeInfoObject, "SoapExtensions");
                object[] MethodConfiguredExtensions = (object[])ReflectionHelper.GetFieldValue(soapMethodStubInfo, "SoapExtensions");

                Type[] methodTypes = new Type[] {
                    SoapExtensionRuntimeConfigArrayType,
                    SoapExtensionRuntimeConfigArrayType,
                    SoapExtensionRuntimeConfigArrayType
                };

                //extension chain
                SoapExtension[] extensions = (SoapExtension[])ReflectionHelper.ExecuteStaticMethod(SoapExtensionType, "CreateExtensionChain", methodTypes, ClassConfiguredExtensions[0], MethodConfiguredExtensions, ClassConfiguredExtensions[1]);

                //uri
                object thisUri = ReflectionHelper.GetFieldValue(this, "uri");

                //body
                string requestData = null;
                using (MemoryStream memoryStream = new MemoryStream()) {
                    SerializeRequest(memoryStream, soapClientMessage, extensions);
                    requestData = Encoding.UTF8.GetString(memoryStream.ToArray());
                }

                //HttpClient sync call
                using (HttpClientResponse clientResponse = AsyncOperatingContext.Run <HttpClientResponse>(() => {
                    HttpClientHelper.Proxy = Proxy;
                    HttpClientHelper.UserAgent = UserAgent;
                    HttpClientHelper.EnableDecompression = EnableDecompression;
                    HttpClientHelper.Timeout = Timeout;
                    return(HttpClientHelper.GetResponse((Uri)thisUri, requestData, soapClientMessage));
                })) {
                    object[] result = DeserializeResponse(clientResponse.DataStream, clientResponse.StatusCode, clientResponse.ContentType, (SoapClientMessage)soapClientMessage, (SoapExtension[])extensions);
                    return(result);
                }
            } catch (Exception ex) {
                Console.Write(ex);
                throw ex;
            }
        }
Beispiel #11
0
        private SoapClientMessage BeforeSerialize(WebRequest request, string methodName, object[] parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            SoapClientMethod method = this.clientType.GetMethod(methodName);

            if (method == null)
            {
                throw new ArgumentException(System.Web.Services.Res.GetString("WebInvalidMethodName", new object[1]
                {
                    (object)methodName
                }));
            }
            else
            {
                SoapExtension[]   soapExtensionArray = SoapMessage.InitializeExtensions((SoapReflectedExtension[])SoapHttpClientProtocol.CombineExtensionsHelper((Array)this.clientType.HighPriExtensions, (Array)method.extensions, (Array)this.clientType.LowPriExtensions, typeof(SoapReflectedExtension)), (object[])SoapHttpClientProtocol.CombineExtensionsHelper((Array)this.clientType.HighPriExtensionInitializers, (Array)method.extensionInitializers, (Array)this.clientType.LowPriExtensionInitializers, typeof(object)));
                SoapClientMessage soapClientMessage  = new SoapClientMessage(this, method, this.Url);
                soapClientMessage.initializedExtensions = soapExtensionArray;
                if (soapExtensionArray != null)
                {
                    soapClientMessage.SetExtensionStream(new SoapExtensionStream());
                }
                soapClientMessage.InitExtensionStreamChain(soapClientMessage.initializedExtensions);
                string action = UrlEncoder.EscapeString(method.action, Encoding.UTF8);
                soapClientMessage.SetStage(SoapMessageStage.BeforeSerialize);
                if (this.version == SoapProtocolVersion.Soap12)
                {
                    soapClientMessage.ContentType = ContentType.Compose("application/soap+xml", this.RequestEncoding != null ? this.RequestEncoding : Encoding.UTF8, action);
                }
                else
                {
                    soapClientMessage.ContentType = ContentType.Compose("text/xml", this.RequestEncoding != null ? this.RequestEncoding : Encoding.UTF8);
                }
                soapClientMessage.SetParameterValues(parameters);
                SoapHeaderHandling.GetHeaderMembers(soapClientMessage.Headers, (object)this, method.inHeaderMappings, SoapHeaderDirection.In, true);
                soapClientMessage.RunExtensions(soapClientMessage.initializedExtensions, true);
                request.ContentType = soapClientMessage.ContentType;
                if (soapClientMessage.ContentEncoding != null && soapClientMessage.ContentEncoding.Length > 0)
                {
                    ((NameValueCollection)request.Headers)["Content-Encoding"] = soapClientMessage.ContentEncoding;
                }
                request.Method = "POST";
                if (this.version != SoapProtocolVersion.Soap12 && ((NameValueCollection)request.Headers)["SOAPAction"] == null)
                {
                    StringBuilder stringBuilder = new StringBuilder(action.Length + 2);
                    stringBuilder.Append('"');
                    stringBuilder.Append(action);
                    stringBuilder.Append('"');
                    ((NameValueCollection)request.Headers).Add("SOAPAction", ((object)stringBuilder).ToString());
                }
                return(soapClientMessage);
            }
        }
Beispiel #12
0
        private SoapClientMessage BeforeSerialize(WebRequest request, string methodName, object[] parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            SoapClientMethod method = this.clientType.GetMethod(methodName);

            if (method == null)
            {
                throw new ArgumentException(System.Web.Services.Res.GetString("WebInvalidMethodName", new object[] { methodName }));
            }
            SoapReflectedExtension[] reflectedExtensions = (SoapReflectedExtension[])CombineExtensionsHelper(this.clientType.HighPriExtensions, method.extensions, this.clientType.LowPriExtensions, typeof(SoapReflectedExtension));
            object[]          extensionInitializers      = (object[])CombineExtensionsHelper(this.clientType.HighPriExtensionInitializers, method.extensionInitializers, this.clientType.LowPriExtensionInitializers, typeof(object));
            SoapExtension[]   extensionArray2            = SoapMessage.InitializeExtensions(reflectedExtensions, extensionInitializers);
            SoapClientMessage message = new SoapClientMessage(this, method, base.Url)
            {
                initializedExtensions = extensionArray2
            };

            if (extensionArray2 != null)
            {
                message.SetExtensionStream(new SoapExtensionStream());
            }
            message.InitExtensionStreamChain(message.initializedExtensions);
            string action = UrlEncoder.EscapeString(method.action, Encoding.UTF8);

            message.SetStage(SoapMessageStage.BeforeSerialize);
            if (this.version == SoapProtocolVersion.Soap12)
            {
                message.ContentType = ContentType.Compose("application/soap+xml", (base.RequestEncoding != null) ? base.RequestEncoding : Encoding.UTF8, action);
            }
            else
            {
                message.ContentType = ContentType.Compose("text/xml", (base.RequestEncoding != null) ? base.RequestEncoding : Encoding.UTF8);
            }
            message.SetParameterValues(parameters);
            SoapHeaderHandling.GetHeaderMembers(message.Headers, this, method.inHeaderMappings, SoapHeaderDirection.In, true);
            message.RunExtensions(message.initializedExtensions, true);
            request.ContentType = message.ContentType;
            if ((message.ContentEncoding != null) && (message.ContentEncoding.Length > 0))
            {
                request.Headers["Content-Encoding"] = message.ContentEncoding;
            }
            request.Method = "POST";
            if ((this.version != SoapProtocolVersion.Soap12) && (request.Headers["SOAPAction"] == null))
            {
                StringBuilder builder = new StringBuilder(action.Length + 2);
                builder.Append('"');
                builder.Append(action);
                builder.Append('"');
                request.Headers.Add("SOAPAction", builder.ToString());
            }
            return(message);
        }
Beispiel #13
0
        private void Serialize(SoapClientMessage message)
        {
            Stream           stream           = message.Stream;
            SoapClientMethod method           = message.Method;
            bool             isEncoded        = method.use == SoapBindingUse.Encoded;
            string           envelopeNs       = this.EnvelopeNs;
            string           encodingNs       = this.EncodingNs;
            XmlWriter        writerForMessage = this.GetWriterForMessage(message, 1024);

            if (writerForMessage == null)
            {
                throw new InvalidOperationException(System.Web.Services.Res.GetString("WebNullWriterForMessage"));
            }
            writerForMessage.WriteStartDocument();
            writerForMessage.WriteStartElement("soap", "Envelope", envelopeNs);
            writerForMessage.WriteAttributeString("xmlns", "soap", (string)null, envelopeNs);
            if (isEncoded)
            {
                writerForMessage.WriteAttributeString("xmlns", "soapenc", (string)null, encodingNs);
                writerForMessage.WriteAttributeString("xmlns", "tns", (string)null, this.clientType.serviceNamespace);
                writerForMessage.WriteAttributeString("xmlns", "types", (string)null, SoapReflector.GetEncodedNamespace(this.clientType.serviceNamespace, this.clientType.serviceDefaultIsEncoded));
            }
            writerForMessage.WriteAttributeString("xmlns", "xsi", (string)null, "http://www.w3.org/2001/XMLSchema-instance");
            writerForMessage.WriteAttributeString("xmlns", "xsd", (string)null, "http://www.w3.org/2001/XMLSchema");
            SoapHeaderHandling.WriteHeaders(writerForMessage, method.inHeaderSerializer, message.Headers, method.inHeaderMappings, SoapHeaderDirection.In, isEncoded, this.clientType.serviceNamespace, this.clientType.serviceDefaultIsEncoded, envelopeNs);
            writerForMessage.WriteStartElement("Body", envelopeNs);
            if (isEncoded && this.version != SoapProtocolVersion.Soap12)
            {
                writerForMessage.WriteAttributeString("soap", "encodingStyle", (string)null, encodingNs);
            }
            object[]    parameterValues = message.GetParameterValues();
            TraceMethod caller          = Tracing.On ? new TraceMethod((object)this, "Serialize", new object[0]) : (TraceMethod)null;

            if (Tracing.On)
            {
                Tracing.Enter(Tracing.TraceId("TraceWriteRequest"), caller, new TraceMethod((object)method.parameterSerializer, "Serialize", new object[4]
                {
                    (object)writerForMessage,
                    (object)parameterValues,
                    null,
                    isEncoded ? (object)encodingNs : (object)(string)null
                }));
            }
            method.parameterSerializer.Serialize(writerForMessage, (object)parameterValues, (XmlSerializerNamespaces)null, isEncoded ? encodingNs : (string)null);
            if (Tracing.On)
            {
                Tracing.Exit(Tracing.TraceId("TraceWriteRequest"), caller);
            }
            writerForMessage.WriteEndElement();
            writerForMessage.WriteEndElement();
            writerForMessage.Flush();
            message.SetStage(SoapMessageStage.AfterSerialize);
            message.RunExtensions(message.initializedExtensions, true);
        }
Beispiel #14
0
 protected override XmlReader GetReaderForMessage(System.Web.Services.Protocols.SoapClientMessage message, int bufferSize)
 {
     if (!AgsLogger.IsLogging)
     {
         return(base.GetReaderForMessage(message, bufferSize));
     }
     else
     {
         return(new AgsLoggingXmlReader(message.Stream, bufferSize));
     }
 }
Beispiel #15
0
        protected override XmlWriter GetWriterForMessage(System.Web.Services.Protocols.SoapClientMessage message, int bufferSize)
        {
            if (!AgsLogger.IsLogging)
            {
                return(base.GetWriterForMessage(message, bufferSize));
            }
            else
            {
                var requestXML = new AgsLoggingXmlWriter(message.Stream);

                return(requestXML);
            }
        }
 private SoapClientMessage BeforeSerialize(WebRequest request, string methodName, object[] parameters)
 {
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     SoapClientMethod method = this.clientType.GetMethod(methodName);
     if (method == null)
     {
         throw new ArgumentException(System.Web.Services.Res.GetString("WebInvalidMethodName", new object[] { methodName }));
     }
     SoapReflectedExtension[] reflectedExtensions = (SoapReflectedExtension[]) CombineExtensionsHelper(this.clientType.HighPriExtensions, method.extensions, this.clientType.LowPriExtensions, typeof(SoapReflectedExtension));
     object[] extensionInitializers = (object[]) CombineExtensionsHelper(this.clientType.HighPriExtensionInitializers, method.extensionInitializers, this.clientType.LowPriExtensionInitializers, typeof(object));
     SoapExtension[] extensionArray2 = SoapMessage.InitializeExtensions(reflectedExtensions, extensionInitializers);
     SoapClientMessage message = new SoapClientMessage(this, method, base.Url) {
         initializedExtensions = extensionArray2
     };
     if (extensionArray2 != null)
     {
         message.SetExtensionStream(new SoapExtensionStream());
     }
     message.InitExtensionStreamChain(message.initializedExtensions);
     string action = UrlEncoder.EscapeString(method.action, Encoding.UTF8);
     message.SetStage(SoapMessageStage.BeforeSerialize);
     if (this.version == SoapProtocolVersion.Soap12)
     {
         message.ContentType = ContentType.Compose("application/soap+xml", (base.RequestEncoding != null) ? base.RequestEncoding : Encoding.UTF8, action);
     }
     else
     {
         message.ContentType = ContentType.Compose("text/xml", (base.RequestEncoding != null) ? base.RequestEncoding : Encoding.UTF8);
     }
     message.SetParameterValues(parameters);
     SoapHeaderHandling.GetHeaderMembers(message.Headers, this, method.inHeaderMappings, SoapHeaderDirection.In, true);
     message.RunExtensions(message.initializedExtensions, true);
     request.ContentType = message.ContentType;
     if ((message.ContentEncoding != null) && (message.ContentEncoding.Length > 0))
     {
         request.Headers["Content-Encoding"] = message.ContentEncoding;
     }
     request.Method = "POST";
     if ((this.version != SoapProtocolVersion.Soap12) && (request.Headers["SOAPAction"] == null))
     {
         StringBuilder builder = new StringBuilder(action.Length + 2);
         builder.Append('"');
         builder.Append(action);
         builder.Append('"');
         request.Headers.Add("SOAPAction", builder.ToString());
     }
     return message;
 }
Beispiel #17
0
        WebRequest GetRequestForMessage(Uri uri, SoapClientMessage message)
        {
            WebRequest request = GetWebRequest(uri);

            request.Method = "POST";
            WebHeaderCollection headers = request.Headers;

            if (!message.IsSoap12)
            {
                headers.Add("SOAPAction", "\"" + message.Action + "\"");
            }
            request.ContentType = message.ContentType + "; charset=utf-8";
            return(request);
        }
Beispiel #18
0
        protected object[] Invoke(string methodName, object[] parameters)
        {
            WebResponse webResponse = null;
            WebRequest  webRequest  = null;

            object[] objArray;
            try
            {
                webRequest = this.GetWebRequest(base.Uri);
                base.NotifyClientCallOut(webRequest);
                base.PendingSyncRequest = webRequest;
                SoapClientMessage message       = this.BeforeSerialize(webRequest, methodName, parameters);
                Stream            requestStream = webRequest.GetRequestStream();
                try
                {
                    message.SetStream(requestStream);
                    this.Serialize(message);
                }
                finally
                {
                    requestStream.Close();
                }
                webResponse = this.GetWebResponse(webRequest);
                Stream responseStream = null;
                try
                {
                    responseStream = webResponse.GetResponseStream();
                    objArray       = this.ReadResponse(message, webResponse, responseStream, false);
                }
                catch (XmlException exception)
                {
                    throw new InvalidOperationException(System.Web.Services.Res.GetString("WebResponseBadXml"), exception);
                }
                finally
                {
                    if (responseStream != null)
                    {
                        responseStream.Close();
                    }
                }
            }
            finally
            {
                if (webRequest == base.PendingSyncRequest)
                {
                    base.PendingSyncRequest = null;
                }
            }
            return(objArray);
        }
Beispiel #19
0
        protected virtual XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize)
        {
            Encoding encoding = message.SoapVersion == SoapProtocolVersion.Soap12 ? RequestResponseUtils.GetEncoding2(message.ContentType) : RequestResponseUtils.GetEncoding(message.ContentType);

            if (bufferSize < 512)
            {
                bufferSize = 512;
            }
            XmlTextReader xmlTextReader = encoding == null ? new XmlTextReader(message.Stream) : new XmlTextReader((TextReader) new StreamReader(message.Stream, encoding, true, bufferSize));

            xmlTextReader.DtdProcessing = DtdProcessing.Prohibit;
            xmlTextReader.Normalization = true;
            xmlTextReader.XmlResolver   = (XmlResolver)null;
            return((XmlReader)xmlTextReader);
        }
Beispiel #20
0
        protected object[] Invoke(string methodName, object[] parameters)
        {
            WebRequest request = (WebRequest)null;

            try
            {
                request = this.GetWebRequest(this.Uri);
                this.NotifyClientCallOut(request);
                this.PendingSyncRequest = request;
                SoapClientMessage message       = this.BeforeSerialize(request, methodName, parameters);
                Stream            requestStream = request.GetRequestStream();
                try
                {
                    message.SetStream(requestStream);
                    this.Serialize(message);
                }
                finally
                {
                    requestStream.Close();
                }
                WebResponse webResponse    = this.GetWebResponse(request);
                Stream      responseStream = (Stream)null;
                try
                {
                    responseStream = webResponse.GetResponseStream();
                    return(this.ReadResponse(message, webResponse, responseStream, false));
                }
                catch (XmlException ex)
                {
                    throw new InvalidOperationException(System.Web.Services.Res.GetString("WebResponseBadXml"), (Exception)ex);
                }
                finally
                {
                    if (responseStream != null)
                    {
                        responseStream.Close();
                    }
                }
            }
            finally
            {
                if (request == this.PendingSyncRequest)
                {
                    this.PendingSyncRequest = (WebRequest)null;
                }
            }
        }
        /// <include file='doc\SoapClientProtocol.uex' path='docs/doc[@for="SoapHttpClientProtocol.Invoke"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Invokes a method of a SOAP web service.
        ///    </para>
        /// </devdoc>
        protected object[] Invoke(string methodName, object[] parameters)
        {
            WebResponse response = null;
            WebRequest  request  = null;

            try {
                request = GetWebRequest(Uri);
                NotifyClientCallOut(request);
                //
                PendingSyncRequest = request;
                SoapClientMessage message       = BeforeSerialize(request, methodName, parameters);
                Stream            requestStream = request.GetRequestStream();
                try {
                    message.SetStream(requestStream);
                    Serialize(message);
                }
                finally {
                    requestStream.Close();
                }

                response = GetWebResponse(request);
                Stream responseStream = null;
                try {
                    responseStream = response.GetResponseStream();
                    return(ReadResponse(message, response, responseStream, false));
                }
                catch (XmlException e) {
                    throw new InvalidOperationException(Res.GetString(Res.WebResponseBadXml), e);
                }
                finally {
                    if (responseStream != null)
                    {
                        responseStream.Close();
                    }
                }
            }
            finally {
                if (request == PendingSyncRequest)
                {
                    PendingSyncRequest = null;
                }
            }
        }
        protected virtual XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize)
        {
            if (bufferSize < 512)
            {
                bufferSize = 512;
            }
            XmlTextWriter writer = new XmlTextWriter(new StreamWriter(message.Stream, RequestEncoding != null ? RequestEncoding : new UTF8Encoding(false), bufferSize));

            /*
             * if (RequestEncoding != null && RequestEncoding.GetType() != typeof(UTF8Encoding)) {
             *  writer = new XmlTextWriter(new StreamWriter(message.Stream, RequestEncoding, bufferSize));
             * }
             * else {
             *  XmlWriterSettings ws = new XmlWriterSettings();
             *  ws.Encoding = new UTF8Encoding(false);
             *  ws.Indent = false;
             *  ws.NewLineHandling = NewLineHandling.None;
             *  writer = XmlWriter.Create(message.Stream, ws);
             * }
             */
            return(writer);
        }
Beispiel #23
0
        /// <include file='doc\SoapClientProtocol.uex' path='docs/doc[@for="SoapHttpClientProtocol.Invoke"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Invokes a method of a SOAP web service.
        ///    </para>
        /// </devdoc>
        protected object[] Invoke(string methodName, object[] parameters)
        {
            WebResponse response = null;
            WebRequest  request  = null;

            try {
                request = GetWebRequest(Uri);
                // CONSIDER,yannc: when we expose protocol extensibility we will want a better way to set/clear this.
                PendingSyncRequest = request;
                SoapClientMessage message       = BeforeSerialize(request, methodName, parameters);
                Stream            requestStream = request.GetRequestStream();
                try {
                    message.SetStream(requestStream);
                    Serialize(message);
                }
                finally {
                    requestStream.Close();
                }

                response = GetWebResponse(request);
                Stream responseStream = null;
                try {
                    responseStream = response.GetResponseStream();
                    return(ReadResponse(message, response, responseStream, false));
                }
                finally {
                    if (responseStream != null)
                    {
                        responseStream.Close();
                    }
                }
            }
            finally {
                if (request == PendingSyncRequest)
                {
                    PendingSyncRequest = null;
                }
            }
        }
Beispiel #24
0
        void Serialize(SoapClientMessage message)
        {
            Stream           stream    = message.Stream;
            SoapClientMethod method    = message.Method;
            bool             isEncoded = method.use == SoapBindingUse.Encoded;
            // Serialize the message.
            string        envelopeNs = EnvelopeNs;
            string        encodingNs = EncodingNs;
            StreamWriter  sw         = new StreamWriter(stream, RequestEncoding != null ? RequestEncoding : new UTF8Encoding(false), 128);
            XmlTextWriter writer     = isEncoded && message.Headers.Count > 0 ? new XmlSpecialTextWriter(sw, version) : new XmlTextWriter(sw);

            writer.WriteStartDocument();
            writer.WriteStartElement("soap", Soap.Envelope, envelopeNs);
            writer.WriteAttributeString("xmlns", "soap", null, envelopeNs);
            if (isEncoded)
            {
                writer.WriteAttributeString("xmlns", "soapenc", null, encodingNs);
                writer.WriteAttributeString("xmlns", "tns", null, clientType.serviceNamespace);
                writer.WriteAttributeString("xmlns", "types", null, SoapReflector.GetEncodedNamespace(clientType.serviceNamespace, clientType.serviceDefaultIsEncoded));
            }
            writer.WriteAttributeString("xmlns", "xsi", null, XmlSchema.InstanceNamespace);
            writer.WriteAttributeString("xmlns", "xsd", null, XmlSchema.Namespace);
            SoapHeaderHandling.WriteHeaders(writer, method.inHeaderSerializer, message.Headers, method.inHeaderMappings, SoapHeaderDirection.In, isEncoded, clientType.serviceNamespace, clientType.serviceDefaultIsEncoded, envelopeNs);
            writer.WriteStartElement(Soap.Body, envelopeNs);
            if (isEncoded)
            {
                writer.WriteAttributeString("soap", Soap.EncodingStyle, null, encodingNs);
            }
            // SOAP12: not using encodingStyle
            //method.parameterSerializer.Serialize(writer, message.GetParameterValues(), null, isEncoded ? encodingNs : null);
            method.parameterSerializer.Serialize(writer, message.GetParameterValues(), null);
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();

            // run the after serialize extension pass.
            message.SetStage(SoapMessageStage.AfterSerialize);
            message.RunExtensions(message.initializedExtensions);
        }
Beispiel #25
0
        void SendRequest(Stream s, SoapClientMessage message, SoapExtension[] extensions)
        {
            using (s) {
                if (extensions != null)
                {
                    s = SoapExtension.ExecuteChainStream(extensions, s);
                    message.SetStage(SoapMessageStage.BeforeSerialize);
                    SoapExtension.ExecuteProcessMessage(extensions, message, s, true);
                }

                XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter(s);
                WebServiceHelper.WriteSoapMessage(xtw, message.MethodStubInfo, SoapHeaderDirection.In, message.Parameters, message.Headers, message.IsSoap12);

                if (extensions != null)
                {
                    message.SetStage(SoapMessageStage.AfterSerialize);
                    SoapExtension.ExecuteProcessMessage(extensions, message, s, true);
                }

                xtw.Flush();
                xtw.Close();
            }
        }
        protected virtual XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize) {
            Encoding enc = message.SoapVersion == SoapProtocolVersion.Soap12 ? RequestResponseUtils.GetEncoding2(message.ContentType) : RequestResponseUtils.GetEncoding(message.ContentType);
            if (bufferSize < 512)
                bufferSize = 512;
            XmlTextReader reader;
            if (enc != null)
                reader = new XmlTextReader(new StreamReader(message.Stream, enc, true, bufferSize));
            else
                // 
                reader = new XmlTextReader(message.Stream);

            reader.DtdProcessing = DtdProcessing.Prohibit;
            reader.Normalization = true;
            reader.XmlResolver = null;

            return reader;
        }
 protected virtual XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize) {
     if (bufferSize < 512)
         bufferSize = 512;
     XmlTextWriter writer = new XmlTextWriter(new StreamWriter(message.Stream, RequestEncoding != null ? RequestEncoding : new UTF8Encoding(false), bufferSize));
     /*
     if (RequestEncoding != null && RequestEncoding.GetType() != typeof(UTF8Encoding)) {
         writer = new XmlTextWriter(new StreamWriter(message.Stream, RequestEncoding, bufferSize));
     }
     else {
         XmlWriterSettings ws = new XmlWriterSettings();
         ws.Encoding = new UTF8Encoding(false);
         ws.Indent = false;
         ws.NewLineHandling = NewLineHandling.None;
         writer = XmlWriter.Create(message.Stream, ws);
     }
     */
     return writer;
 }
Beispiel #28
0
        public static async Task <HttpClientResponse> GetResponse(Uri address, string requestBody, SoapClientMessage message)
        {
            //Create the HttpClient for this server
            using (HttpClient client = GetHttpClientForAddress(address.Scheme + "://" + address.Host)) {
                //Headers
                bool isSoap12 = (bool)ReflectionHelper.GetPropertyValue(message, "IsSoap12");
                if (!isSoap12)
                {
                    client.DefaultRequestHeaders.Add("SOAPAction", "\"" + message.Action + "\"");
                }

                //if we use Add instead of TryAddWithoutValidation the client will automatically add commas wherever it finds a space.
                //very ugly and probably not what we want.
                client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", UserAgent);

                //Should be:
                //User-Agent: Mono Custom HttpSoapClient 1.0
                //SOAPAction: "http://tempuri.org/Service/Method"
                //Content-Type: text/xml; charset=utf-8

                //content, with type and encoding, as string
                var content = new StringContent(requestBody, Encoding.UTF8, message.ContentType);

                //post
                using (var result = await client.PostAsync(address, content)) {
                    //response wrapper, to avoid passing params by ref
                    HttpClientResponse response = new HttpClientResponse();
                    response.DataStream = await result.Content.ReadAsStreamAsync();

                    response.StatusCode = result.StatusCode;

                    //content type, from result content
                    IEnumerable <string> values;
                    if (result.Content.Headers.TryGetValues("Content-Type", out values))
                    {
                        response.ContentType = values.FirstOrDefault();
                    }

                    return(response);
                }
            }
        }
		XmlWriter GetWriterForMessage (
			SoapClientMessage message, int bufferSize)
		{
			throw new NotImplementedException ();
		}
 protected virtual XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize)
 {
     XmlTextReader reader;
     Encoding encoding = (message.SoapVersion == SoapProtocolVersion.Soap12) ? RequestResponseUtils.GetEncoding2(message.ContentType) : RequestResponseUtils.GetEncoding(message.ContentType);
     if (bufferSize < 0x200)
     {
         bufferSize = 0x200;
     }
     if (encoding != null)
     {
         reader = new XmlTextReader(new StreamReader(message.Stream, encoding, true, bufferSize));
     }
     else
     {
         reader = new XmlTextReader(message.Stream);
     }
     reader.DtdProcessing = DtdProcessing.Prohibit;
     reader.Normalization = true;
     reader.XmlResolver = null;
     return reader;
 }
        object[] ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, bool asyncCall) {
            SoapClientMethod method = message.Method;

            // 


            HttpWebResponse httpResponse = response as HttpWebResponse;
            int statusCode = httpResponse != null ? (int)httpResponse.StatusCode : -1;
            if (statusCode >= 300 && statusCode != 500 && statusCode != 400)
                throw new WebException(RequestResponseUtils.CreateResponseExceptionString(httpResponse, responseStream), null, 
                    WebExceptionStatus.ProtocolError, httpResponse);

            message.Headers.Clear();
            message.SetStream(responseStream);
            message.InitExtensionStreamChain(message.initializedExtensions);

            message.SetStage(SoapMessageStage.BeforeDeserialize);
            message.ContentType = response.ContentType;
            message.ContentEncoding = response.Headers[ContentType.ContentEncoding];
            message.RunExtensions(message.initializedExtensions, false);

            if (method.oneWay && (httpResponse == null || (int)httpResponse.StatusCode != 500)) {
                return new object[0];
            }

            // this statusCode check is just so we don't repeat the contentType check we did above
            bool isSoap = ContentType.IsSoap(message.ContentType);
            if (!isSoap || (isSoap && (httpResponse != null) && (httpResponse.ContentLength == 0))) {
                // special-case 400 since we exempted it above on the off-chance it might be a soap 1.2 sender fault. 
                // based on the content-type, it looks like it's probably just a regular old 400
                if (statusCode == 400) 
                    throw new WebException(RequestResponseUtils.CreateResponseExceptionString(httpResponse, responseStream), null, 
                        WebExceptionStatus.ProtocolError, httpResponse);
                else
                    throw new InvalidOperationException(Res.GetString(Res.WebResponseContent, message.ContentType, HttpContentType) +
                                    Environment.NewLine +
                                    RequestResponseUtils.CreateResponseExceptionString(response, responseStream));
            }
            if (message.Exception != null) {
                throw message.Exception;
            }

            // perf fix: changed buffer size passed to StreamReader
            int bufferSize;
            if (asyncCall || httpResponse == null)
                bufferSize = 512;
            else {
                bufferSize = RequestResponseUtils.GetBufferSize((int)httpResponse.ContentLength);
            }
            XmlReader reader = GetReaderForMessage(message, bufferSize);
            if (reader == null)
                throw new InvalidOperationException(Res.GetString(Res.WebNullReaderForMessage));

            reader.MoveToContent();
            int depth = reader.Depth;

            // should be able to handle no ns, soap 1.1 ns, or soap 1.2 ns
            string encodingNs = EncodingNs;
            string envelopeNs = reader.NamespaceURI;

            if (envelopeNs == null || envelopeNs.Length == 0)
                // ok to omit namespace -- assume correct version
                reader.ReadStartElement(Soap.Element.Envelope);
            else if (reader.NamespaceURI == Soap.Namespace)
                reader.ReadStartElement(Soap.Element.Envelope, Soap.Namespace);
            else if (reader.NamespaceURI == Soap12.Namespace)
                reader.ReadStartElement(Soap.Element.Envelope, Soap12.Namespace);
            else
                throw new SoapException(Res.GetString(Res.WebInvalidEnvelopeNamespace, envelopeNs, EnvelopeNs), SoapException.VersionMismatchFaultCode);

            reader.MoveToContent();
            SoapHeaderHandling headerHandler = new SoapHeaderHandling();
            headerHandler.ReadHeaders(reader, method.outHeaderSerializer, message.Headers, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, envelopeNs, method.use == SoapBindingUse.Encoded ? encodingNs : null, false);
            reader.MoveToContent();
            reader.ReadStartElement(Soap.Element.Body, envelopeNs);
            reader.MoveToContent();
            if (reader.IsStartElement(Soap.Element.Fault, envelopeNs)) {
                message.Exception = ReadSoapException(reader);
            } 
            else {
                if (method.oneWay) {
                    reader.Skip();
                    message.SetParameterValues(new object[0]);
                }
                else {
                    TraceMethod caller = Tracing.On ? new TraceMethod(this, "ReadResponse") : null;
                    bool isEncodedSoap = method.use == SoapBindingUse.Encoded;
                    if (Tracing.On) Tracing.Enter(Tracing.TraceId(Res.TraceReadResponse), caller, new TraceMethod(method.returnSerializer, "Deserialize", reader, isEncodedSoap ? encodingNs : null));

                    bool useDeserializationEvents = !isEncodedSoap && (WebServicesSection.Current.SoapEnvelopeProcessing.IsStrict || Tracing.On);
                    if (useDeserializationEvents) {
                        XmlDeserializationEvents events = Tracing.On ? Tracing.GetDeserializationEvents() : RuntimeUtils.GetDeserializationEvents();
                        message.SetParameterValues((object[])method.returnSerializer.Deserialize(reader, null, events));
                    }
                    else {
                        message.SetParameterValues((object[])method.returnSerializer.Deserialize(reader, isEncodedSoap ? encodingNs : null));
                    }

                    if (Tracing.On) Tracing.Exit(Tracing.TraceId(Res.TraceReadResponse), caller);
                }
            }

            // Consume soap:Body and soap:Envelope closing tags
            while (depth < reader.Depth && reader.Read()) {
                // Nothing, just read on
            }
            // consume end tag
            if (reader.NodeType == XmlNodeType.EndElement) {
                reader.Read();
            }

            message.SetStage(SoapMessageStage.AfterDeserialize);
            message.RunExtensions(message.initializedExtensions, false);
            SoapHeaderHandling.SetHeaderMembers(message.Headers, this, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, true);

            if (message.Exception != null) throw message.Exception;
            return message.GetParameterValues();        
        }
 private void Serialize(SoapClientMessage message)
 {
   Stream stream = message.Stream;
   SoapClientMethod method = message.Method;
   bool isEncoded = method.use == SoapBindingUse.Encoded;
   string envelopeNs = this.EnvelopeNs;
   string encodingNs = this.EncodingNs;
   XmlWriter writerForMessage = this.GetWriterForMessage(message, 1024);
   if (writerForMessage == null)
     throw new InvalidOperationException(System.Web.Services.Res.GetString("WebNullWriterForMessage"));
   writerForMessage.WriteStartDocument();
   writerForMessage.WriteStartElement("soap", "Envelope", envelopeNs);
   writerForMessage.WriteAttributeString("xmlns", "soap", (string) null, envelopeNs);
   if (isEncoded)
   {
     writerForMessage.WriteAttributeString("xmlns", "soapenc", (string) null, encodingNs);
     writerForMessage.WriteAttributeString("xmlns", "tns", (string) null, this.clientType.serviceNamespace);
     writerForMessage.WriteAttributeString("xmlns", "types", (string) null, SoapReflector.GetEncodedNamespace(this.clientType.serviceNamespace, this.clientType.serviceDefaultIsEncoded));
   }
   writerForMessage.WriteAttributeString("xmlns", "xsi", (string) null, "http://www.w3.org/2001/XMLSchema-instance");
   writerForMessage.WriteAttributeString("xmlns", "xsd", (string) null, "http://www.w3.org/2001/XMLSchema");
   SoapHeaderHandling.WriteHeaders(writerForMessage, method.inHeaderSerializer, message.Headers, method.inHeaderMappings, SoapHeaderDirection.In, isEncoded, this.clientType.serviceNamespace, this.clientType.serviceDefaultIsEncoded, envelopeNs);
   writerForMessage.WriteStartElement("Body", envelopeNs);
   if (isEncoded && this.version != SoapProtocolVersion.Soap12)
     writerForMessage.WriteAttributeString("soap", "encodingStyle", (string) null, encodingNs);
   object[] parameterValues = message.GetParameterValues();
   TraceMethod caller = Tracing.On ? new TraceMethod((object) this, "Serialize", new object[0]) : (TraceMethod) null;
   if (Tracing.On)
     Tracing.Enter(Tracing.TraceId("TraceWriteRequest"), caller, new TraceMethod((object) method.parameterSerializer, "Serialize", new object[4]
     {
       (object) writerForMessage,
       (object) parameterValues,
       null,
       isEncoded ? (object) encodingNs : (object) (string) null
     }));
   method.parameterSerializer.Serialize(writerForMessage, (object) parameterValues, (XmlSerializerNamespaces) null, isEncoded ? encodingNs : (string) null);
   if (Tracing.On)
     Tracing.Exit(Tracing.TraceId("TraceWriteRequest"), caller);
   writerForMessage.WriteEndElement();
   writerForMessage.WriteEndElement();
   writerForMessage.Flush();
   message.SetStage(SoapMessageStage.AfterSerialize);
   message.RunExtensions(message.initializedExtensions, true);
 }
 private object[] ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, bool asyncCall)
 {
   SoapClientMethod method = message.Method;
   HttpWebResponse httpWebResponse = response as HttpWebResponse;
   int num1 = httpWebResponse != null ? (int) httpWebResponse.StatusCode : -1;
   if (num1 >= 300 && num1 != 500 && num1 != 400)
     throw new WebException(RequestResponseUtils.CreateResponseExceptionString((WebResponse) httpWebResponse, responseStream), (Exception) null, WebExceptionStatus.ProtocolError, (WebResponse) httpWebResponse);
   message.Headers.Clear();
   message.SetStream(responseStream);
   message.InitExtensionStreamChain(message.initializedExtensions);
   message.SetStage(SoapMessageStage.BeforeDeserialize);
   message.ContentType = response.ContentType;
   message.ContentEncoding = ((NameValueCollection) response.Headers)["Content-Encoding"];
   message.RunExtensions(message.initializedExtensions, false);
   if (method.oneWay && (httpWebResponse == null || httpWebResponse.StatusCode != HttpStatusCode.InternalServerError))
     return new object[0];
   bool flag1 = ContentType.IsSoap(message.ContentType);
   if (!flag1 || flag1 && httpWebResponse != null && httpWebResponse.ContentLength == 0L)
   {
     if (num1 == 400)
       throw new WebException(RequestResponseUtils.CreateResponseExceptionString((WebResponse) httpWebResponse, responseStream), (Exception) null, WebExceptionStatus.ProtocolError, (WebResponse) httpWebResponse);
     throw new InvalidOperationException(System.Web.Services.Res.GetString("WebResponseContent", (object) message.ContentType, (object) this.HttpContentType) + Environment.NewLine + RequestResponseUtils.CreateResponseExceptionString(response, responseStream));
   }
   else
   {
     if (message.Exception != null)
       throw message.Exception;
     int bufferSize = asyncCall || httpWebResponse == null ? 512 : RequestResponseUtils.GetBufferSize((int) httpWebResponse.ContentLength);
     XmlReader readerForMessage = this.GetReaderForMessage(message, bufferSize);
     if (readerForMessage == null)
       throw new InvalidOperationException(System.Web.Services.Res.GetString("WebNullReaderForMessage"));
     int num2 = (int) readerForMessage.MoveToContent();
     int depth = readerForMessage.Depth;
     string encodingNs = this.EncodingNs;
     string namespaceUri = readerForMessage.NamespaceURI;
     if (namespaceUri == null || namespaceUri.Length == 0)
       readerForMessage.ReadStartElement("Envelope");
     else if (readerForMessage.NamespaceURI == "http://schemas.xmlsoap.org/soap/envelope/")
       readerForMessage.ReadStartElement("Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
     else if (readerForMessage.NamespaceURI == "http://www.w3.org/2003/05/soap-envelope")
       readerForMessage.ReadStartElement("Envelope", "http://www.w3.org/2003/05/soap-envelope");
     else
       throw new SoapException(System.Web.Services.Res.GetString("WebInvalidEnvelopeNamespace", (object) namespaceUri, (object) this.EnvelopeNs), SoapException.VersionMismatchFaultCode);
     int num3 = (int) readerForMessage.MoveToContent();
     new SoapHeaderHandling().ReadHeaders(readerForMessage, method.outHeaderSerializer, message.Headers, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, namespaceUri, method.use == SoapBindingUse.Encoded ? encodingNs : (string) null, false);
     int num4 = (int) readerForMessage.MoveToContent();
     readerForMessage.ReadStartElement("Body", namespaceUri);
     int num5 = (int) readerForMessage.MoveToContent();
     if (readerForMessage.IsStartElement("Fault", namespaceUri))
       message.Exception = this.ReadSoapException(readerForMessage);
     else if (method.oneWay)
     {
       readerForMessage.Skip();
       message.SetParameterValues(new object[0]);
     }
     else
     {
       TraceMethod caller = Tracing.On ? new TraceMethod((object) this, "ReadResponse", new object[0]) : (TraceMethod) null;
       bool flag2 = method.use == SoapBindingUse.Encoded;
       if (Tracing.On)
         Tracing.Enter(Tracing.TraceId("TraceReadResponse"), caller, new TraceMethod((object) method.returnSerializer, "Deserialize", new object[2]
         {
           (object) readerForMessage,
           flag2 ? (object) encodingNs : (object) (string) null
         }));
       if (!flag2 && (WebServicesSection.Current.SoapEnvelopeProcessing.IsStrict || Tracing.On))
       {
         XmlDeserializationEvents events = Tracing.On ? Tracing.GetDeserializationEvents() : RuntimeUtils.GetDeserializationEvents();
         message.SetParameterValues((object[]) method.returnSerializer.Deserialize(readerForMessage, (string) null, events));
       }
       else
         message.SetParameterValues((object[]) method.returnSerializer.Deserialize(readerForMessage, flag2 ? encodingNs : (string) null));
       if (Tracing.On)
         Tracing.Exit(Tracing.TraceId("TraceReadResponse"), caller);
     }
     do
       ;
     while (depth < readerForMessage.Depth && readerForMessage.Read());
     if (readerForMessage.NodeType == XmlNodeType.EndElement)
       readerForMessage.Read();
     message.SetStage(SoapMessageStage.AfterDeserialize);
     message.RunExtensions(message.initializedExtensions, false);
     SoapHeaderHandling.SetHeaderMembers(message.Headers, (object) this, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, true);
     if (message.Exception != null)
       throw message.Exception;
     else
       return message.GetParameterValues();
   }
 }
 private object[] ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, bool asyncCall)
 {
     int bufferSize;
     SoapClientMethod method = message.Method;
     HttpWebResponse response2 = response as HttpWebResponse;
     int num = (response2 != null) ? ((int) response2.StatusCode) : -1;
     if (((num >= 300) && (num != 500)) && (num != 400))
     {
         throw new WebException(RequestResponseUtils.CreateResponseExceptionString(response2, responseStream), null, WebExceptionStatus.ProtocolError, response2);
     }
     message.Headers.Clear();
     message.SetStream(responseStream);
     message.InitExtensionStreamChain(message.initializedExtensions);
     message.SetStage(SoapMessageStage.BeforeDeserialize);
     message.ContentType = response.ContentType;
     message.ContentEncoding = response.Headers["Content-Encoding"];
     message.RunExtensions(message.initializedExtensions, false);
     if (method.oneWay && ((response2 == null) || (response2.StatusCode != HttpStatusCode.InternalServerError)))
     {
         return new object[0];
     }
     bool flag = ContentType.IsSoap(message.ContentType);
     if (!flag || ((flag && (response2 != null)) && (response2.ContentLength == 0L)))
     {
         if (num == 400)
         {
             throw new WebException(RequestResponseUtils.CreateResponseExceptionString(response2, responseStream), null, WebExceptionStatus.ProtocolError, response2);
         }
         throw new InvalidOperationException(System.Web.Services.Res.GetString("WebResponseContent", new object[] { message.ContentType, this.HttpContentType }) + Environment.NewLine + RequestResponseUtils.CreateResponseExceptionString(response, responseStream));
     }
     if (message.Exception != null)
     {
         throw message.Exception;
     }
     if (asyncCall || (response2 == null))
     {
         bufferSize = 0x200;
     }
     else
     {
         bufferSize = RequestResponseUtils.GetBufferSize((int) response2.ContentLength);
     }
     XmlReader readerForMessage = this.GetReaderForMessage(message, bufferSize);
     if (readerForMessage == null)
     {
         throw new InvalidOperationException(System.Web.Services.Res.GetString("WebNullReaderForMessage"));
     }
     readerForMessage.MoveToContent();
     int depth = readerForMessage.Depth;
     string encodingNs = this.EncodingNs;
     string namespaceURI = readerForMessage.NamespaceURI;
     if ((namespaceURI == null) || (namespaceURI.Length == 0))
     {
         readerForMessage.ReadStartElement("Envelope");
     }
     else if (readerForMessage.NamespaceURI == "http://schemas.xmlsoap.org/soap/envelope/")
     {
         readerForMessage.ReadStartElement("Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
     }
     else
     {
         if (readerForMessage.NamespaceURI != "http://www.w3.org/2003/05/soap-envelope")
         {
             throw new SoapException(System.Web.Services.Res.GetString("WebInvalidEnvelopeNamespace", new object[] { namespaceURI, this.EnvelopeNs }), SoapException.VersionMismatchFaultCode);
         }
         readerForMessage.ReadStartElement("Envelope", "http://www.w3.org/2003/05/soap-envelope");
     }
     readerForMessage.MoveToContent();
     new SoapHeaderHandling().ReadHeaders(readerForMessage, method.outHeaderSerializer, message.Headers, method.outHeaderMappings, SoapHeaderDirection.Fault | SoapHeaderDirection.Out, namespaceURI, (method.use == SoapBindingUse.Encoded) ? encodingNs : null, false);
     readerForMessage.MoveToContent();
     readerForMessage.ReadStartElement("Body", namespaceURI);
     readerForMessage.MoveToContent();
     if (readerForMessage.IsStartElement("Fault", namespaceURI))
     {
         message.Exception = this.ReadSoapException(readerForMessage);
     }
     else if (method.oneWay)
     {
         readerForMessage.Skip();
         message.SetParameterValues(new object[0]);
     }
     else
     {
         TraceMethod caller = Tracing.On ? new TraceMethod(this, "ReadResponse", new object[0]) : null;
         bool flag2 = method.use == SoapBindingUse.Encoded;
         if (Tracing.On)
         {
             Tracing.Enter(Tracing.TraceId("TraceReadResponse"), caller, new TraceMethod(method.returnSerializer, "Deserialize", new object[] { readerForMessage, flag2 ? encodingNs : null }));
         }
         if (!flag2 && (WebServicesSection.Current.SoapEnvelopeProcessing.IsStrict || Tracing.On))
         {
             XmlDeserializationEvents events = Tracing.On ? Tracing.GetDeserializationEvents() : RuntimeUtils.GetDeserializationEvents();
             message.SetParameterValues((object[]) method.returnSerializer.Deserialize(readerForMessage, null, events));
         }
         else
         {
             message.SetParameterValues((object[]) method.returnSerializer.Deserialize(readerForMessage, flag2 ? encodingNs : null));
         }
         if (Tracing.On)
         {
             Tracing.Exit(Tracing.TraceId("TraceReadResponse"), caller);
         }
     }
     while ((depth < readerForMessage.Depth) && readerForMessage.Read())
     {
     }
     if (readerForMessage.NodeType == XmlNodeType.EndElement)
     {
         readerForMessage.Read();
     }
     message.SetStage(SoapMessageStage.AfterDeserialize);
     message.RunExtensions(message.initializedExtensions, false);
     SoapHeaderHandling.SetHeaderMembers(message.Headers, this, method.outHeaderMappings, SoapHeaderDirection.Fault | SoapHeaderDirection.Out, true);
     if (message.Exception != null)
     {
         throw message.Exception;
     }
     return message.GetParameterValues();
 }
        protected override XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize)
        {
            string xmlMatchSchema = "<?xml";
            string xmlSchema = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
            int schemaLength = Encoding.UTF8.GetByteCount(xmlMatchSchema);
            Stream messageStream = message.Stream;
            byte[] schemaArray = new byte[schemaLength];

            if (messageStream.CanSeek)
            {
                long originalPosition = messageStream.Position;

                messageStream.Seek(0, SeekOrigin.Begin);
                int bytesRead = messageStream.Read(schemaArray, 0, schemaArray.Length);

                string readSchema = Encoding.UTF8.GetString(schemaArray);
                if (readSchema.ToLowerInvariant() != xmlMatchSchema.ToLowerInvariant())
                {
                    messageStream.Seek(0, SeekOrigin.Begin);
                    byte[] content = new byte[messageStream.Length];
                    messageStream.Read(content, 0, content.Length);
                    messageStream.Seek(0, SeekOrigin.Begin);

                    string strContent = Encoding.UTF8.GetString(content);

                    MemoryStream newMemStream = new MemoryStream();
                    newMemStream.Seek(0, SeekOrigin.Begin);
                    newMemStream.Write(Encoding.UTF8.GetBytes(xmlSchema), 0, Encoding.UTF8.GetByteCount(xmlSchema));
                    newMemStream.Write(content, 0, content.Length);
                    newMemStream.Seek(0, SeekOrigin.Begin);

                    XmlTextReader reader = null;
                    Encoding encoding = (message.SoapVersion == SoapProtocolVersion.Soap12) ? RequestResponseUtils.GetEncoding2(message.ContentType) : RequestResponseUtils.GetEncoding(message.ContentType);
                    if (bufferSize < 0x200)
                    {
                        bufferSize = 0x200;
                    }

                    if (encoding != null)
                    {
                        reader = new XmlTextReader(new StreamReader(message.Stream, encoding, true, bufferSize));
                    }
                    else
                    {
                        reader = new XmlTextReader(message.Stream);
                    }
                    reader.ProhibitDtd = true;
                    reader.Normalization = true;
                    reader.XmlResolver = null;
                    return reader;
                }
                else
                {
                    messageStream.Seek(originalPosition, SeekOrigin.Begin);
                    return base.GetReaderForMessage(message, bufferSize);
                }
            }
            else
            {
                Trace.WriteLineIf(Settings.TraceSwitch.TraceWarning, "Unseekable stream returned with message, maybe the connection has terminated. Stream type: " + message.Stream.GetType().ToString());
                return base.GetReaderForMessage(message, bufferSize);
            }
        }
Beispiel #36
0
        private object[] ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, bool asyncCall)
        {
            SoapClientMethod method          = message.Method;
            HttpWebResponse  httpWebResponse = response as HttpWebResponse;
            int num1 = httpWebResponse != null ? (int)httpWebResponse.StatusCode : -1;

            if (num1 >= 300 && num1 != 500 && num1 != 400)
            {
                throw new WebException(RequestResponseUtils.CreateResponseExceptionString((WebResponse)httpWebResponse, responseStream), (Exception)null, WebExceptionStatus.ProtocolError, (WebResponse)httpWebResponse);
            }
            message.Headers.Clear();
            message.SetStream(responseStream);
            message.InitExtensionStreamChain(message.initializedExtensions);
            message.SetStage(SoapMessageStage.BeforeDeserialize);
            message.ContentType     = response.ContentType;
            message.ContentEncoding = ((NameValueCollection)response.Headers)["Content-Encoding"];
            message.RunExtensions(message.initializedExtensions, false);
            if (method.oneWay && (httpWebResponse == null || httpWebResponse.StatusCode != HttpStatusCode.InternalServerError))
            {
                return(new object[0]);
            }
            bool flag1 = ContentType.IsSoap(message.ContentType);

            if (!flag1 || flag1 && httpWebResponse != null && httpWebResponse.ContentLength == 0L)
            {
                if (num1 == 400)
                {
                    throw new WebException(RequestResponseUtils.CreateResponseExceptionString((WebResponse)httpWebResponse, responseStream), (Exception)null, WebExceptionStatus.ProtocolError, (WebResponse)httpWebResponse);
                }
                throw new InvalidOperationException(System.Web.Services.Res.GetString("WebResponseContent", (object)message.ContentType, (object)this.HttpContentType) + Environment.NewLine + RequestResponseUtils.CreateResponseExceptionString(response, responseStream));
            }
            else
            {
                if (message.Exception != null)
                {
                    throw message.Exception;
                }
                int       bufferSize       = asyncCall || httpWebResponse == null ? 512 : RequestResponseUtils.GetBufferSize((int)httpWebResponse.ContentLength);
                XmlReader readerForMessage = this.GetReaderForMessage(message, bufferSize);
                if (readerForMessage == null)
                {
                    throw new InvalidOperationException(System.Web.Services.Res.GetString("WebNullReaderForMessage"));
                }
                int    num2         = (int)readerForMessage.MoveToContent();
                int    depth        = readerForMessage.Depth;
                string encodingNs   = this.EncodingNs;
                string namespaceUri = readerForMessage.NamespaceURI;
                if (namespaceUri == null || namespaceUri.Length == 0)
                {
                    readerForMessage.ReadStartElement("Envelope");
                }
                else if (readerForMessage.NamespaceURI == "http://schemas.xmlsoap.org/soap/envelope/")
                {
                    readerForMessage.ReadStartElement("Envelope", "http://schemas.xmlsoap.org/soap/envelope/");
                }
                else if (readerForMessage.NamespaceURI == "http://www.w3.org/2003/05/soap-envelope")
                {
                    readerForMessage.ReadStartElement("Envelope", "http://www.w3.org/2003/05/soap-envelope");
                }
                else
                {
                    throw new SoapException(System.Web.Services.Res.GetString("WebInvalidEnvelopeNamespace", (object)namespaceUri, (object)this.EnvelopeNs), SoapException.VersionMismatchFaultCode);
                }
                int num3 = (int)readerForMessage.MoveToContent();
                new SoapHeaderHandling().ReadHeaders(readerForMessage, method.outHeaderSerializer, message.Headers, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, namespaceUri, method.use == SoapBindingUse.Encoded ? encodingNs : (string)null, false);
                int num4 = (int)readerForMessage.MoveToContent();
                readerForMessage.ReadStartElement("Body", namespaceUri);
                int num5 = (int)readerForMessage.MoveToContent();
                if (readerForMessage.IsStartElement("Fault", namespaceUri))
                {
                    message.Exception = this.ReadSoapException(readerForMessage);
                }
                else if (method.oneWay)
                {
                    readerForMessage.Skip();
                    message.SetParameterValues(new object[0]);
                }
                else
                {
                    TraceMethod caller = Tracing.On ? new TraceMethod((object)this, "ReadResponse", new object[0]) : (TraceMethod)null;
                    bool        flag2  = method.use == SoapBindingUse.Encoded;
                    if (Tracing.On)
                    {
                        Tracing.Enter(Tracing.TraceId("TraceReadResponse"), caller, new TraceMethod((object)method.returnSerializer, "Deserialize", new object[2]
                        {
                            (object)readerForMessage,
                            flag2 ? (object)encodingNs : (object)(string)null
                        }));
                    }
                    if (!flag2 && (WebServicesSection.Current.SoapEnvelopeProcessing.IsStrict || Tracing.On))
                    {
                        XmlDeserializationEvents events = Tracing.On ? Tracing.GetDeserializationEvents() : RuntimeUtils.GetDeserializationEvents();
                        message.SetParameterValues((object[])method.returnSerializer.Deserialize(readerForMessage, (string)null, events));
                    }
                    else
                    {
                        message.SetParameterValues((object[])method.returnSerializer.Deserialize(readerForMessage, flag2 ? encodingNs : (string)null));
                    }
                    if (Tracing.On)
                    {
                        Tracing.Exit(Tracing.TraceId("TraceReadResponse"), caller);
                    }
                }
                do
                {
                    ;
                }while (depth < readerForMessage.Depth && readerForMessage.Read());
                if (readerForMessage.NodeType == XmlNodeType.EndElement)
                {
                    readerForMessage.Read();
                }
                message.SetStage(SoapMessageStage.AfterDeserialize);
                message.RunExtensions(message.initializedExtensions, false);
                SoapHeaderHandling.SetHeaderMembers(message.Headers, (object)this, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, true);
                if (message.Exception != null)
                {
                    throw message.Exception;
                }
                else
                {
                    return(message.GetParameterValues());
                }
            }
        }
Beispiel #37
0
        public object[] ReceiveResponse(WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
        {
            StreamReader sr = new StreamReader(response.GetResponseStream());
            String content = sr.ReadToEnd();
            System.Console.WriteLine(content);

            return null;
        }
        SoapClientMessage BeforeSerialize(WebRequest request, string methodName, object[] parameters) {
            if (parameters == null) throw new ArgumentNullException("parameters");
            SoapClientMethod method = clientType.GetMethod(methodName);
            if (method == null) throw new ArgumentException(Res.GetString(Res.WebInvalidMethodName, methodName));            

            // Run BeforeSerialize extension pass. Extensions are not allowed
            // to write into the stream during this pass.
            SoapReflectedExtension[] allExtensions = (SoapReflectedExtension[])CombineExtensionsHelper(clientType.HighPriExtensions, method.extensions, clientType.LowPriExtensions, typeof(SoapReflectedExtension));
            object[] allExtensionInitializers = (object[])CombineExtensionsHelper(clientType.HighPriExtensionInitializers, method.extensionInitializers, clientType.LowPriExtensionInitializers, typeof(object));
            SoapExtension[] initializedExtensions = SoapMessage.InitializeExtensions(allExtensions, allExtensionInitializers);
            SoapClientMessage message = new SoapClientMessage(this, method, Url);
            message.initializedExtensions = initializedExtensions;
            if (initializedExtensions != null)
                message.SetExtensionStream(new SoapExtensionStream());
            message.InitExtensionStreamChain(message.initializedExtensions);            

            string soapAction = UrlEncoder.EscapeString(method.action, Encoding.UTF8);
            message.SetStage(SoapMessageStage.BeforeSerialize);
            if (this.version == SoapProtocolVersion.Soap12)
                message.ContentType = ContentType.Compose(ContentType.ApplicationSoap, RequestEncoding != null ? RequestEncoding : Encoding.UTF8, soapAction);
            else
                message.ContentType = ContentType.Compose(ContentType.TextXml, RequestEncoding != null ? RequestEncoding : Encoding.UTF8);
            message.SetParameterValues(parameters);
            SoapHeaderHandling.GetHeaderMembers(message.Headers, this, method.inHeaderMappings, SoapHeaderDirection.In, true);
            message.RunExtensions(message.initializedExtensions, true);

            // Last chance to set request headers            
            request.ContentType = message.ContentType;
            if (message.ContentEncoding != null && message.ContentEncoding.Length > 0)
                request.Headers[ContentType.ContentEncoding] = message.ContentEncoding;

            request.Method = "POST";
            if (this.version != SoapProtocolVersion.Soap12 && request.Headers[Soap.Action] == null) {
                StringBuilder actionStringBuilder = new StringBuilder(soapAction.Length + 2);            
                actionStringBuilder.Append('"');
                actionStringBuilder.Append(soapAction);
                actionStringBuilder.Append('"');
                request.Headers.Add(Soap.Action, actionStringBuilder.ToString());                
            }

            return message;
        }
        void Serialize(SoapClientMessage message) {
            Stream stream = message.Stream;            
            SoapClientMethod method = message.Method;
            bool isEncoded = method.use == SoapBindingUse.Encoded;

            // Serialize the message.  
            string envelopeNs = EnvelopeNs;
            string encodingNs = EncodingNs;

            XmlWriter writer = GetWriterForMessage(message, 1024);
            if (writer == null)
                throw new InvalidOperationException(Res.GetString(Res.WebNullWriterForMessage));

            writer.WriteStartDocument();
            writer.WriteStartElement(Soap.Prefix, Soap.Element.Envelope, envelopeNs);
            writer.WriteAttributeString("xmlns", Soap.Prefix, null, envelopeNs);
            if (isEncoded) {
                writer.WriteAttributeString("xmlns", "soapenc", null, encodingNs);
                writer.WriteAttributeString("xmlns", "tns", null, clientType.serviceNamespace);
                writer.WriteAttributeString("xmlns", "types", null, SoapReflector.GetEncodedNamespace(clientType.serviceNamespace, clientType.serviceDefaultIsEncoded));
            }
            writer.WriteAttributeString("xmlns", "xsi", null, XmlSchema.InstanceNamespace);
            writer.WriteAttributeString("xmlns", "xsd", null, XmlSchema.Namespace);
            SoapHeaderHandling.WriteHeaders(writer, method.inHeaderSerializer, message.Headers, method.inHeaderMappings, SoapHeaderDirection.In, isEncoded, clientType.serviceNamespace, clientType.serviceDefaultIsEncoded, envelopeNs);
            writer.WriteStartElement(Soap.Element.Body, envelopeNs);
            if (isEncoded && version != SoapProtocolVersion.Soap12) // don't write encodingStyle on soap:Body for soap 1.2
                writer.WriteAttributeString("soap", Soap.Attribute.EncodingStyle, null, encodingNs);

            object[] parameters = message.GetParameterValues();
            TraceMethod caller = Tracing.On ? new TraceMethod(this, "Serialize") : null;

            if (Tracing.On) Tracing.Enter(Tracing.TraceId(Res.TraceWriteRequest), caller, new TraceMethod(method.parameterSerializer, "Serialize", writer, parameters, null, isEncoded ? encodingNs : null));
            method.parameterSerializer.Serialize(writer, parameters, null, isEncoded ? encodingNs : null);
            if (Tracing.On) Tracing.Exit(Tracing.TraceId(Res.TraceWriteRequest), caller);

            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.Flush();

            // run the after serialize extension pass. 
            message.SetStage(SoapMessageStage.AfterSerialize);
            message.RunExtensions(message.initializedExtensions, true);
        }
		void SendRequest (Stream s, SoapClientMessage message, SoapExtension[] extensions)
		{
			using (s) {

				if (extensions != null) {
					s = SoapExtension.ExecuteChainStream (extensions, s);
					message.SetStage (SoapMessageStage.BeforeSerialize);
					SoapExtension.ExecuteProcessMessage (extensions, message, true);
				}

				XmlTextWriter xtw = WebServiceHelper.CreateXmlWriter (s);
				
				WebServiceHelper.WriteSoapMessage (xtw, type_info, message.MethodStubInfo.Use, message.MethodStubInfo.RequestSerializer, message.Parameters, message.Headers);

				if (extensions != null) {
					message.SetStage (SoapMessageStage.AfterSerialize);
					SoapExtension.ExecuteProcessMessage (extensions, message, true);
				}

				xtw.Flush ();
				xtw.Close ();
			 }
		}
Beispiel #41
0
 XmlWriter GetWriterForMessage(
     SoapClientMessage message, int bufferSize)
 {
     throw new NotImplementedException();
 }
		protected object[] Invoke (string method_name, object[] parameters)
		{
			SoapMethodStubInfo msi = (SoapMethodStubInfo) type_info.GetMethod (method_name);
			
			SoapClientMessage message = new SoapClientMessage (this, msi, Url, parameters);
			message.CollectHeaders (this, message.MethodStubInfo.Headers, SoapHeaderDirection.In);

			SoapExtension[] extensions = SoapExtension.CreateExtensionChain (type_info.SoapExtensions[0], msi.SoapExtensions, type_info.SoapExtensions[1]);

			WebResponse response;
			try
			{
				WebRequest request = GetRequestForMessage (uri, message);
				SendRequest (request.GetRequestStream (), message, extensions);
				response = GetWebResponse (request);
			}
			catch (WebException ex)
			{
				response = ex.Response;
				HttpWebResponse http_response = response as HttpWebResponse;
				if (http_response == null || http_response.StatusCode != HttpStatusCode.InternalServerError)
					throw ex;
			}

			try {
				return ReceiveResponse (response, message, extensions);
			}
			finally {
				response.Close();
			}
		}
Beispiel #43
0
        //
        // TODO:
        //    Handle other web responses (multi-output?)
        //
        object [] ReceiveResponse(WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
        {
            SoapMethodStubInfo msi           = message.MethodStubInfo;
            HttpWebResponse    http_response = response as HttpWebResponse;

            if (http_response != null)
            {
                HttpStatusCode code = http_response.StatusCode;

                if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError))
                {
                    string msg = "The request failed with HTTP status {0}: {1}";
                    msg = String.Format(msg, (int)code, code);
                    throw new WebException(msg, null, WebExceptionStatus.ProtocolError, http_response);
                }
                if (message.OneWay && response.ContentLength <= 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK))
                {
                    return(new object[0]);
                }
            }

            //
            // Remove optional encoding
            //
            string   ctype;
            Encoding encoding = WebServiceHelper.GetContentEncoding(response.ContentType, out ctype);

            ctype = ctype.ToLower(CultureInfo.InvariantCulture);
            if ((!message.IsSoap12 || ctype != "application/soap+xml") && ctype != "text/xml")
            {
                WebServiceHelper.InvalidOperation(
                    String.Format("Not supported Content-Type in the response: '{0}'", response.ContentType),
                    response, encoding);
            }

            message.ContentType     = ctype;
            message.ContentEncoding = encoding.WebName;

            Stream stream = response.GetResponseStream();

            if (extensions != null)
            {
                stream = SoapExtension.ExecuteChainStream(extensions, stream);
                message.SetStage(SoapMessageStage.BeforeDeserialize);
                SoapExtension.ExecuteProcessMessage(extensions, message, stream, false);
            }

            // Deserialize the response

            SoapHeaderCollection headers;
            object content;

            using (StreamReader reader = new StreamReader(stream, encoding, false)) {
                XmlTextReader xml_reader = new XmlTextReader(reader);

                WebServiceHelper.ReadSoapMessage(xml_reader, msi, SoapHeaderDirection.Out, message.IsSoap12, out content, out headers);
            }

            if (content is Soap12Fault)
            {
                SoapException ex = WebServiceHelper.Soap12FaultToSoapException((Soap12Fault)content);
                message.SetException(ex);
            }
            else
            if (content is Fault)
            {
                Fault         fault = (Fault)content;
                SoapException ex    = new SoapException(fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
                message.SetException(ex);
            }
            else
            {
                message.OutParameters = (object[])content;
            }

            message.SetHeaders(headers);
            message.UpdateHeaderValues(this, message.MethodStubInfo.Headers);

            if (extensions != null)
            {
                message.SetStage(SoapMessageStage.AfterDeserialize);
                SoapExtension.ExecuteProcessMessage(extensions, message, stream, false);
            }

            if (message.Exception == null)
            {
                return(message.OutParameters);
            }
            else
            {
                throw message.Exception;
            }
        }
 protected virtual XmlReader GetReaderForMessage(SoapClientMessage message, int bufferSize)
 {
   Encoding encoding = message.SoapVersion == SoapProtocolVersion.Soap12 ? RequestResponseUtils.GetEncoding2(message.ContentType) : RequestResponseUtils.GetEncoding(message.ContentType);
   if (bufferSize < 512)
     bufferSize = 512;
   XmlTextReader xmlTextReader = encoding == null ? new XmlTextReader(message.Stream) : new XmlTextReader((TextReader) new StreamReader(message.Stream, encoding, true, bufferSize));
   xmlTextReader.DtdProcessing = DtdProcessing.Prohibit;
   xmlTextReader.Normalization = true;
   xmlTextReader.XmlResolver = (XmlResolver) null;
   return (XmlReader) xmlTextReader;
 }
 private SoapClientMessage BeforeSerialize(WebRequest request, string methodName, object[] parameters)
 {
   if (parameters == null)
     throw new ArgumentNullException("parameters");
   SoapClientMethod method = this.clientType.GetMethod(methodName);
   if (method == null)
   {
     throw new ArgumentException(System.Web.Services.Res.GetString("WebInvalidMethodName", new object[1]
     {
       (object) methodName
     }));
   }
   else
   {
     SoapExtension[] soapExtensionArray = SoapMessage.InitializeExtensions((SoapReflectedExtension[]) SoapHttpClientProtocol.CombineExtensionsHelper((Array) this.clientType.HighPriExtensions, (Array) method.extensions, (Array) this.clientType.LowPriExtensions, typeof (SoapReflectedExtension)), (object[]) SoapHttpClientProtocol.CombineExtensionsHelper((Array) this.clientType.HighPriExtensionInitializers, (Array) method.extensionInitializers, (Array) this.clientType.LowPriExtensionInitializers, typeof (object)));
     SoapClientMessage soapClientMessage = new SoapClientMessage(this, method, this.Url);
     soapClientMessage.initializedExtensions = soapExtensionArray;
     if (soapExtensionArray != null)
       soapClientMessage.SetExtensionStream(new SoapExtensionStream());
     soapClientMessage.InitExtensionStreamChain(soapClientMessage.initializedExtensions);
     string action = UrlEncoder.EscapeString(method.action, Encoding.UTF8);
     soapClientMessage.SetStage(SoapMessageStage.BeforeSerialize);
     if (this.version == SoapProtocolVersion.Soap12)
       soapClientMessage.ContentType = ContentType.Compose("application/soap+xml", this.RequestEncoding != null ? this.RequestEncoding : Encoding.UTF8, action);
     else
       soapClientMessage.ContentType = ContentType.Compose("text/xml", this.RequestEncoding != null ? this.RequestEncoding : Encoding.UTF8);
     soapClientMessage.SetParameterValues(parameters);
     SoapHeaderHandling.GetHeaderMembers(soapClientMessage.Headers, (object) this, method.inHeaderMappings, SoapHeaderDirection.In, true);
     soapClientMessage.RunExtensions(soapClientMessage.initializedExtensions, true);
     request.ContentType = soapClientMessage.ContentType;
     if (soapClientMessage.ContentEncoding != null && soapClientMessage.ContentEncoding.Length > 0)
       ((NameValueCollection) request.Headers)["Content-Encoding"] = soapClientMessage.ContentEncoding;
     request.Method = "POST";
     if (this.version != SoapProtocolVersion.Soap12 && ((NameValueCollection) request.Headers)["SOAPAction"] == null)
     {
       StringBuilder stringBuilder = new StringBuilder(action.Length + 2);
       stringBuilder.Append('"');
       stringBuilder.Append(action);
       stringBuilder.Append('"');
       ((NameValueCollection) request.Headers).Add("SOAPAction", ((object) stringBuilder).ToString());
     }
     return soapClientMessage;
   }
 }
Beispiel #46
0
        object[] ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, bool asyncCall)
        {
            SoapClientMethod method = message.Method;

            // CONSIDER,yannc: use the SoapExtensionStream here as well so we throw exceptions
            //      : if the extension touches stream properties/methods in before deserialize.
            // note that if there is an error status code then the response might be content-type=text/plain.
            HttpWebResponse httpResponse = response as HttpWebResponse;
            int             statusCode   = httpResponse != null ? (int)httpResponse.StatusCode : -1;

            if (statusCode >= 300 && statusCode != 500 && statusCode != 400)
            {
                throw new WebException(RequestResponseUtils.CreateResponseExceptionString(httpResponse, responseStream), null,
                                       WebExceptionStatus.ProtocolError, httpResponse);
            }

            message.Headers.Clear();
            message.SetStream(responseStream);
            message.InitExtensionStreamChain(message.initializedExtensions);

            message.SetStage(SoapMessageStage.BeforeDeserialize);
            message.ContentType     = response.ContentType;
            message.ContentEncoding = response.Headers[ContentType.ContentEncoding];
            message.RunExtensions(message.initializedExtensions);

            if (method.oneWay && (httpResponse == null || (int)httpResponse.StatusCode != 500))
            {
                return(new object[0]);
            }

            // this statusCode check is just so we don't repeat the contentType check we did above
            if (!ContentType.IsSoap(message.ContentType))
            {
                // special-case 400 since we exempted it above on the off-chance it might be a soap 1.2 sender fault.
                // based on the content-type, it looks like it's probably just a regular old 400
                if (statusCode == 400)
                {
                    throw new WebException(RequestResponseUtils.CreateResponseExceptionString(httpResponse, responseStream), null,
                                           WebExceptionStatus.ProtocolError, httpResponse);
                }
                else
                {
                    throw new InvalidOperationException(Res.GetString(Res.WebResponseContent, message.ContentType, HttpContentType) +
                                                        "\r\n" +
                                                        RequestResponseUtils.CreateResponseExceptionString(response, responseStream));
                }
            }

            Encoding enc = RequestResponseUtils.GetEncoding(message.ContentType);

            // perf fix: changed buffer size passed to StreamReader
            int bufferSize;

            if (asyncCall || httpResponse == null)
            {
                bufferSize = 512;
            }
            else
            {
                int contentLength = (int)httpResponse.ContentLength;
                if (contentLength == -1)
                {
                    bufferSize = 8000;
                }
                else if (contentLength <= 16000)
                {
                    bufferSize = contentLength;
                }
                else
                {
                    bufferSize = 16000;
                }
            }
            XmlTextReader reader;

            if (enc != null)
            {
                reader = new XmlTextReader(new StreamReader(message.Stream, enc, true, bufferSize));
            }
            else
            {
                // CONSIDER: do i need to pass a buffer size somehow?
                reader = new XmlTextReader(message.Stream);
            }

            reader.Normalization = true;
            reader.XmlResolver   = null;
            reader.MoveToContent();
            // should be able to handle no ns, soap 1.1 ns, or soap 1.2 ns
            string encodingNs = EncodingNs;
            string envelopeNs = reader.NamespaceURI;

            if (envelopeNs == null || envelopeNs.Length == 0)
            {
                // ok to omit namespace -- assume correct version
                reader.ReadStartElement(Soap.Envelope);
            }
            else if (reader.NamespaceURI == Soap.Namespace)
            {
                reader.ReadStartElement(Soap.Envelope, Soap.Namespace);
            }
            else if (reader.NamespaceURI == Soap12.Namespace)
            {
                reader.ReadStartElement(Soap.Envelope, Soap12.Namespace);
            }
            else
            {
                throw new SoapException(Res.GetString(Res.WebInvalidEnvelopeNamespace, envelopeNs, EnvelopeNs), SoapException.VersionMismatchFaultCode);
            }

            reader.MoveToContent();
            SoapHeaderHandling headerHandler = new SoapHeaderHandling();

            headerHandler.ReadHeaders(reader, method.outHeaderSerializer, message.Headers, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, envelopeNs, method.use == SoapBindingUse.Encoded ? encodingNs : null);
            reader.MoveToContent();
            reader.ReadStartElement(Soap.Body, envelopeNs);
            reader.MoveToContent();
            if (reader.IsStartElement(Soap.Fault, envelopeNs))
            {
                message.SetException(ReadSoapException(reader));
            }
            else
            {
                if (method.oneWay)
                {
                    reader.Skip();
                    message.SetParameterValues(new object[0]);
                }
                else
                {
                    // SOAP12: not using encodingStyle
                    //message.SetParameterValues((object[])method.returnSerializer.Deserialize(reader, method.use == SoapBindingUse.Encoded ? encodingNs : null));
                    message.SetParameterValues((object[])method.returnSerializer.Deserialize(reader));
                }
            }

            while (reader.NodeType == XmlNodeType.Whitespace)
            {
                reader.Skip();
            }
            if (reader.NodeType == XmlNodeType.None)
            {
                reader.Skip();
            }
            else
            {
                reader.ReadEndElement();
            }
            while (reader.NodeType == XmlNodeType.Whitespace)
            {
                reader.Skip();
            }
            if (reader.NodeType == XmlNodeType.None)
            {
                reader.Skip();
            }
            else
            {
                reader.ReadEndElement();
            }

            message.SetStage(SoapMessageStage.AfterDeserialize);
            message.RunExtensions(message.initializedExtensions);
            SoapHeaderHandling.SetHeaderMembers(message.Headers, this, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, true);

            if (message.Exception != null)
            {
                throw message.Exception;
            }
            return(message.GetParameterValues());
        }
		WebRequest GetRequestForMessage (Uri uri, SoapClientMessage message)
		{
			WebRequest request = GetWebRequest (uri);
			request.Method = "POST";
			WebHeaderCollection headers = request.Headers;
			headers.Add ("SOAPAction", "\"" + message.Action + "\"");
			request.ContentType = message.ContentType + "; charset=utf-8";
			return request;
		}
        object[] ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, bool asyncCall)
        {
            SoapClientMethod method = message.Method;

            //


            HttpWebResponse httpResponse = response as HttpWebResponse;
            int             statusCode   = httpResponse != null ? (int)httpResponse.StatusCode : -1;

            if (statusCode >= 300 && statusCode != 500 && statusCode != 400)
            {
                throw new WebException(RequestResponseUtils.CreateResponseExceptionString(httpResponse, responseStream), null,
                                       WebExceptionStatus.ProtocolError, httpResponse);
            }

            message.Headers.Clear();
            message.SetStream(responseStream);
            message.InitExtensionStreamChain(message.initializedExtensions);

            message.SetStage(SoapMessageStage.BeforeDeserialize);
            message.ContentType     = response.ContentType;
            message.ContentEncoding = response.Headers[ContentType.ContentEncoding];
            message.RunExtensions(message.initializedExtensions, false);

            if (method.oneWay && (httpResponse == null || (int)httpResponse.StatusCode != 500))
            {
                return(new object[0]);
            }

            // this statusCode check is just so we don't repeat the contentType check we did above
            bool isSoap = ContentType.IsSoap(message.ContentType);

            if (!isSoap || (isSoap && (httpResponse != null) && (httpResponse.ContentLength == 0)))
            {
                // special-case 400 since we exempted it above on the off-chance it might be a soap 1.2 sender fault.
                // based on the content-type, it looks like it's probably just a regular old 400
                if (statusCode == 400)
                {
                    throw new WebException(RequestResponseUtils.CreateResponseExceptionString(httpResponse, responseStream), null,
                                           WebExceptionStatus.ProtocolError, httpResponse);
                }
                else
                {
                    throw new InvalidOperationException(Res.GetString(Res.WebResponseContent, message.ContentType, HttpContentType) +
                                                        Environment.NewLine +
                                                        RequestResponseUtils.CreateResponseExceptionString(response, responseStream));
                }
            }
            if (message.Exception != null)
            {
                throw message.Exception;
            }

            // perf fix: changed buffer size passed to StreamReader
            int bufferSize;

            if (asyncCall || httpResponse == null)
            {
                bufferSize = 512;
            }
            else
            {
                bufferSize = RequestResponseUtils.GetBufferSize((int)httpResponse.ContentLength);
            }
            XmlReader reader = GetReaderForMessage(message, bufferSize);

            if (reader == null)
            {
                throw new InvalidOperationException(Res.GetString(Res.WebNullReaderForMessage));
            }

            reader.MoveToContent();
            int depth = reader.Depth;

            // should be able to handle no ns, soap 1.1 ns, or soap 1.2 ns
            string encodingNs = EncodingNs;
            string envelopeNs = reader.NamespaceURI;

            if (envelopeNs == null || envelopeNs.Length == 0)
            {
                // ok to omit namespace -- assume correct version
                reader.ReadStartElement(Soap.Element.Envelope);
            }
            else if (reader.NamespaceURI == Soap.Namespace)
            {
                reader.ReadStartElement(Soap.Element.Envelope, Soap.Namespace);
            }
            else if (reader.NamespaceURI == Soap12.Namespace)
            {
                reader.ReadStartElement(Soap.Element.Envelope, Soap12.Namespace);
            }
            else
            {
                throw new SoapException(Res.GetString(Res.WebInvalidEnvelopeNamespace, envelopeNs, EnvelopeNs), SoapException.VersionMismatchFaultCode);
            }

            reader.MoveToContent();
            SoapHeaderHandling headerHandler = new SoapHeaderHandling();

            headerHandler.ReadHeaders(reader, method.outHeaderSerializer, message.Headers, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, envelopeNs, method.use == SoapBindingUse.Encoded ? encodingNs : null, false);
            reader.MoveToContent();
            reader.ReadStartElement(Soap.Element.Body, envelopeNs);
            reader.MoveToContent();
            if (reader.IsStartElement(Soap.Element.Fault, envelopeNs))
            {
                message.Exception = ReadSoapException(reader);
            }
            else
            {
                if (method.oneWay)
                {
                    reader.Skip();
                    message.SetParameterValues(new object[0]);
                }
                else
                {
                    TraceMethod caller        = Tracing.On ? new TraceMethod(this, "ReadResponse") : null;
                    bool        isEncodedSoap = method.use == SoapBindingUse.Encoded;
                    if (Tracing.On)
                    {
                        Tracing.Enter(Tracing.TraceId(Res.TraceReadResponse), caller, new TraceMethod(method.returnSerializer, "Deserialize", reader, isEncodedSoap ? encodingNs : null));
                    }

                    bool useDeserializationEvents = !isEncodedSoap && (WebServicesSection.Current.SoapEnvelopeProcessing.IsStrict || Tracing.On);
                    if (useDeserializationEvents)
                    {
                        XmlDeserializationEvents events = Tracing.On ? Tracing.GetDeserializationEvents() : RuntimeUtils.GetDeserializationEvents();
                        message.SetParameterValues((object[])method.returnSerializer.Deserialize(reader, null, events));
                    }
                    else
                    {
                        message.SetParameterValues((object[])method.returnSerializer.Deserialize(reader, isEncodedSoap ? encodingNs : null));
                    }

                    if (Tracing.On)
                    {
                        Tracing.Exit(Tracing.TraceId(Res.TraceReadResponse), caller);
                    }
                }
            }

            // Consume soap:Body and soap:Envelope closing tags
            while (depth < reader.Depth && reader.Read())
            {
                // Nothing, just read on
            }
            // consume end tag
            if (reader.NodeType == XmlNodeType.EndElement)
            {
                reader.Read();
            }

            message.SetStage(SoapMessageStage.AfterDeserialize);
            message.RunExtensions(message.initializedExtensions, false);
            SoapHeaderHandling.SetHeaderMembers(message.Headers, this, method.outHeaderMappings, SoapHeaderDirection.Out | SoapHeaderDirection.Fault, true);

            if (message.Exception != null)
            {
                throw message.Exception;
            }
            return(message.GetParameterValues());
        }
		//
		// TODO:
		//    Handle other web responses (multi-output?)
		//    
		object [] ReceiveResponse (WebResponse response, SoapClientMessage message, SoapExtension[] extensions)
		{
			SoapMethodStubInfo msi = message.MethodStubInfo;
			HttpWebResponse http_response = response as HttpWebResponse;
			
			if (http_response != null)
			{
				HttpStatusCode code = http_response.StatusCode;
	
				if (!(code == HttpStatusCode.Accepted || code == HttpStatusCode.OK || code == HttpStatusCode.InternalServerError)) {
					string msg = "The request failed with HTTP status {0}: {1}";
					msg = String.Format (msg, (int) code, code);
					throw new WebException (msg, null, WebExceptionStatus.ProtocolError, http_response);
				}
				if (message.OneWay && response.ContentLength == 0 && (code == HttpStatusCode.Accepted || code == HttpStatusCode.OK)) {
					return new object[0];
				}
			}
			
			//
			// Remove optional encoding
			//
			string ctype;
			Encoding encoding = WebServiceHelper.GetContentEncoding (response.ContentType, out ctype);
			if (ctype != "text/xml")
				WebServiceHelper.InvalidOperation (
					"Content is not 'text/xml' but '" + response.ContentType + "'",
					response, encoding);

			message.ContentType = ctype;
			message.ContentEncoding = encoding.WebName;
			
			Stream stream = response.GetResponseStream ();

			if (extensions != null) {
				stream = SoapExtension.ExecuteChainStream (extensions, stream);
				message.SetStage (SoapMessageStage.BeforeDeserialize);
				SoapExtension.ExecuteProcessMessage (extensions, message, false);
			}
			
			// Deserialize the response

			SoapHeaderCollection headers;
			object content;

			using (StreamReader reader = new StreamReader (stream, encoding, false)) {
				XmlTextReader xml_reader = new XmlTextReader (reader);

				WebServiceHelper.ReadSoapMessage (xml_reader, type_info, msi.Use, msi.ResponseSerializer,
								out content, out headers);
			}

			
			if (content is Fault)
			{
				Fault fault = (Fault) content;
				SoapException ex = new SoapException (fault.faultstring, fault.faultcode, fault.faultactor, fault.detail);
				message.SetException (ex);
			}
			else
				message.OutParameters = (object[]) content;
			
			message.SetHeaders (headers);
			message.UpdateHeaderValues (this, message.MethodStubInfo.Headers);

			if (extensions != null) {
				message.SetStage (SoapMessageStage.AfterDeserialize);
				SoapExtension.ExecuteProcessMessage (extensions, message, false);
			}

			if (message.Exception == null)
				return message.OutParameters;
			else
				throw message.Exception;
		}
Beispiel #50
0
        SoapClientMessage BeforeSerialize(WebRequest request, string methodName, object[] parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            SoapClientMethod method = clientType.GetMethod(methodName);

            if (method == null)
            {
                throw new ArgumentException(Res.GetString(Res.WebInvalidMethodName, methodName));
            }

            // Run BeforeSerialize extension pass. Extensions are not allowed
            // to write into the stream during this pass.
            SoapReflectedExtension[] allExtensions     = (SoapReflectedExtension[])CombineExtensionsHelper(clientType.HighPriExtensions, method.extensions, clientType.LowPriExtensions, typeof(SoapReflectedExtension));
            object[]          allExtensionInitializers = (object[])CombineExtensionsHelper(clientType.HighPriExtensionInitializers, method.extensionInitializers, clientType.LowPriExtensionInitializers, typeof(object));
            SoapExtension[]   initializedExtensions    = SoapMessage.InitializeExtensions(allExtensions, allExtensionInitializers);
            SoapClientMessage message = new SoapClientMessage(this, method, Url);

            message.initializedExtensions = initializedExtensions;
            if (initializedExtensions != null)
            {
                message.SetExtensionStream(new SoapExtensionStream());
            }
            message.InitExtensionStreamChain(message.initializedExtensions);

            string soapAction = UrlEncoder.EscapeString(method.action, Encoding.UTF8);

            message.SetStage(SoapMessageStage.BeforeSerialize);
            if (this.version == SoapProtocolVersion.Soap12)
            {
                message.ContentType = ContentType.Compose(ContentType.ApplicationSoap, RequestEncoding != null ? RequestEncoding : Encoding.UTF8, soapAction);
            }
            else
            {
                message.ContentType = ContentType.Compose(ContentType.TextXml, RequestEncoding != null ? RequestEncoding : Encoding.UTF8);
            }
            message.SetParameterValues(parameters);
            SoapHeaderHandling.GetHeaderMembers(message.Headers, this, method.inHeaderMappings, SoapHeaderDirection.In, true);
            message.RunExtensions(message.initializedExtensions);

            // Last chance to set request headers
            request.ContentType = message.ContentType;
            if (message.ContentEncoding != null && message.ContentEncoding.Length > 0)
            {
                request.Headers[ContentType.ContentEncoding] = message.ContentEncoding;
            }

            request.Method = "POST";
            if (this.version != SoapProtocolVersion.Soap12 && request.Headers[Soap.Action] == null)
            {
                StringBuilder actionStringBuilder = new StringBuilder(soapAction.Length + 2);
                actionStringBuilder.Append('"');
                actionStringBuilder.Append(soapAction);
                actionStringBuilder.Append('"');
                request.Headers.Add(Soap.Action, actionStringBuilder.ToString());
            }

            return(message);
        }
        protected override XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize)
        {
            if (bufferSize < 0x200)
            {
                bufferSize = 0x200;
            }

            return new XmlSpecialNSPrefixTextWriter(new StreamWriter(message.Stream, (base.RequestEncoding != null) ? base.RequestEncoding : new UTF8Encoding(false), bufferSize));
        }
 protected virtual XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize)
 {
   if (bufferSize < 512)
     bufferSize = 512;
   return (XmlWriter) new XmlTextWriter((TextWriter) new StreamWriter(message.Stream, this.RequestEncoding != null ? this.RequestEncoding : (Encoding) new UTF8Encoding(false), bufferSize));
 }