Пример #1
1
        //Can only be called inside a service
        public static void PromoteException(Exception error,MessageVersion version,ref Message fault)
        {
            StackFrame frame = new StackFrame(1);

             Type serviceType = frame.GetMethod().ReflectedType;
             PromoteException(serviceType,error,version,ref fault);
        }
Пример #2
0
        protected virtual Message GetJsonFaultMessage(MessageVersion version, Exception error)
        {
            BaseFault detail = null;
            var knownTypes = new List<Type>();
            string faultType = error.GetType().Name; //default

            if ((error is FaultException) &&
                (error.GetType().GetProperty("Detail") != null))
            {
                detail =
                    (error.GetType().GetProperty("Detail").GetGetMethod().Invoke(
                        error, null) as BaseFault);
                knownTypes.Add(detail.GetType());
                faultType = detail.GetType().Name;
            }

            var  jsonFault = new JsonFault
                             	{
                             		Message = error.Message,
                             		Detail = detail,
                             		FaultType = faultType
                             	};

            var faultMessage = Message.CreateMessage(version, "", jsonFault,
                                                     new DataContractJsonSerializer(jsonFault.GetType(), knownTypes));

            return faultMessage;
        }
Пример #3
0
        private IChannelFactory <IRequestSessionChannel> CreateChannelFactory(bool useSslStreamSecurity, bool includeExceptionDetails, DnsEndpointIdentity endpointIdentity)
        {
            string        str;
            int           num           = 0;
            CustomBinding customBinding = SbmpProtocolDefaults.CreateBinding(false, false, 2147483647, useSslStreamSecurity, endpointIdentity);
            DuplexRequestBindingElement duplexRequestBindingElement = new DuplexRequestBindingElement()
            {
                IncludeExceptionDetails = includeExceptionDetails,
                ClientMode = this.clientMode
            };
            DuplexRequestBindingElement duplexRequestBindingElement1 = duplexRequestBindingElement;
            int num1 = num;

            num = num1 + 1;
            customBinding.Elements.Insert(num1, duplexRequestBindingElement1);
            BindingParameterCollection bindingParameterCollection = new BindingParameterCollection();

            if (useSslStreamSecurity)
            {
                ClientCredentials clientCredential = new ClientCredentials();
                clientCredential.ServiceCertificate.Authentication.CertificateValidationMode  = X509CertificateValidationMode.Custom;
                clientCredential.ServiceCertificate.Authentication.CustomCertificateValidator = RetriableCertificateValidator.Instance;
                if (SoapProtocolDefaults.IsAvailableClientCertificateThumbprint(out str))
                {
                    clientCredential.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, str);
                }
                bindingParameterCollection.Add(clientCredential);
            }
            this.MessageVersion = customBinding.MessageVersion;
            return(customBinding.BuildChannelFactory <IRequestSessionChannel>(bindingParameterCollection));
        }
Пример #4
0
        public System.ServiceModel.Channels.Message SerializeReply(System.ServiceModel.Channels.MessageVersion messageVersion, object[] parameters, object result)
        {
            Message returnMessage = null;


            if (_compression && result != null)
            {
                XmlSerializer serializer = new XmlSerializer(result.GetType());

                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.Serialize(ms, result);

                    // Compress MemoryStream data and create message based on messageversion and action
                    returnMessage = Message.CreateMessage(messageVersion, _replyAction, Zip(ms.ToArray()));
                }
            }
            else
            {
                // Used defualt serialization
                returnMessage = _baseFormater.SerializeReply(messageVersion, parameters, result);
            }


            return(returnMessage);
        }
Пример #5
0
 public void ProvideFault(Exception error, c.MessageVersion version, ref c.Message fault)
 {
     if (error is FaultException)
     {
         return;
     }
 }
 void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
 {
     this.ErrorGuid = Guid.NewGuid();
     FaultException<ExceptionDetail> faultException = new FaultException<ExceptionDetail>(new ExceptionDetail(error) { Message = this.ErrorGuid.ToString() }, new FaultReason("ServiceError"));
     MessageFault messageFault = faultException.CreateMessageFault();
     fault = Message.CreateMessage(version, messageFault, faultException.Action);
 }
 //- @ProvideFault -//
 public virtual void ProvideFault(Exception error, MessageVersion version, ref Message fault)
 {
     fault.Properties[HttpResponseMessageProperty.Name] = new HttpResponseMessageProperty
                                                          {
                                                              StatusCode = HttpStatusCode.OK
                                                          };
 }
        public System.ServiceModel.Channels.Message SerializeReply(System.ServiceModel.Channels.MessageVersion messageVersion, object[] parameters, object result)
        {
            Message returnMessage = null;

            PerformanceMonitorHelper.GetDefaultMonitor().WriteExecutionDuration("SerializeReply", () =>
            {
                //返回值总是Raw格式的
                string jsonResult = string.Empty;

                if (result is string)
                {
                    if (this._AtlasEnabled)
                    {
                        //asp.net ajax 返回值格式
                        Dictionary <string, object> returnDict = new Dictionary <string, object>();
                        returnDict.Add("d", result);
                        jsonResult = JSONSerializerExecute.Serialize(returnDict);
                    }
                    else
                    {
                        jsonResult = result.ToString();
                    }
                }
                else
                {
                    jsonResult = JSONSerializerExecute.SerializeWithType(result);
                }

                returnMessage = WcfUtils.CreateJsonFormatReplyMessage(messageVersion, this._OperationDesc.Messages[1].Action, jsonResult);
            });

            return(returnMessage);
        }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            bool includeDetails = IncludeExceptionDetails();

            object msgId = null;
            if (OperationContext.Current.IncomingMessageProperties.ContainsKey(DispatcherUtils.MessageIdKey))
                msgId = OperationContext.Current.IncomingMessageProperties[DispatcherUtils.MessageIdKey];

            var jsonRpcError = error as JsonRpcException;
            if (jsonRpcError != null)
                fault = DispatcherUtils.CreateErrorMessage(version, msgId, jsonRpcError);
            else {
                // TODO: extract exception details from FaultException
                object additionalData;
                var faultException = error as FaultException;
                if (faultException != null && faultException.GetType().IsGenericType) {
                    additionalData = faultException.GetType().GetProperty("Detail").GetValue(faultException, null);
                } else {
                    additionalData = error;
                }

                // TODO: check error type and set appropriate error code
                fault = DispatcherUtils.CreateErrorMessage(version, msgId,
                    (int)JsonRpcErrorCodes.ServerError, error.Message, additionalData);
            }
        }
