File: WebScriptEnablingBehavior.cs

package info (click to toggle)
mono 4.6.2.7%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 778,148 kB
  • ctags: 914,052
  • sloc: cs: 5,779,509; xml: 2,773,713; ansic: 432,645; sh: 14,749; makefile: 12,361; perl: 2,488; python: 1,434; cpp: 849; asm: 531; sql: 95; sed: 16; php: 1
file content (491 lines) | stat: -rw-r--r-- 24,814 bytes parent folder | download
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//------------------------------------------------------------
#pragma warning disable 1634, 1691
namespace System.ServiceModel.Description
{
    using System;
    using System.Diagnostics;
    using System.Globalization;
    using System.Net;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.Security;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Dispatcher;
    using System.ServiceModel.Web;
    using System.Xml;

    public sealed class WebScriptEnablingBehavior : WebHttpBehavior
    {
        static readonly DataContractJsonSerializer jsonFaultSerializer = new DataContractJsonSerializer(typeof(JsonFaultDetail));
        static readonly WebMessageBodyStyle webScriptBodyStyle = WebMessageBodyStyle.WrappedRequest;
        static readonly WebMessageFormat webScriptDefaultMessageFormat = WebMessageFormat.Json;
        const int MaxMetadataEndpointBufferSize = 2048;
        WebMessageFormat requestMessageFormat = webScriptDefaultMessageFormat;
        WebMessageFormat responseMessageFormat = webScriptDefaultMessageFormat;

        public WebScriptEnablingBehavior()
        {
        }

        public override WebMessageBodyStyle DefaultBodyStyle
        {
            get
            {
                return webScriptBodyStyle;
            }
            set
            {
                if (value != webScriptBodyStyle)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.BodyStyleNotSupportedByWebScript, value, this.GetType().Name, webScriptBodyStyle)));
                }
            }
        }

        public override WebMessageFormat DefaultOutgoingRequestFormat
        {
            get
            {
                return this.requestMessageFormat;
            }
            set
            {
                if (!WebMessageFormatHelper.IsDefined(value))
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
                }
                this.requestMessageFormat = value;
            }
        }

        public override WebMessageFormat DefaultOutgoingResponseFormat
        {
            get
            {
                return this.responseMessageFormat;
            }
            set
            {
                if (!WebMessageFormatHelper.IsDefined(value))
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
                }
                this.responseMessageFormat = value;
            }
        }

        public override bool HelpEnabled
        {
            get
            {
                return false;
            }
            set
            {
                if (value)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.HelpPageNotSupportedInScripts)));
                }
            }
        }

        public override bool AutomaticFormatSelectionEnabled
        {
            get
            {
                return false;
            }
            set
            {
                if (value)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.AutomaticFormatSelectionNotSupportedInScripts)));
                }
            }
        }

        public override bool FaultExceptionEnabled
        {
            get
            {
                return false;
            }
            set
            {
                if (value)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.FaultExceptionEnabledNotSupportedInScripts)));
                }
            }
        }

        public override void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            base.ApplyClientBehavior(endpoint, clientRuntime);
#pragma warning disable 56506 // [....], clientRuntime.MessageInspectors is never null
            clientRuntime.MessageInspectors.Add(new JsonClientMessageInspector());
