File: HttpClientProtocol.cs

package info (click to toggle)
mono 6.8.0.105%2Bdfsg-3.3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,284,512 kB
  • sloc: cs: 11,172,132; xml: 2,850,069; ansic: 671,653; cpp: 122,091; perl: 59,366; javascript: 30,841; asm: 22,168; makefile: 20,093; sh: 15,020; python: 4,827; pascal: 925; sql: 859; sed: 16; php: 1
file content (348 lines) | stat: -rw-r--r-- 16,885 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
//------------------------------------------------------------------------------
// <copyright file="HttpClientProtocol.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>                                                                
//------------------------------------------------------------------------------

namespace System.Web.Services.Protocols {
    using System;
    using System.Collections;
    using System.IO;
    using System.Reflection;
    using System.Xml.Serialization;
    using System.Net;
    using System.Text;
    using System.Threading;
    using System.ComponentModel;
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    using System.Web.Services.Diagnostics;

    internal class HttpClientMethod {
        internal Type readerType;
        internal object readerInitializer;
        internal Type writerType;
        internal object writerInitializer;
        internal LogicalMethodInfo methodInfo;
    }

    internal class HttpClientType {
        Hashtable methods = new Hashtable();

        internal HttpClientType(Type type) {
            LogicalMethodInfo[] methodInfos = LogicalMethodInfo.Create(type.GetMethods(), LogicalMethodTypes.Sync);

            Hashtable formatterTypes = new Hashtable();
            for (int i = 0; i < methodInfos.Length; i++) {
                LogicalMethodInfo methodInfo = methodInfos[i];
                try {
                    object[] attributes = methodInfo.GetCustomAttributes(typeof(HttpMethodAttribute));
                    if (attributes.Length == 0) continue;
                    HttpMethodAttribute attribute = (HttpMethodAttribute)attributes[0];
                    HttpClientMethod method = new HttpClientMethod();
                    method.readerType = attribute.ReturnFormatter;
                    method.writerType = attribute.ParameterFormatter;
                    method.methodInfo = methodInfo;
                    AddFormatter(formatterTypes, method.readerType, method);
                    AddFormatter(formatterTypes, method.writerType, method);
                    methods.Add(methodInfo.Name, method);
                }
                catch (Exception e) {
                    if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
                        throw;
                    }
                    throw new InvalidOperationException(Res.GetString(Res.WebReflectionError, methodInfo.DeclaringType.FullName, methodInfo.Name), e);
                }
            }

            foreach (Type t in formatterTypes.Keys) {
                ArrayList list = (ArrayList)formatterTypes[t];
                LogicalMethodInfo[] m = new LogicalMethodInfo[list.Count];
                for (int j = 0; j < list.Count; j++)
                    m[j] = ((HttpClientMethod)list[j]).methodInfo;
                object[] initializers = MimeFormatter.GetInitializers(t, m);
                bool isWriter = typeof(MimeParameterWriter).IsAssignableFrom(t);
                for (int j = 0; j < list.Count; j++) {
                    if (isWriter) {
                        ((HttpClientMethod)list[j]).writerInitializer = initializers[j];
                    }
                    else {
                        ((HttpClientMethod)list[j]).readerInitializer = initializers[j];
                    }
                }
            }
        }

        static void AddFormatter(Hashtable formatterTypes, Type formatterType, HttpClientMethod method) {
            if (formatterType == null) return;
            ArrayList list = (ArrayList)formatterTypes[formatterType];
            if (list == null) {
                list = new ArrayList();
                formatterTypes.Add(formatterType, list);
            }
            list.Add(method);
        }