Пример #10
0
        /// <summary cref="IClientMessageFormatter.SerializeRequest" />
        public System.ServiceModel.Channels.Message SerializeRequest(System.ServiceModel.Channels.MessageVersion messageVersion, object[] parameters)
        {
            Message message = m_clientFormatter.SerializeRequest(messageVersion, parameters);

            message.Properties.Add(MessageProperties.RequestBody, parameters[0]);
            return(message);
        }
Пример #11
0
        internal ChannelHandler(MessageVersion messageVersion, IChannelBinder binder, ServiceChannel channel)
        {
            ClientRuntime clientRuntime = channel.ClientRuntime;

            this.messageVersion = messageVersion;
            this.isManualAddressing = clientRuntime.ManualAddressing;
            this.binder = binder;
            this.channel = channel;

            this.isConcurrent = true;
            this.duplexBinder = binder as DuplexChannelBinder;
            this.hasSession = binder.HasSession;
            this.isCallback = true;

            DispatchRuntime dispatchRuntime = clientRuntime.DispatchRuntime;
            if (dispatchRuntime == null)
            {
                this.receiver = new ErrorHandlingReceiver(binder, null);
            }
            else
            {
                this.receiver = new ErrorHandlingReceiver(binder, dispatchRuntime.ChannelDispatcher);
            }
            this.requestInfo = new RequestInfo(this);

        }
 public static CreateSequenceInfo ReadMessage(MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion, ISecureConversationSession securitySession, Message message, MessageHeaders headers)
 {
     CreateSequenceInfo info;
     if (message.IsEmpty)
     {
         string reason = System.ServiceModel.SR.GetString("NonEmptyWsrmMessageIsEmpty", new object[] { WsrmIndex.GetCreateSequenceActionString(reliableMessagingVersion) });
         Message faultReply = WsrmUtilities.CreateCSRefusedProtocolFault(messageVersion, reliableMessagingVersion, reason);
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WsrmMessageInfo.CreateInternalFaultException(faultReply, reason, new ProtocolException(reason)));
     }
     using (XmlDictionaryReader reader = message.GetReaderAtBodyContents())
     {
         info = CreateSequence.Create(messageVersion, reliableMessagingVersion, securitySession, reader);
         message.ReadFromBodyContentsToEnd(reader);
     }
     info.SetMessageId(messageVersion, headers);
     info.SetReplyTo(messageVersion, headers);
     if (info.AcksTo.Uri != info.ReplyTo.Uri)
     {
         string str2 = System.ServiceModel.SR.GetString("CSRefusedAcksToMustEqualReplyTo");
         Message message3 = WsrmUtilities.CreateCSRefusedProtocolFault(messageVersion, reliableMessagingVersion, str2);
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WsrmMessageInfo.CreateInternalFaultException(message3, str2, new ProtocolException(str2)));
     }
     info.to = message.Headers.To;
     if ((info.to == null) && (messageVersion.Addressing == AddressingVersion.WSAddressing10))
     {
         info.to = messageVersion.Addressing.AnonymousUri;
     }
     return info;
 }
 protected override IChannelFactory<IRequestReplyService> SelectChannelFactory(out MessageVersion messageVersion)
 {
     base.interoperating = false;
     EndpointIdentity identity = base.to.Identity;
     if (identity != null)
     {
         string claimType = identity.IdentityClaim.ClaimType;
         if ((claimType != ClaimTypes.Spn) && (claimType != ClaimTypes.Upn))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CreateChannelFailureException(Microsoft.Transactions.SR.GetString("InvalidTrustIdentityType", new object[] { claimType })));
         }
     }
     string scheme = base.to.Uri.Scheme;
     if (string.Compare(scheme, Uri.UriSchemeNetPipe, StringComparison.OrdinalIgnoreCase) == 0)
     {
         messageVersion = base.coordinationService.NamedPipeActivationBinding.MessageVersion;
         return base.coordinationService.NamedPipeActivationChannelFactory;
     }
     if (!base.coordinationService.Config.RemoteClientsEnabled || (string.Compare(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) != 0))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CreateChannelFailureException(Microsoft.Transactions.SR.GetString("InvalidSchemeWithTrustIdentity", new object[] { scheme })));
     }
     messageVersion = base.coordinationService.WindowsActivationBinding.MessageVersion;
     return base.coordinationService.WindowsActivationChannelFactory;
 }
Пример #14
0
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            var faultEx = new FaultException <ApiFault>(new ApiFault(error.Message), new FaultReason(error.Message));

            fault = Message.CreateMessage(version, faultEx.CreateMessageFault(), "error");

            fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Xml));

            WebOperationContext.Current.OutgoingResponse.StatusDescription = error.Message;
            //WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;

            // specal hack to prevent forms auth redirection
            var code = error is ApiException ? ((ApiException)error).StatusCode : System.Net.HttpStatusCode.InternalServerError;

            if (error is System.Runtime.Serialization.SerializationException)
            {
                code = HttpStatusCode.BadRequest;
            }

            WebOperationContext.Current.OutgoingResponse.StatusCode = code == HttpStatusCode.Unauthorized ? HttpStatusCode.Unauthorized : code;
            if (error is ApiException)
            {
                WebOperationContext.Current.OutgoingResponse.Headers["error_id"] = ((ApiException)error).ErrorId;
            }
        }
 internal CustomTextMessageEncoderFactory(string mediaType, string charSet, MessageVersion version)
 {
     _version = version;
     _mediaType = mediaType;
     _charSet = charSet;
     _encoder = new CustomTextMessageEncoder(this);
 }
Пример #16
0
 internal ErrorBehavior(ChannelDispatcher channelDispatcher)
 {
     this.handlers = EmptyArray<IErrorHandler>.ToArray(channelDispatcher.ErrorHandlers);
     this.debug = channelDispatcher.IncludeExceptionDetailInFaults;
     this.isOnServer = channelDispatcher.IsOnServer;
     this.messageVersion = channelDispatcher.MessageVersion;
 }