#pragma warning restore 56506
        }

        public override void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            base.ApplyDispatchBehavior(endpoint, endpointDispatcher);

            try
            {
                AddMetadataEndpoint(endpoint, endpointDispatcher, false); //  debugMode 
                AddMetadataEndpoint(endpoint, endpointDispatcher, true); //  debugMode 
            }
            catch (XmlException exception)
            {
                // [....], need to reference this resource string although fix for 13332 was removed
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.InvalidXmlCharactersInNameUsedWithPOSTMethod, string.Empty, string.Empty, string.Empty), exception));
            }
        }

        public override void Validate(ServiceEndpoint endpoint)
        {
            base.Validate(endpoint);

#pragma warning disable 56506 // [....], endpoint.Contract is never null
            foreach (OperationDescription operation in endpoint.Contract.Operations)
#pragma warning restore 56506
            {
                if (operation.Behaviors.Find<XmlSerializerOperationBehavior>() != null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                        SR2.GetString(SR2.WebScriptNotSupportedForXmlSerializerFormat, typeof(XmlSerializerFormatAttribute).Name, this.GetType().ToString())));
                }
                string method = WebHttpBehavior.GetWebMethod(operation);
                if (method != WebHttpBehavior.GET
                    && method != WebHttpBehavior.POST)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                        SR2.GetString(SR2.WebScriptInvalidHttpRequestMethod, operation.Name,
                        endpoint.Contract.Name, method, this.GetType().ToString())));
                }
                WebGetAttribute webGetAttribute = operation.Behaviors.Find<WebGetAttribute>();
                if (webGetAttribute != null && webGetAttribute.UriTemplate != null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                        SR2.GetString(SR2.WebScriptNotSupportedForXmlSerializerFormat, typeof(UriTemplate).Name, this.GetType().ToString())));
                }
                WebInvokeAttribute webInvokeAttribute = operation.Behaviors.Find<WebInvokeAttribute>();
                if (webInvokeAttribute != null && webInvokeAttribute.UriTemplate != null)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                        SR2.GetString(SR2.WebScriptNotSupportedForXmlSerializerFormat, typeof(UriTemplate).Name, this.GetType().ToString())));
                }
                WebMessageBodyStyle bodyStyle = GetBodyStyle(operation);
                if (bodyStyle != webScriptBodyStyle)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.BodyStyleNotSupportedByWebScript, bodyStyle, this.GetType().Name, webScriptBodyStyle)));
                }

                foreach (MessageDescription messageDescription in operation.Messages)
                {
                    if (!messageDescription.IsTypedMessage &&
                        (messageDescription.Direction == MessageDirection.Output) &&
                        (messageDescription.Body.Parts.Count > 0))
                    {
                        throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                            SR2.GetString(SR2.WebScriptOutRefOperationsNotSupported, operation.Name,
                            endpoint.Contract.Name)));
                    }
                }
            }
        }

        internal override DataContractJsonSerializerOperationFormatter CreateDataContractJsonSerializerOperationFormatter(OperationDescription od, DataContractSerializerOperationBehavior dcsob, bool isWrapped)
        {
            return new DataContractJsonSerializerOperationFormatter(od, dcsob.MaxItemsInObjectGraph, dcsob.IgnoreExtensionDataObject, dcsob.DataContractSurrogate, isWrapped, true, this.JavascriptCallbackParameterName);
        }

        internal override string GetWmiTypeName()
        {
            return "WebScriptEnablingBehavior";
        }

        internal override bool UseBareReplyFormatter(WebMessageBodyStyle style, OperationDescription operationDescription, WebMessageFormat responseFormat, out Type parameterType)
        {
            if (responseFormat == WebMessageFormat.Json)
            {
                parameterType = null;
                return false;
            }
            return base.UseBareReplyFormatter(style, operationDescription, responseFormat, out parameterType);
        }

        protected override void AddClientErrorInspector(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(new JsonClientMessageInspector());
        }

        protected override void AddServerErrorHandlers(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            if (endpointDispatcher.ChannelDispatcher == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(
                    "endpointDispatcher", SR2.GetString(SR2.ChannelDispatcherMustBePresent));
            }
#pragma warning disable 56506 // [....], endpointDispatcher.ChannelDispatcher.ErrorHandlers never null
            endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new JsonErrorHandler(endpoint, endpointDispatcher.ChannelDispatcher.IncludeExceptionDetailInFaults));