        internal HttpClientMethod GetMethod(string name) {
            return (HttpClientMethod)methods[name];
        }
    }

    /// <include file='doc\HttpClientProtocol.uex' path='docs/doc[@for="HttpSimpleClientProtocol"]/*' />
    /// <devdoc>
    ///    <para>
    ///       Specifies
    ///       most of the implementation for communicating with an HTTP web service over HTTP.
    ///    </para>
    /// </devdoc>
    [ComVisible(true)]
    public abstract class HttpSimpleClientProtocol : HttpWebClientProtocol {
        HttpClientType clientType;

        /// <include file='doc\HttpClientProtocol.uex' path='docs/doc[@for="HttpSimpleClientProtocol.HttpSimpleClientProtocol"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Web.Services.Protocols.HttpSimpleClientProtocol'/> class.
        ///    </para>
        /// </devdoc>
        protected HttpSimpleClientProtocol()
            : base() {
            Type type = this.GetType();
            clientType = (HttpClientType)GetFromCache(type);
            if (clientType == null) {
                lock (InternalSyncObject) {
                    clientType = (HttpClientType)GetFromCache(type);
                    if (clientType == null) {
                        clientType = new HttpClientType(type);
                        AddToCache(type, clientType);
                    }
                }
            }
        }

        /// <include file='doc\HttpClientProtocol.uex' path='docs/doc[@for="HttpSimpleClientProtocol.Invoke"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Invokes a method of a HTTP web service.
        ///    </para>
        /// </devdoc>
        protected object Invoke(string methodName, string requestUrl, object[] parameters) {
            WebResponse response = null;
            HttpClientMethod method = GetClientMethod(methodName);
            MimeParameterWriter paramWriter = GetParameterWriter(method);                
            Uri requestUri = new Uri(requestUrl);
            if (paramWriter != null) {
                paramWriter.RequestEncoding = RequestEncoding;
                requestUrl = paramWriter.GetRequestUrl(requestUri.AbsoluteUri, parameters);
                requestUri = new Uri(requestUrl, true);
            }
            WebRequest request = null;
            try {
                request = GetWebRequest(requestUri);
                NotifyClientCallOut(request);
                PendingSyncRequest = request;
                if (paramWriter != null) {
                    paramWriter.InitializeRequest(request, parameters);      
                    // 


                    if (paramWriter.UsesWriteRequest) {                        
                        if (parameters.Length == 0)
                            request.ContentLength = 0;
                        else {
                            Stream requestStream = null;
                            try {
                                requestStream = request.GetRequestStream();
                                paramWriter.WriteRequest(requestStream, parameters);
                            }
                            finally {
                                if (requestStream != null) requestStream.Close();
                            }                            
                        }
                    }
                }
                response = GetWebResponse(request);            
                Stream responseStream = null;
                if (response.ContentLength != 0)
                    responseStream = response.GetResponseStream();

                return ReadResponse(method, response, responseStream);
            }
            finally {
                if (request == PendingSyncRequest)
                    PendingSyncRequest = null;
            }
        }


        /// <include file='doc\HttpClientProtocol.uex' path='docs/doc[@for="HttpSimpleClientProtocol.BeginInvoke"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Starts an asynchronous invocation of a method of a HTTP web service.
        ///    </para>
        /// </devdoc>
        protected IAsyncResult BeginInvoke(string methodName, string requestUrl, object[] parameters, AsyncCallback callback, object asyncState) {
            HttpClientMethod method = GetClientMethod(methodName);
            MimeParameterWriter paramWriter = GetParameterWriter(method);
            Uri requestUri = new Uri(requestUrl);            
            if (paramWriter != null) {
                paramWriter.RequestEncoding = RequestEncoding;
                requestUrl = paramWriter.GetRequestUrl(requestUri.AbsoluteUri, parameters);
                requestUri = new Uri(requestUrl, true);
            }
            InvokeAsyncState invokeState = new InvokeAsyncState(method, paramWriter, parameters);            
            WebClientAsyncResult asyncResult = new WebClientAsyncResult(this, invokeState, null, callback, asyncState);
            return BeginSend(requestUri, asyncResult, paramWriter.UsesWriteRequest);
        }


        /// <include file='doc\HttpClientProtocol.uex' path='docs/doc[@for="HttpSimpleClientProtocol.InitializeAsyncRequest"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        internal override void InitializeAsyncRequest(WebRequest request, object internalAsyncState) {
            InvokeAsyncState invokeState = (InvokeAsyncState)internalAsyncState;
            if (invokeState.ParamWriter.UsesWriteRequest && invokeState.Parameters.Length == 0) 
                request.ContentLength = 0;
        }

        internal override void AsyncBufferedSerialize(WebRequest request, Stream requestStream, object internalAsyncState) {
            InvokeAsyncState invokeState = (InvokeAsyncState)internalAsyncState;
            if (invokeState.ParamWriter != null) {
                invokeState.ParamWriter.InitializeRequest(request, invokeState.Parameters);
                if (invokeState.ParamWriter.UsesWriteRequest && invokeState.Parameters.Length > 0)
                    invokeState.ParamWriter.WriteRequest(requestStream, invokeState.Parameters);                        
            }
        }

        class InvokeAsyncState {            
            internal object[] Parameters;
            internal MimeParameterWriter ParamWriter;
            internal HttpClientMethod Method;            

            internal InvokeAsyncState(HttpClientMethod method, MimeParameterWriter paramWriter, object[] parameters) {
                this.Method = method;
                this.ParamWriter = paramWriter;
                this.Parameters = parameters;
            }
        }

        /// <include file='doc\HttpClientProtocol.uex' path='docs/doc[@for="HttpSimpleClientProtocol.EndInvoke"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Ends an asynchronous invocation of a method of a HTTP web service.
        ///    </para>
        /// </devdoc>
        protected object EndInvoke(IAsyncResult asyncResult) {            
            object o = null;
            Stream responseStream = null;
            WebResponse response = EndSend(asyncResult, ref o, ref responseStream);
            InvokeAsyncState invokeState = (InvokeAsyncState) o;
            return ReadResponse(invokeState.Method, response, responseStream);
        }

        private void InvokeAsyncCallback(IAsyncResult result) {
            object parameter = null;
            Exception exception = null;
            WebClientAsyncResult asyncResult = (WebClientAsyncResult)result;
            if (asyncResult.Request != null) {
                try {
                    object o = null;
                    Stream responseStream = null;
                    WebResponse response = EndSend(asyncResult, ref o, ref responseStream);
                    InvokeAsyncState invokeState = (InvokeAsyncState) o;
                    parameter = ReadResponse(invokeState.Method, response, responseStream);
                } 
                catch (Exception e) {
                    if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                        throw;
                    exception = e;
                    if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "InvokeAsyncCallback", e);
                }
            }
            AsyncOperation asyncOp = (AsyncOperation)result.AsyncState;
            UserToken token = (UserToken)asyncOp.UserSuppliedState;
            OperationCompleted(token.UserState, new object[] { parameter }, exception, false);
        }
        /// <include file='doc\HttpClientProtocol.uex' path='docs/doc[@for="HttpSimpleClientProtocol.InvokeAsync"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected void InvokeAsync(string methodName, string requestUrl, object[] parameters, SendOrPostCallback callback) {
            InvokeAsync(methodName, requestUrl, parameters, callback, null);
        }

        /// <include file='doc\HttpClientProtocol.uex' path='docs/doc[@for="HttpSimpleClientProtocol.InvokeAsync1"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected void InvokeAsync(string methodName, string requestUrl, object[] parameters, SendOrPostCallback callback, object userState) {
            if (userState == null)
                userState = NullToken;
            AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(new UserToken(callback, userState));
            WebClientAsyncResult asyncResult = new WebClientAsyncResult(this, null, null, new AsyncCallback(InvokeAsyncCallback), asyncOp);
            try {
                AsyncInvokes.Add(userState, asyncResult);
            }
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                    throw;
                if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "InvokeAsync", e);
                Exception exception = new ArgumentException(Res.GetString(Res.AsyncDuplicateUserState), e);
                InvokeCompletedEventArgs eventArgs = new InvokeCompletedEventArgs(new object[] { null }, exception, false, userState);
                asyncOp.PostOperationCompleted(callback, eventArgs);
                return;
            }
            try {
                HttpClientMethod method = GetClientMethod(methodName);
                MimeParameterWriter paramWriter = GetParameterWriter(method);
                Uri requestUri = new Uri(requestUrl);            
                if (paramWriter != null) {
                    paramWriter.RequestEncoding = RequestEncoding;
                    requestUrl = paramWriter.GetRequestUrl(requestUri.AbsoluteUri, parameters);
                    requestUri = new Uri(requestUrl, true);
                }
                asyncResult.InternalAsyncState = new InvokeAsyncState(method, paramWriter, parameters);
                BeginSend(requestUri, asyncResult, paramWriter.UsesWriteRequest);
            } 
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
                    throw;
                if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "InvokeAsync", e);
                OperationCompleted(userState, new object[] { null }, e, false);
            }
        }

        MimeParameterWriter GetParameterWriter(HttpClientMethod method) {
            if (method.writerType == null)
                return null;
            return (MimeParameterWriter)MimeFormatter.CreateInstance(method.writerType, method.writerInitializer);                
        }

        HttpClientMethod GetClientMethod(string methodName) {
            HttpClientMethod method = clientType.GetMethod(methodName);
            if (method == null) throw new ArgumentException(Res.GetString(Res.WebInvalidMethodName, methodName), "methodName");
            return method;
        }

        object ReadResponse(HttpClientMethod method, WebResponse response, Stream responseStream) {
            HttpWebResponse httpResponse = response as HttpWebResponse;
            if (httpResponse != null && (int)httpResponse.StatusCode >= 300)
                throw new WebException(RequestResponseUtils.CreateResponseExceptionString(httpResponse, responseStream), null, 
                    WebExceptionStatus.ProtocolError, httpResponse);

            if (method.readerType == null)
                return null;

            // 


            if (responseStream != null) {
                MimeReturnReader reader = (MimeReturnReader)MimeFormatter.CreateInstance(method.readerType, method.readerInitializer);
                return reader.Read(response, responseStream);                
            }
            else
                return null;
        }
    }
}