Пример #17
0
        protected TransportChannelFactory(TransportBindingElement bindingElement, BindingContext context, System.ServiceModel.Channels.MessageEncoderFactory defaultMessageEncoderFactory) : base(context.Binding)
        {
            this.manualAddressing       = bindingElement.ManualAddressing;
            this.maxBufferPoolSize      = bindingElement.MaxBufferPoolSize;
            this.maxReceivedMessageSize = bindingElement.MaxReceivedMessageSize;
            Collection <MessageEncodingBindingElement> messageEncodingBindingElements = context.BindingParameters.FindAll <MessageEncodingBindingElement>();

            if (messageEncodingBindingElements.Count > 1)
            {
                throw Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(Microsoft.ServiceBus.SR.GetString(Resources.MultipleMebesInParameters, new object[0])));
            }
            if (messageEncodingBindingElements.Count != 1)
            {
                this.messageEncoderFactory = defaultMessageEncoderFactory;
            }
            else
            {
                this.messageEncoderFactory = messageEncodingBindingElements[0].CreateMessageEncoderFactory();
                context.BindingParameters.Remove <MessageEncodingBindingElement>();
            }
            if (this.messageEncoderFactory == null)
            {
                this.messageVersion = System.ServiceModel.Channels.MessageVersion.None;
                return;
            }
            this.messageVersion = this.messageEncoderFactory.MessageVersion;
        }
Пример #18
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            Contract.Requires<NullReferenceException>(error != null);

            FaultCode code = FaultCode.CreateSenderFaultCode(error.GetType().Name, FaultNs);
            fault = Message.CreateMessage(version, code, error.Message, null);

        if (this.Context != null)
        {
            var se = error as ServiceException;
            if (se != null)
            {
                Context.OutgoingResponse.StatusCode = ((ServiceException)error).StatusCode;
            }

            var sb = new StringBuilder();

            for (int i = 0; i < error.Message.Length; i++)
            {
                var ch = (char)('\x00ff' & error.Message[i]);
                if (((ch <= '\x001f') && (ch != '\t')) || (ch == '\x007f'))
                {
                    // Specified value has invalid Control characters.
                    // See HttpListenerResponse.StatusDescription implementation.
                }
                else
                {
                    sb.Append(ch);
                }
            }

            Context.OutgoingResponse.StatusDescription = sb.ToString();
            Context.OutgoingResponse.SuppressEntityBody = false;
            }
        }
Пример #19
0
 public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
 {
     JObject json = new JObject();
     json[JsonRpcConstants.ErrorKey] = null;
     json[JsonRpcConstants.ResultKey] = JToken.FromObject(result);
     return JsonRpcHelpers.SerializeMessage(json, null);
 }
 public Message CreateMessage(MessageVersion messageVersion, ReliableMessagingVersion reliableMessagingVersion)
 {
     this.SetReliableMessagingVersion(reliableMessagingVersion);
     string faultActionString = WsrmIndex.GetFaultActionString(messageVersion.Addressing, reliableMessagingVersion);
     if (messageVersion.Envelope == EnvelopeVersion.Soap11)
     {
         this.code = this.Get11Code(this.code, this.subcode);
     }
     else
     {
         if (messageVersion.Envelope != EnvelopeVersion.Soap12)
         {
             throw Fx.AssertAndThrow("Unsupported MessageVersion.");
         }
         if (this.code.SubCode == null)
         {
             FaultCode subCode = new FaultCode(this.subcode, WsrmIndex.GetNamespaceString(reliableMessagingVersion));
             this.code = new FaultCode(this.code.Name, this.code.Namespace, subCode);
         }
         this.hasDetail = this.Get12HasDetail();
     }
     Message message = Message.CreateMessage(messageVersion, this, faultActionString);
     this.OnFaultMessageCreated(messageVersion, message);
     return message;
 }
        /// <summary>
        /// Serializes a reply message from a specified message version, array of parameters, and a return value.
        /// </summary>
        /// <param name="messageVersion">The SOAP message version.</param>
        /// <param name="parameters">The out parameters.</param>
        /// <param name="result">The return value.</param>
        /// <returns>he serialized reply message.</returns>
        Message IDispatchMessageFormatter.SerializeReply(
            MessageVersion messageVersion,
            object[] parameters,
            object result)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            if (messageVersion != MessageVersion.None)
            {
                throw new NotSupportedException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        SR.HttpMessageFormatterMessageVersion,
                        this.GetType()));
            }

            HttpResponseMessage response = this.GetDefaultResponse();
            if (response == null)
            {
                 throw new InvalidOperationException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        SR.HttpMessageFormatterNullResponse,
                        this.GetType()));
            }

            this.SerializeReply(parameters, result, response);

            return response.ToMessage();
        }
 /// <summary>
 /// Serializes a reply message from a specified message version, array of parameters, and a return value.
 /// </summary>
 /// <param name="messageVersion">The SOAP message version.</param>
 /// <param name="parameters">The out parameters.</param>
 /// <param name="result">The return value.</param>
 /// <returns>The serialized reply message.</returns>
 public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
 {
     // Instantiate a new domain data service and ask it to process the incoming request.
     // We already have the result of the invocation handy, so we can simply pass it to
     // the IDSP implementation for domain data service.
     return this.serviceFactory.CreateService(result).ProcessRequestForMessage(new MemoryStream());
 }
        public RelayedOnewayChannelListener(BindingContext context, RelayedOnewayTransportBindingElement transportBindingElement) : base(context.Binding)
        {
            this.nameSettings = context.BindingParameters.Find <Microsoft.ServiceBus.NameSettings>();
            if (this.nameSettings == null)
            {
                this.nameSettings = new Microsoft.ServiceBus.NameSettings();
                this.nameSettings.ServiceSettings.ListenerType = ListenerType.Unicast;
            }
            this.scheme         = context.Binding.Scheme;
            this.messageVersion = context.Binding.MessageVersion;
            switch (context.ListenUriMode)
            {
            case ListenUriMode.Explicit:
            {
                this.SetUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
                break;
            }

            case ListenUriMode.Unique:
            {
                this.SetUniqueUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
                break;
            }
            }
            this.channel  = new RelayedOnewayChannelListener.RelayedOnewayInputChannel(this, new EndpointAddress(this.Uri, new AddressHeader[0]));
            base.Acceptor = new Microsoft.ServiceBus.Channels.InputChannelAcceptor(this, () => this.GetPendingException());
            this.ChannelAcceptor.EnqueueAndDispatch(this.channel, new Action(this.OnChannelDequeued));
            this.connection = RelayedOnewayManager.RegisterListener(context, transportBindingElement, this);
        }
 public BufferedHeader(MessageVersion version, XmlBuffer buffer, XmlDictionaryReader reader, XmlAttributeHolder[] envelopeAttributes, XmlAttributeHolder[] headerAttributes)
 {
     this.streamed = true;
     this.buffer = buffer;
     this.version = version;
     MessageHeader.GetHeaderAttributes(reader, version, out this.actor, out this.mustUnderstand, out this.relay, out this.isRefParam);
     this.name = reader.LocalName;
     this.ns = reader.NamespaceURI;
     this.bufferIndex = buffer.SectionCount;
     XmlDictionaryWriter writer = buffer.OpenSection(reader.Quotas);
     writer.WriteStartElement("Envelope");
     if (envelopeAttributes != null)
     {
         XmlAttributeHolder.WriteAttributes(envelopeAttributes, writer);
     }
     writer.WriteStartElement("Header");
     if (headerAttributes != null)
     {
         XmlAttributeHolder.WriteAttributes(headerAttributes, writer);
     }
     writer.WriteNode(reader, false);
     writer.WriteEndElement();
     writer.WriteEndElement();
     buffer.CloseSection();
 }