#pragma warning restore 56506
        }

        protected override QueryStringConverter GetQueryStringConverter(OperationDescription operationDescription)
        {
            return new JsonQueryStringConverter(operationDescription);
        }

        void AddMetadataEndpoint(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher, bool debugMode)
        {
            Uri baseAddress = endpoint.Address.Uri;
            if (baseAddress == null)
            {
                return;
            }

            ServiceHostBase host = endpointDispatcher.ChannelDispatcher.Host;

            UriBuilder builder = new UriBuilder(baseAddress);
            builder.Path += builder.Path.EndsWith("/", StringComparison.OrdinalIgnoreCase)
                ? (WebScriptClientGenerator.GetMetadataEndpointSuffix(debugMode))
                : ("/" + WebScriptClientGenerator.GetMetadataEndpointSuffix(debugMode));
            EndpointAddress metadataAddress = new EndpointAddress(builder.Uri);

            foreach (ServiceEndpoint serviceEndpoint in host.Description.Endpoints)
            {
                if (EndpointAddress.UriEquals(serviceEndpoint.Address.Uri, metadataAddress.Uri, true, false))//  ignoreCase //  includeHostNameInComparison 
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(SR2.GetString(SR2.JsonNoEndpointAtMetadataAddress, this.GetType().ToString(), serviceEndpoint.Address, serviceEndpoint.Name, host.Description.Name)));
                }
            }

            HttpTransportBindingElement transportBindingElement;
            HttpTransportBindingElement existingTransportBindingElement = endpoint.Binding.CreateBindingElements().Find<HttpTransportBindingElement>();

            if (existingTransportBindingElement != null)
            {
                transportBindingElement = (HttpTransportBindingElement)existingTransportBindingElement.Clone();
            }
            else
            {
                if (baseAddress.Scheme == "https")
                {
                    transportBindingElement = new HttpsTransportBindingElement();
                }
                else
                {
                    transportBindingElement = new HttpTransportBindingElement();
                }
            }

            transportBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            transportBindingElement.TransferMode = TransferMode.Buffered;
            transportBindingElement.MaxBufferSize = MaxMetadataEndpointBufferSize;
            transportBindingElement.MaxReceivedMessageSize = MaxMetadataEndpointBufferSize;
            Binding metadataBinding = new CustomBinding(
                new WebScriptMetadataMessageEncodingBindingElement(),
                transportBindingElement);
            BindingParameterCollection parameters = host.GetBindingParameters(endpoint);

            // build endpoint dispatcher
            ContractDescription metadataContract = ContractDescription.GetContract(typeof(ServiceMetadataExtension.IHttpGetMetadata));
            OperationDescription metadataOperation = metadataContract.Operations[0];
            EndpointDispatcher metadataEndpointDispatcher = new EndpointDispatcher(metadataAddress, metadataContract.Name, metadataContract.Namespace);
            DispatchOperation dispatchOperation = new DispatchOperation(metadataEndpointDispatcher.DispatchRuntime, metadataOperation.Name, metadataOperation.Messages[0].Action, metadataOperation.Messages[1].Action);
            dispatchOperation.Formatter = new WebScriptMetadataFormatter();
            dispatchOperation.Invoker = new SyncMethodInvoker(metadataOperation.SyncMethod);
            metadataEndpointDispatcher.DispatchRuntime.Operations.Add(dispatchOperation);
            metadataEndpointDispatcher.DispatchRuntime.SingletonInstanceContext = new InstanceContext(host, new WebScriptClientGenerator(endpoint, debugMode, !String.IsNullOrEmpty(this.JavascriptCallbackParameterName)));
            metadataEndpointDispatcher.DispatchRuntime.InstanceContextProvider = new SingletonInstanceContextProvider(metadataEndpointDispatcher.DispatchRuntime);

            // build channel dispatcher
            IChannelListener<IReplyChannel> listener = null;
            if (metadataBinding.CanBuildChannelListener<IReplyChannel>(parameters))
            {
                listener = metadataBinding.BuildChannelListener<IReplyChannel>(metadataAddress.Uri, parameters);
            }
            ChannelDispatcher metadataChannelDispatcher = new ChannelDispatcher(listener);
            metadataChannelDispatcher.MessageVersion = MessageVersion.None;
            metadataChannelDispatcher.Endpoints.Add(metadataEndpointDispatcher);

            host.ChannelDispatchers.Add(metadataChannelDispatcher);
        }

        class JsonClientMessageInspector : WebFaultClientMessageInspector
        {
            public override void AfterReceiveReply(ref Message reply, object correlationState)
            {
                bool callBase = true;
                if (reply != null)
                {
                    object responseProperty = reply.Properties[HttpResponseMessageProperty.Name];
                    if (responseProperty != null)
                    {
                        if (((HttpResponseMessageProperty)responseProperty).Headers[JsonGlobals.jsonerrorString] == JsonGlobals.trueString)
                        {
                            callBase = false;
                            XmlDictionaryReader reader = reply.GetReaderAtBodyContents();
                            JsonFaultDetail faultDetail = jsonFaultSerializer.ReadObject(reader) as JsonFaultDetail;
                            FaultCode faultCode = new FaultCode(FaultCodeConstants.Codes.InternalServiceFault, FaultCodeConstants.Namespaces.NetDispatch);
                            faultCode = FaultCode.CreateReceiverFaultCode(faultCode);
                            if (faultDetail != null)
                            {
                                if (faultDetail.ExceptionDetail != null)
                                {
                                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                        new FaultException<ExceptionDetail>(faultDetail.ExceptionDetail, faultDetail.Message, faultCode));
                                }
                                else
                                {
                                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                        new FaultException(MessageFault.CreateFault(faultCode, faultDetail.Message)));
                                }
                            }
                            else
                            {
                                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                    new FaultException(MessageFault.CreateFault(faultCode,
                                    System.ServiceModel.SR.GetString(System.ServiceModel.SR.SFxInternalServerError))));
                            }
                        }
                    }
                }
                if (callBase)
                {
                    base.AfterReceiveReply(ref reply, correlationState);
                }
            }
        }

        class JsonErrorHandler : IErrorHandler
        {
            bool includeExceptionDetailInFaults;
            string outgoingContentType;

            public JsonErrorHandler(ServiceEndpoint endpoint, bool includeExceptionDetailInFaults)
            {
                WebMessageEncodingBindingElement webMEBE = endpoint.Binding.CreateBindingElements().Find<WebMessageEncodingBindingElement>();
                outgoingContentType = JsonMessageEncoderFactory.GetContentType(webMEBE);
                this.includeExceptionDetailInFaults = includeExceptionDetailInFaults;
            }

            public bool HandleError(Exception error)
            {
                return false;
            }

            public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
            {
                HttpResponseMessageProperty responseProperty;
                if (fault == null)
                {
                    FaultCode code = new FaultCode(FaultCodeConstants.Codes.InternalServiceFault, FaultCodeConstants.Namespaces.NetDispatch);
                    code = FaultCode.CreateReceiverFaultCode(code);
                    string action = FaultCodeConstants.Actions.NetDispatcher;

                    MessageFault innerFault;
                    innerFault = MessageFault.CreateFault(code, new FaultReason(error.Message, CultureInfo.CurrentCulture), new ExceptionDetail(error));
                    fault = Message.CreateMessage(version, action, new JsonFaultBodyWriter(innerFault, this.includeExceptionDetailInFaults));

                    responseProperty = new HttpResponseMessageProperty();
                    fault.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
                }
                else
                {
                    MessageFault innerFault = MessageFault.CreateFault(fault, TransportDefaults.MaxFaultSize);
                    Message newMessage = Message.CreateMessage(version, fault.Headers.Action, new JsonFaultBodyWriter(innerFault, this.includeExceptionDetailInFaults));
                    newMessage.Headers.To = fault.Headers.To;
                    newMessage.Properties.CopyProperties(fault.Properties);

                    object property = null;
                    if (newMessage.Properties.TryGetValue(HttpResponseMessageProperty.Name, out property))
                    {
                        responseProperty = (HttpResponseMessageProperty)property;
                    }
                    else
                    {
                        responseProperty = new HttpResponseMessageProperty();
                        newMessage.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
                    }

                    fault.Close();
                    fault = newMessage;
                }
                responseProperty.Headers.Add(HttpResponseHeader.ContentType, outgoingContentType);
                responseProperty.Headers.Add(JsonGlobals.jsonerrorString, JsonGlobals.trueString);
                responseProperty.StatusCode = System.Net.HttpStatusCode.InternalServerError;

                object bodyFormatPropertyObject;
                if (fault.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatPropertyObject))
                {
                    WebBodyFormatMessageProperty bodyFormatProperty = bodyFormatPropertyObject as WebBodyFormatMessageProperty;
                    if ((bodyFormatProperty == null) ||
                        (bodyFormatProperty.Format != WebContentFormat.Json))
                    {
                        fault.Properties[WebBodyFormatMessageProperty.Name] = WebBodyFormatMessageProperty.JsonProperty;
                    }
                }
                else
                {
                    fault.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.JsonProperty);
                }
            }

            class JsonFaultBodyWriter : BodyWriter
            {
                JsonFaultDetail faultDetail;

                public JsonFaultBodyWriter(MessageFault fault, bool includeExceptionDetailInFaults)
                    : base(false)
                {
                    faultDetail = new JsonFaultDetail();
                    if (includeExceptionDetailInFaults)
                    {
                        faultDetail.Message = fault.Reason.ToString();
                        if (fault.HasDetail)
                        {
                            try
                            {
                                ExceptionDetail originalFaultDetail = fault.GetDetail<ExceptionDetail>();
                                faultDetail.StackTrace = originalFaultDetail.StackTrace;
                                faultDetail.ExceptionType = originalFaultDetail.Type;
                                faultDetail.ExceptionDetail = originalFaultDetail;
                            }
                            catch (SerializationException exception)
                            {
                                System.ServiceModel.DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
                                // A SerializationException will be thrown if the detail isn't of type ExceptionDetail
                                // In that case, we want to just move on.
                            }
                            catch (SecurityException exception)
                            {
                                System.ServiceModel.DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information);
                                // A SecurityException will be thrown if the detail can't be obtained in partial trust
                                // (This is guaranteed to happen unless there's an Assert for MemberAccessPermission, since ExceptionDetail
                                //     has DataMembers that have private setters.)
                                // In that case, we want to just move on.
                            }
                        }
                    }
                    else
                    {
                        faultDetail.Message = System.ServiceModel.SR.GetString(System.ServiceModel.SR.SFxInternalServerError);
                    }
                }

                protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
                {
                    jsonFaultSerializer.WriteObject(writer, faultDetail);
                }
            }
        }
    }
}