Пример #25
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            FaultException faultException;
            var logger = LogManager.GetCurrentClassLogger();

            if (error != null && error is ObjectValidationException)
            {
                faultException = new FaultException<ValidationFault>(new ValidationFault(((ObjectValidationException)error).ValidationErrors.Select(item =>
                    new ValidationError
                    {
                        ErrorMessage = item.ErrorMessage,
                        ObjectName = item.ObjectName,
                        PropertyName = item.PropertyName
                    })), new FaultReason("Validation error"));

                logger.Error(error, "Validation error in GlobalError filter");
            }
            else
            {
                faultException = new FaultException<InternalServiceFault>(new InternalServiceFault(error,
                string.Format("Exception caught at GlobalErrorHandler{0}Method: {1}{2}Message:{3}",
                             Environment.NewLine, error.TargetSite.Name, Environment.NewLine, error.Message)));

                logger.Error(error, "Generic internal error in GlobalError filter");
            }
            // Shield the unknown exception
            //FaultException faultException = new FaultException<SimpleErrorFault>(new SimpleErrorFault(), new FaultReason("Server error encountered. All details have been logged."));
            //new FaultException("Server error encountered. All details have been logged.");
            MessageFault messageFault = faultException.CreateMessageFault();

            fault = Message.CreateMessage(version, messageFault, faultException.Action);
        }
Пример #26
0
        public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
        {
            MemoryStream outStream = new MemoryStream();
            StreamWriter writer = new StreamWriter(outStream);
            writer.WriteLine("--" + Boundary);
            writer.WriteLine("Content-Disposition: form-data; name=\"torrent_file\"; filename=\"foo.torrent\"");
            writer.WriteLine("Content-Type: ");
            writer.WriteLine();
            writer.Flush();
            (parameters[0] as Stream).CopyTo(outStream);
            writer.WriteLine();
            writer.WriteLine("--" + Boundary + "--");
            writer.Flush();

            outStream.Seek(0, SeekOrigin.Begin);
            parameters[0] = outStream;

            Message request = this.originalFormatter.SerializeRequest(messageVersion, parameters);

            if (!request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
            {
                request.Properties[HttpRequestMessageProperty.Name] = new HttpRequestMessageProperty();
            }

            HttpRequestMessageProperty http = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            http.Headers.Set(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + Boundary);
            http.Headers.Remove(HttpRequestHeader.Expect);

            return request;
        }
Пример #27
0
        /// <summary>
        /// Enables the creation of a custom System.ServiceModel.FaultException{TDetail}
        /// that is returned from an exception in the course of a service method.
        /// </summary>
        /// <param name="error">The System.Exception object thrown in the course of the service operation.</param>
        /// <param name="version">The SOAP version of the message.</param>
        /// <param name="fault">The System.ServiceModel.Channels.Message object that is returned to the client, or service in duplex case</param>
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            if (error is FaultException <ApplicationServiceError> )
            {
                MessageFault messageFault = ((FaultException <ApplicationServiceError>)error).CreateMessageFault();

                //propagate FaultException
                fault = Message.CreateMessage(version, messageFault, ((FaultException <ApplicationServiceError>)error).Action);
            }
            else
            {
                //create service error
                ApplicationServiceError defaultError = new ApplicationServiceError()
                {
                    ErrorMessage = Resources.Messages.message_DefaultErrorMessage
                };

                //Create fault exception and message fault
                FaultException <ApplicationServiceError> defaultFaultException = new FaultException <ApplicationServiceError>(defaultError);
                MessageFault defaultMessageFault = defaultFaultException.CreateMessageFault();

                //propagate FaultException
                fault = Message.CreateMessage(version, defaultMessageFault, defaultFaultException.Action);
            }
        }
Пример #28
0
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            // Tell WCF to use JSON encoding rather than default XML
            var webBodyFormatProperty = new WebBodyFormatMessageProperty(WebContentFormat.Json);
            var responseProperty      = new HttpResponseMessageProperty();

            responseProperty.Headers.Add(HttpResponseHeader.ContentType, "application/json");

            if (error is FaultException)
            {
                // Extract the FaultContract object from the exception object.
                var detail = error.GetType().GetProperty("Detail").GetGetMethod().Invoke(error, null);

                // Return custom error http response.
                responseProperty.StatusCode = System.Net.HttpStatusCode.Unauthorized;

                // Create a fault message containing our FaultContract object
                fault = Message.CreateMessage(version, "", detail, new DataContractJsonSerializer(detail.GetType()));
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, webBodyFormatProperty);
                fault.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
            }
            else
            {
                // Return custom error http response.
                responseProperty.StatusCode = System.Net.HttpStatusCode.InternalServerError;

                var detail = error.Message;

                fault = Message.CreateMessage(version, "", detail, new DataContractJsonSerializer(typeof(string)));
                fault.Properties.Add(WebBodyFormatMessageProperty.Name, webBodyFormatProperty);
                fault.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
            }
        }
            public void ProvideFault(Exception exception, MessageVersion version, ref Message fault)
            {
                if (exception.GetType() == typeof(HttpException))
                {
                    var httpException = (HttpException)exception;

                    var inResponse = WebOperationContext.Current.IncomingRequest;

                    var webGetAttribute = GetCurrentAttribute(inResponse);
                    
                    if(webGetAttribute == null)
                    {
                        throw new RestException();    
                    }

                    var currentResponseFormat = webGetAttribute.ResponseFormat;

                    var restErrorMessage = new RestErrorMessage(httpException.Data, httpException.GetHttpCode(), httpException.ErrorCode);
                    fault = CreateMessage(restErrorMessage, version, currentResponseFormat);
                    fault.Properties.Add(WebBodyFormatMessageProperty.Name, GetBodyFormat(currentResponseFormat));

                    var outResponse = WebOperationContext.Current.OutgoingResponse;
                    outResponse.StatusCode = (HttpStatusCode)httpException.GetHttpCode();
                    outResponse.ContentType = string.Format("application/{0}", currentResponseFormat);
                }
                else
                {
                    throw new RestException();
                }
            }
Пример #30
0
        public void ProvideFault(Exception error, MessageVersion version,ref Message fault)
        {
            fault = this.GetJsonFaultMessage(version, error);

            this.ApplyJsonSettings(ref fault);
            this.ApplyHttpResponseSettings(ref fault, System.Net.HttpStatusCode.BadRequest, "status desrckslndf");
        }
 internal Message ProvideFault(MessageVersion messageVersion)
 {
     WSAddressing10ProblemHeaderQNameFault fault = new WSAddressing10ProblemHeaderQNameFault(this);
     Message message = Message.CreateMessage(messageVersion, fault, messageVersion.Addressing.FaultAction);
     fault.AddHeaders(message.Headers);
     return message;
 }
Пример #32
0
      /// <summary>
      ///    Enables the creation of a custom System.ServiceModel.FaultException{TDetail}
      ///    that is returned from an exception in the course of a service method.
      /// </summary>
      /// <param name="error">The System.Exception object thrown in the course of the service operation.</param>
      /// <param name="version">The SOAP version of the message.</param>
      /// <param name="fault">
      ///    The System.ServiceModel.Channels.Message object that is returned to the client, or service in
      ///    duplex case
      /// </param>
      public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
      {
         if (error is FaultException<ApplicationServiceError>)
         {
            var messageFault = ((FaultException<ApplicationServiceError>) error).CreateMessageFault();

            //propagate FaultException
            fault = Message.CreateMessage(
               version,
               messageFault,
               ((FaultException<ApplicationServiceError>) error).Action);
         }
         else
         {
            //create service error
            var defaultError = new ApplicationServiceError()
            {
               ErrorMessage = Messages.message_DefaultErrorMessage
            };

            //Create fault exception and message fault
            var defaultFaultException = new FaultException<ApplicationServiceError>(defaultError);
            var defaultMessageFault = defaultFaultException.CreateMessageFault();

            //propagate FaultException
            fault = Message.CreateMessage(version, defaultMessageFault, defaultFaultException.Action);
         }
      }
 public IssuedTokensHeader(XmlReader xmlReader, MessageVersion version, SecurityStandardsManager standardsManager)
     : base()
 {
     if (xmlReader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("xmlReader");
     }
     if (standardsManager == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("standardsManager"));
     }
     this.standardsManager = standardsManager;
     XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(xmlReader);
     MessageHeader.GetHeaderAttributes(reader, version, out this.actor, out this.mustUnderstand, out this.relay, out this.isRefParam);
     reader.ReadStartElement(this.Name, this.Namespace);
     Collection<RequestSecurityTokenResponse> coll = new Collection<RequestSecurityTokenResponse>();
     if (this.standardsManager.TrustDriver.IsAtRequestSecurityTokenResponseCollection(reader))
     {
         RequestSecurityTokenResponseCollection rstrColl = this.standardsManager.TrustDriver.CreateRequestSecurityTokenResponseCollection(reader);
         foreach (RequestSecurityTokenResponse rstr in rstrColl.RstrCollection)
         {
             coll.Add(rstr);
         }
     }
     else
     {
         RequestSecurityTokenResponse rstr = this.standardsManager.TrustDriver.CreateRequestSecurityTokenResponse(reader);
         coll.Add(rstr);
     }
     this.tokenIssuances = new ReadOnlyCollection<RequestSecurityTokenResponse>(coll);
     reader.ReadEndElement();
 }
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            WebOperationContext currentContext = WebOperationContext.Current;
            OutgoingWebResponseContext outgoingResponse = null;

            if (currentContext != null)
            {
                outgoingResponse = currentContext.OutgoingResponse;
            }
            
            WebMessageFormat format = this.defaultFormat;
            if (outgoingResponse != null)
            {
                WebMessageFormat? nullableFormat = outgoingResponse.Format;
                if (nullableFormat.HasValue)
                {
                    format = nullableFormat.Value;
                }
            }

            if (!this.formatters.ContainsKey(format))
            {
                string operationName = "<null>";

                if (OperationContext.Current != null)
                {
                    MessageProperties messageProperties = OperationContext.Current.IncomingMessageProperties;
                    if (messageProperties.ContainsKey(WebHttpDispatchOperationSelector.HttpOperationNamePropertyName))
                    {
                        operationName = messageProperties[WebHttpDispatchOperationSelector.HttpOperationNamePropertyName] as string;
                    }
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR2.GetString(SR2.OperationDoesNotSupportFormat, operationName, format.ToString())));
            }

            if (outgoingResponse != null && string.IsNullOrEmpty(outgoingResponse.ContentType))
            {
                string automatedSelectionContentType = outgoingResponse.AutomatedFormatSelectionContentType;
                if (!string.IsNullOrEmpty(automatedSelectionContentType))
                {
                    // Don't set the content-type if it is default xml for backwards compatiabilty
                    if (!string.Equals(automatedSelectionContentType, defaultContentTypes[WebMessageFormat.Xml], StringComparison.OrdinalIgnoreCase))
                    {
                        outgoingResponse.ContentType = automatedSelectionContentType;
                    }
                }
                else
                {
                    // Don't set the content-type if it is default xml for backwards compatiabilty
                    if (format != WebMessageFormat.Xml)
                    {
                        outgoingResponse.ContentType = defaultContentTypes[format];
                    }
                }
            }

            Message message = this.formatters[format].SerializeReply(messageVersion, parameters, result);

            return message;
        }
Пример #35
0
        /// <summary>
        /// Enables the creation of a custom <see cref="System.ServiceModel.FaultException"/>
        /// that is returned from an exception in the course of a service method.
        /// </summary>
        /// <param name="error"></param>
        /// <param name="version"></param>
        /// <param name="faultMessage"></param>
        public void ProvideFault(Exception error, MessageVersion version, ref Message faultMessage)
        {
            // Gets a serializable Fault object fromn error.
            Fault fault = Fault.GetFault(error);

            // Now we make the message by serializing the Fault to JSON.
            faultMessage = Message.CreateMessage(version, null, fault,
              new DataContractJsonSerializer(fault.GetType()));

            // Gotta set HTTP status codes.
            HttpResponseMessageProperty prop = new HttpResponseMessageProperty()
            {
                StatusCode = HttpStatusCode.InternalServerError, // 500
                StatusDescription = "An internal server error occurred." // Could use elaboration.
            };

            // Make sure to set the content type. Important for avoiding
            // certain kinds of encoding-specific XSS attacks.
            prop.Headers[HttpResponseHeader.ContentType] = "application/json; charset=utf-8";

            // Set a few other properties of the Message.
            faultMessage.Properties.Add(HttpResponseMessageProperty.Name, prop);
            faultMessage.Properties.Add(WebBodyFormatMessageProperty.Name,
                new WebBodyFormatMessageProperty(WebContentFormat.Json));
        }
		protected virtual void OnImportPolicy (XmlElement assertion,
			MessageVersion messageVersion,
			MetadataImporter exporter,
			PolicyConversionContext context)
		{
			throw new NotImplementedException ();
		}
Пример #37
0
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            var newEx = new FaultException(string.Format("服务端错误 {0}", error.TargetSite.Name));
            MessageFault msgFault = newEx.CreateMessageFault();

            fault = Message.CreateMessage(version, msgFault, newEx.Action);
        }
 internal static IListenerBinder GetBinder(IChannelListener listener, MessageVersion messageVersion)
 {
     IChannelListener<IInputChannel> listener2 = listener as IChannelListener<IInputChannel>;
     if (listener2 != null)
     {
         return new InputListenerBinder(listener2, messageVersion);
     }
     IChannelListener<IInputSessionChannel> listener3 = listener as IChannelListener<IInputSessionChannel>;
     if (listener3 != null)
     {
         return new InputSessionListenerBinder(listener3, messageVersion);
     }
     IChannelListener<IReplyChannel> listener4 = listener as IChannelListener<IReplyChannel>;
     if (listener4 != null)
     {
         return new ReplyListenerBinder(listener4, messageVersion);
     }
     IChannelListener<IReplySessionChannel> listener5 = listener as IChannelListener<IReplySessionChannel>;
     if (listener5 != null)
     {
         return new ReplySessionListenerBinder(listener5, messageVersion);
     }
     IChannelListener<IDuplexChannel> listener6 = listener as IChannelListener<IDuplexChannel>;
     if (listener6 != null)
     {
         return new DuplexListenerBinder(listener6, messageVersion);
     }
     IChannelListener<IDuplexSessionChannel> listener7 = listener as IChannelListener<IDuplexSessionChannel>;
     if (listener7 == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("UnknownListenerType1", new object[] { listener.Uri.AbsoluteUri })));
     }
     return new DuplexSessionListenerBinder(listener7, messageVersion);
 }
Пример #39
0
        public void ProvideFault(
            Exception error,
            MessageVersion version,
            ref Message fault)
        {
            if (error is WebFaultException)
                return;

            object responseMessage;
            HttpStatusCode responseStatusCode;
            if (error is UserException || error is ClientException)
            {
                responseStatusCode = HttpStatusCode.BadRequest;
                responseMessage = error.Message;
            }
            else
            {
                responseStatusCode = HttpStatusCode.InternalServerError;
                responseMessage = "Internal server error occurred (" + error.GetType().Name + "). See RhetosServer.log for more information.";
            }

            fault = Message.CreateMessage(version, "", responseMessage,
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(responseMessage.GetType()));

            fault.Properties.Add(WebBodyFormatMessageProperty.Name,
                new WebBodyFormatMessageProperty(WebContentFormat.Json));

            fault.Properties.Add(HttpResponseMessageProperty.Name,
                new HttpResponseMessageProperty {StatusCode = responseStatusCode});

            var response = WebOperationContext.Current.OutgoingResponse;
            response.ContentType = "application/json";
            response.StatusCode = responseStatusCode;
        }
Пример #40
0
        internal static IListenerBinder GetBinder(IChannelListener listener, MessageVersion messageVersion)
        {
            IChannelListener<IInputChannel> input = listener as IChannelListener<IInputChannel>;
            if (input != null)
                return new InputListenerBinder(input, messageVersion);

            IChannelListener<IInputSessionChannel> inputSession = listener as IChannelListener<IInputSessionChannel>;
            if (inputSession != null)
                return new InputSessionListenerBinder(inputSession, messageVersion);

            IChannelListener<IReplyChannel> reply = listener as IChannelListener<IReplyChannel>;
            if (reply != null)
                return new ReplyListenerBinder(reply, messageVersion);

            IChannelListener<IReplySessionChannel> replySession = listener as IChannelListener<IReplySessionChannel>;
            if (replySession != null)
                return new ReplySessionListenerBinder(replySession, messageVersion);

            IChannelListener<IDuplexChannel> duplex = listener as IChannelListener<IDuplexChannel>;
            if (duplex != null)
                return new DuplexListenerBinder(duplex, messageVersion);

            IChannelListener<IDuplexSessionChannel> duplexSession = listener as IChannelListener<IDuplexSessionChannel>;
            if (duplexSession != null)
                return new DuplexSessionListenerBinder(duplexSession, messageVersion);

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UnknownListenerType1, listener.Uri.AbsoluteUri)));
        }
Пример #41
0
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            string errName = string.Format("调用 {0} 时异常", OperationContext.Current.IncomingMessageProperties["HttpOperationName"]);

            WfErrorDTO errorDTO = new WfErrorDTO()
            {
                Number      = 100,
                Name        = errName,
                Message     = error.Message,
                Description = error.StackTrace
            };

            string jsonResult = string.Empty;

            try
            {
                jsonResult = JSONSerializerExecute.SerializeWithType(errorDTO);
            }
            catch (InvalidOperationException)
            {
                errorDTO.Description = string.Empty;
                jsonResult           = JSONSerializerExecute.SerializeWithType(errorDTO);
            }

            fault = WcfUtils.CreateJsonFormatReplyMessage(version, null, jsonResult);
        }
Пример #42
0
        public void ProvideFault(System.Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message message)
        {
            var fault = new Fault();

            if (error is FaultException)
            {
                // extract the our FaultContract object from the exception object.
                var detail = error.GetType().GetProperty("Detail").GetGetMethod().Invoke(error, null);

                // create a fault message containing our FaultContract object
                message = Message.CreateMessage(version, "", detail, new DataContractJsonSerializer(detail.GetType()));

                // tell WCF to use JSON encoding rather than default XML
                var wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json);

                message.Properties.Add(WebBodyFormatMessageProperty.Name, wbf);

                // return custom error code.
                var rmp = new HttpResponseMessageProperty();
                rmp.StatusCode = System.Net.HttpStatusCode.BadRequest;

                // put appropraite description here..
                rmp.StatusDescription = "See fault object for more information.";

                message.Properties.Add(HttpResponseMessageProperty.Name, rmp);
            }
            else if (error is SerializationException)
            {
                fault.Error = error.Message;
                fault.Error = "Could not decode request: JSON parsing failed";
                toJson(fault, ref message);
            }
        }
Пример #43
0
 public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
 {
     if (error == null)
     {
         return;
     }
     ErrorLog.GetDefault(null).Log(new Elmah.Error(error));
 }
Пример #44
0
 public SocketConnectionChannelFactory(SocketConnectionBindingElement bindingElement, BindingContext context, bool enableKeepAlive) : base(bindingElement, context, bindingElement.ConnectionPoolSettings.GroupName, bindingElement.ConnectionPoolSettings.IdleTimeout, bindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint)
 {
     this.enableKeepAlive      = enableKeepAlive;
     this.connectionElement    = bindingElement.ConnectionElement;
     this.leaseTimeout         = bindingElement.ConnectionPoolSettings.LeaseTimeout;
     this.messageVersion       = context.Binding.MessageVersion;
     this.securityCapabilities = bindingElement.GetProperty <ISecurityCapabilities>(context);
 }
Пример #45
0
 public DuplexSessionChannel(ChannelManagerBase channelManager, IDuplexSessionChannel innerChannel, System.ServiceModel.Channels.MessageVersion messageVersion, bool enableKeepAlive) : base(channelManager, innerChannel)
 {
     this.innerChannel    = innerChannel;
     this.messageVersion  = messageVersion;
     this.enableKeepAlive = enableKeepAlive;
     this.pingTimer       = new IOThreadTimer(SocketConnectionChannelFactory <TChannel> .DuplexSessionChannel.pingCallbackStatic, this, false);
     this.suppressPing    = false;
 }
Пример #46
0
 public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
 {
     if (!(error is FaultException))
     {
         FaultException FE = new FaultException("We apologize for the inconvenience, an error occurred while processing your request.");
         MessageFault   MF = FE.CreateMessageFault();
         fault = Message.CreateMessage(version, MF, null);
     }
 }
Пример #47
0
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            MessageResponse messageResponseError = new MessageResponse(error);

            FaultException <MessageResponse> faultException = new FaultException <MessageResponse>(messageResponseError);

            MessageFault messageFault = faultException.CreateMessageFault();

            fault = Message.CreateMessage(version, messageFault, null);
        }
Пример #48
0
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            if (error is FaultException)
            {
                return;
            }

            var er = new FaultException(error.Message, new FaultCode("ServerException"));

            fault = Message.CreateMessage(version, er.CreateMessageFault(), "Error occured on server");
        }
        /// <summary>
        /// If you want to communicate the exception details to the service client
        /// as proper fault message
        /// here is the place to do it
        /// If we want to suppress the communication about the exception,
        /// set fault to null
        /// </summary>
        /// <param name="error"></param>
        /// <param name="version"></param>
        /// <param name="fault"></param>
        public void ProvideFault(Exception error,
                                 System.ServiceModel.Channels.MessageVersion version,
                                 ref System.ServiceModel.Channels.Message fault)
        {
            var newEx = new FaultException(
                $"Exception caught at Service Application GlobalErrorHandler{Environment.NewLine}Method: {error.TargetSite.Name}{Environment.NewLine}Message: {error.Message}");

            MessageFault msgFault = newEx.CreateMessageFault();

            fault = Message.CreateMessage(version, msgFault, newEx.Action);
        }
Пример #50
0
        /// <summary>
        /// Provides the error message back to the client through the message provider.
        /// </summary>
        /// <param name="error">The current error that has occured.</param>
        /// <param name="version">The SOAP message version.</param>
        /// <param name="fault">The communication channel between the client and server,
        /// sends the message with the error to the client.</param>
        public void ProvideFault(Exception error,
                                 System.ServiceModel.Channels.MessageVersion version,
                                 ref System.ServiceModel.Channels.Message fault)
        {
            // Construct the fault message to send to
            // the client.
            FaultException faultException = new FaultException(error.Message);
            MessageFault   messageFault   = faultException.CreateMessageFault();

            fault = System.ServiceModel.Channels.Message.CreateMessage(version, messageFault, faultException.Action);
        }
Пример #51
0
 /// <summary>
 /// ProvideFault
 /// </summary>
 /// <param name="exception"></param>
 /// <param name="version"></param>
 /// <param name="fault"></param>
 public void ProvideFault(Exception exception, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
 {
     //Propogate the exception back to the client.
     //if (exception is FaultException)
     //	return;
     //else
     //{
     //    FaultException faultException = new FaultException(exception.Message);
     //    MessageFault messageFault = faultException.CreateMessageFault();
     //    fault = Message.CreateMessage(version, messageFault, faultException.Action);
     //}
 }
Пример #52
0
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            if (error is FaultException)
            {
                return;
            }
            FaultException fe = new FaultException("A General service error has occured");

            System.ServiceModel.Channels.MessageFault mf = fe.CreateMessageFault();
            fault = Message.CreateMessage(version, mf, null);
            //throw new NotImplementedException();
        }
Пример #53
0
        /// <summary>
        /// 自定义消息错误处理
        /// </summary>
        /// <param name="error"></param>
        /// <param name="version"></param>
        /// <param name="fault"></param>
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            ///全局错误日志记录
            //string.Format("ERROR:{0}\r\n引起异常方法:{1}\r\n详细:{2}",
            //    OperationContext.Current.IncomingMessageHeaders.Action.ToString(),
            //    error.TargetSite.Name, error.Message).WriteLog("SystemErrorLog");

            var          newEx    = new FaultException(string.Format("ERROR:{0} ", error.Message));
            MessageFault msgFault = newEx.CreateMessageFault();

            fault = Message.CreateMessage(version, msgFault, newEx.Action);
        }
Пример #54
0
        /// <summary>
        /// If you want to communicate the exception details to the service client
        /// as proper fault message
        /// here is the place to do it
        /// If we want to suppress the communication about the exception,
        /// set fault to null
        /// </summary>
        /// <param name="error"></param>
        /// <param name="version"></param>
        /// <param name="fault"></param>
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            FaultException newEx = null;

            newEx = new FaultException(
                string.Format("Exception caught at Service Application GlobalErrorHandler{0}Method: {1} {2} Message: {3}",
                              Environment.NewLine, error.TargetSite.Name,
                              Environment.NewLine, error.Message));

            MessageFault msgFault = newEx.CreateMessageFault();

            fault = Message.CreateMessage(version, msgFault, newEx.Action);
        }
Пример #55
0
 public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
 {
     if (error is FaultException)
     {
         // Let WCF do normal processing
     }
     else
     {
         // Generate fault message manually including the exception as the fault detail
         MessageFault messageFault = MessageFault.CreateFault(new FaultCode("Sender"), new FaultReason(error.Message), error, new NetDataContractSerializer());
         fault = Message.CreateMessage(version, messageFault, null);
     }
 }
Пример #56
0
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            if (fault == null)
            {
                if (error is ConfigurationErrorsException)
                {
                    FaultException <ReceiverFaultDetail> fe = new FaultException <ReceiverFaultDetail>(new ReceiverFaultDetail(error.Message, true), error.Message, FaultCode.CreateReceiverFaultCode(new FaultCode("Configuration")));
                    MessageFault mf = fe.CreateMessageFault();

                    fault = Message.CreateMessage(version, mf, fe.Action);
                }
            }
        }
Пример #57
0
        public void ProvideFault(Exception error,
                                 System.ServiceModel.Channels.MessageVersion version,
                                 ref System.ServiceModel.Channels.Message fault)
        {
            if (error is FaultException)
            {
                return;
            }

            // Return a general service error message to the client
            FaultException faultException = new FaultException("A general service error occured");
            MessageFault   messageFault   = faultException.CreateMessageFault();

            fault = Message.CreateMessage(version, messageFault, null);
        }
Пример #58
0
        /// <summary>
        /// 在异常发生后,异常信息返回前被调用
        /// </summary>
        /// <param name="error">异常</param>
        /// <param name="version">SOAP版本</param>
        /// <param name="fault">返回给客户端的错误信息</param>
        public void ProvideFault(System.Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            if (error is System.IO.IOException)
            {
                FaultException ex = new FaultException("IErrorHandler - ProvideFault测试");

                MessageFault mf = ex.CreateMessageFault();

                fault = System.ServiceModel.Channels.Message.CreateMessage(version, mf, ex.Action);

                // InvalidOperationException error = new InvalidOperationException("An invalid operation has occurred.");
                // MessageFault mfault = MessageFault.CreateFault(new FaultCode("Server", new FaultCode(String.Format("Server.{0}", error.GetType().Name))), new FaultReason(error.Message), error);
                // FaultException fe = FaultException.CreateFault(mfault, typeof(InvalidOperationException));
            }
        }
 internal ProxyRpc(ServiceChannel channel, ProxyOperationRuntime operation, string action, object[] inputs, TimeSpan timeout)
 {
     this.Action           = action;
     this.Activity         = null;
     this.Channel          = channel;
     this.Correlation      = EmptyArray.Allocate(operation.Parent.CorrelationCount);
     this.InputParameters  = inputs;
     this.Operation        = operation;
     this.OutputParameters = null;
     this.Request          = null;
     this.Reply            = null;
     this.ActivityId       = Guid.Empty;
     this.ReturnValue      = null;
     this.MessageVersion   = channel.MessageVersion;
     this.TimeoutHelper    = new System.Runtime.TimeoutHelper(timeout);
 }
Пример #60
0
 private static bool IsMessageVersionMatch(System.ServiceModel.Channels.MessageVersion a, System.ServiceModel.Channels.MessageVersion b)
 {
     if (b == null)
     {
         throw FxTrace.Exception.ArgumentNull("b");
     }
     if (a.Addressing == null)
     {
         throw FxTrace.Exception.AsError(new InvalidOperationException("MessageVersion.Addressing cannot be null"), null);
     }
     if (a.Envelope != b.Envelope)
     {
         return(false);
     }
     return(true);
 }