public Microsoft.ServiceBus.Channels.IConnection Connect(Uri uri, TimeSpan timeout)
        {
            EventTraceActivity eventTraceActivity = new EventTraceActivity();
            TimeoutHelper      timeoutHelper      = new TimeoutHelper(timeout);
            WebStream          webStream          = (new WebStream(uri, "connection", this.useHttpsMode, eventTraceActivity, uri)).Open();

            Microsoft.ServiceBus.Channels.IConnection webStreamConnection = new WebStreamConnection(uri, this.bufferSize, eventTraceActivity, webStream, uri);
            webStreamConnection = SecureSocketUtil.InitiateSecureClientUpgradeIfNeeded(webStreamConnection, null, this.socketSecurityRole, uri.Host, timeoutHelper.RemainingTime());
            SocketMessageHelper socketMessageHelper = new SocketMessageHelper();
            Message             message             = Message.CreateMessage(socketMessageHelper.MessageVersion, "RelayedConnect", new ConnectMessage(uri));

            TrackingIdHeader.TryAddOrUpdate(message.Headers, eventTraceActivity.ActivityId.ToString());
            if (this.tokenProvider != null)
            {
                string        absoluteUri = RelayedHttpUtility.ConvertToHttpUri(uri).AbsoluteUri;
                SecurityToken token       = this.tokenProvider.GetToken(absoluteUri, "Send", false, timeoutHelper.RemainingTime());
                message.Headers.Add(new RelayTokenHeader(token));
            }
            socketMessageHelper.SendMessage(webStreamConnection, message, timeoutHelper.RemainingTime());
            Message message1 = socketMessageHelper.ReceiveMessage(webStreamConnection, timeoutHelper.RemainingTime());

            if (message1.IsFault)
            {
                throw ErrorUtility.ConvertToError(MessageFault.CreateFault(message1, 65536));
            }
            return(webStreamConnection);
        }
        /// <summary>
        /// Gets the metadata set from the Resource Management Service
        /// </summary>
        /// <returns></returns>
        private static MetadataSet GetMetadataSet(EndpointManager e)
        {
            MetadataSet set;
            GetMetadata body = new GetMetadata();

            body.Dialect    = Namespaces.XmlSchema;
            body.Identifier = string.Format("xs:schema/{0}", Namespaces.ResourceManagement);

            Message requestMessage = Message.CreateMessage(MessageVersion.Default, Namespaces.Get, new SerializerBodyWriter(body));

            Binding httpBinding = BindingManager.GetWsHttpBinding();

            ResourceManagementService.MetadataExchangeClient mex = new ResourceManagementService.MetadataExchangeClient(httpBinding, e.MetadataEndpoint);
            Message responseMessage = mex.Get(requestMessage);

            if (responseMessage.IsFault)
            {
                // We shouldn't get here as the WCF framework should convert the fault into an exception
                MessageFault fault = MessageFault.CreateFault(responseMessage, Int32.MaxValue);
                throw new FaultException(fault);
            }

            set = responseMessage.GetBody <MetadataSet>();
            return(set);
        }
 private void Fault(Message message)
 {
     try
     {
         MessageFault fault = MessageFault.CreateFault(message, 0x10000);
         if (DebugTrace.Verbose)
         {
             FaultCode baseFaultCode = Library.GetBaseFaultCode(fault);
             DebugTrace.Trace(TraceLevel.Verbose, "Dispatching participant completion fault {0}", (baseFaultCode == null) ? "unknown" : baseFaultCode.Name);
             if (DebugTrace.Pii)
             {
                 DebugTrace.TracePii(TraceLevel.Verbose, "Sender is {0}", CoordinationServiceSecurity.GetSenderName(message));
             }
         }
         this.dispatch.Fault(message, fault);
     }
     catch (CommunicationException exception)
     {
         Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Warning);
         base.OnMessageException(message, exception);
     }
     catch (Exception exception2)
     {
         DebugTrace.Trace(TraceLevel.Error, "Unhandled exception {0} dispatching completion fault from participant: {1}", exception2.GetType().Name, exception2);
         Microsoft.Transactions.Bridge.DiagnosticUtility.InvokeFinalHandler(exception2);
     }
 }
 private void ProvideFaultOfLastResort(Exception error, ref ErrorHandlerFaultInfo faultInfo)
 {
     if (faultInfo.Fault == null)
     {
         MessageFault fault;
         FaultCode    subCode = new FaultCode("InternalServiceFault", "http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher");
         subCode = FaultCode.CreateReceiverFaultCode(subCode);
         string action = "http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher/fault";
         if (this.debug)
         {
             faultInfo.DefaultFaultAction = action;
             fault = MessageFault.CreateFault(subCode, new FaultReason(error.Message), new ExceptionDetail(error));
         }
         else
         {
             string text = this.isOnServer ? System.ServiceModel.SR.GetString("SFxInternalServerError") : System.ServiceModel.SR.GetString("SFxInternalCallbackError");
             fault = MessageFault.CreateFault(subCode, new FaultReason(text));
         }
         faultInfo.IsConsideredUnhandled = true;
         faultInfo.Fault = Message.CreateMessage(this.messageVersion, fault, action);
     }
     else if (error != null)
     {
         FaultException exception = error as FaultException;
         if ((((exception != null) && (exception.Fault != null)) && ((exception.Fault.Code != null) && (exception.Fault.Code.SubCode != null))) && ((string.Compare(exception.Fault.Code.SubCode.Namespace, "http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher", StringComparison.Ordinal) == 0) && (string.Compare(exception.Fault.Code.SubCode.Name, "InternalServiceFault", StringComparison.Ordinal) == 0)))
         {
             faultInfo.IsConsideredUnhandled = true;
         }
     }
 }
        private static MessagePartSpecification ExtractMessageParts(string action,
                                                                    ScopedMessagePartSpecification scopedParts, bool isForSignature)
        {
            MessagePartSpecification parts = null;

            if (scopedParts.TryGetParts(action, out parts))
            {
                return(parts);
            }
            else if (scopedParts.TryGetParts(MessageHeaders.WildcardAction, out parts))
            {
                return(parts);
            }

            // send back a fault indication that the action is unknown
            SecurityVersion wss        = MessageSecurityVersion.Default.SecurityVersion;
            FaultCode       subCode    = new FaultCode(wss.InvalidSecurityFaultCode.Value, wss.HeaderNamespace.Value);
            FaultCode       senderCode = FaultCode.CreateSenderFaultCode(subCode);
            FaultReason     reason     = new FaultReason(SR.Format(SR.InvalidOrUnrecognizedAction, action), System.Globalization.CultureInfo.CurrentCulture);
            MessageFault    fault      = MessageFault.CreateFault(senderCode, reason);

            if (isForSignature)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.Format(SR.NoSignaturePartsSpecified, action), null, fault));
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.Format(SR.NoEncryptionPartsSpecified, action), null, fault));
            }
        }
        /// <summary>
        /// Factory used to create the expected <see cref="MessageFault"/> to be used when returning this fault type.
        /// </summary>
        /// <param name="fault">The <see cref="ServiceUnavailableFault"/> to create a <see cref="MessageFault"/> from.</param>
        /// <returns>The appropriate <see cref="MessageFault"/> for the supplied <see cref="ServiceUnavailableFault"/>.</returns>
        public static MessageFault CreateStandardFault(ServiceUnavailableFault fault)
        {
            var faultCode   = CreateStandardCode();
            var faultReason = CreateStandardReason();

            return(MessageFault.CreateFault(faultCode, faultReason, fault));
        }
Esempio n. 7
0
        static void CallGeneric(GenericClient genericClient, string action, XmlNode messageBody)
        {
            // Build the message
            Message response;
            Message request;

            request = Message.CreateMessage(
                MessageVersion.Default,
                action,
                new XmlNodeReader(messageBody));

            // send request
            response = genericClient.Request(request);

            // dump the result
            if (!response.IsFault)
            {
                XmlReader resultBody = response.GetReaderAtBodyContents();
                resultBody.ReadToDescendant("text", "http://Microsoft.ServiceModel.Samples");
                string responseText = resultBody.ReadElementContentAsString("text", "http://Microsoft.ServiceModel.Samples");
                Console.WriteLine(responseText);
            }
            else
            {
                MessageFault fault = MessageFault.CreateFault(response, 8192);
                throw new FaultException(fault);
            }

            Console.WriteLine();
        }
        private Exception DeserializeFault(System.ServiceModel.Channels.Message inMessage, FaultConverter faultConverter)
        {
            MessageFault fault  = MessageFault.CreateFault(inMessage, 0x10000);
            string       action = inMessage.Headers.Action;

            if (action == inMessage.Version.Addressing.DefaultFaultAction)
            {
                action = null;
            }
            Exception exception = null;

            if (faultConverter != null)
            {
                faultConverter.TryCreateException(inMessage, fault, out exception);
            }
            if (exception == null)
            {
                exception = this.FaultFormatter.Deserialize(fault, action);
            }
            if (inMessage.State != MessageState.Created)
            {
                inMessage.Close();
            }
            return(exception);
        }
Esempio n. 9
0
        public void TryCreateExceptionDefault()
        {
            var msg = Message.CreateMessage(XmlReader.Create(new StringReader(xml1)), 0x1000, MessageVersion.Soap11WSAddressing10);
            var mf  = MessageFault.CreateFault(msg, 1000);

            msg = Message.CreateMessage(XmlReader.Create(new StringReader(xml1)), 0x1000, MessageVersion.Soap11WSAddressing10);
            Exception ex;

            Assert.IsTrue(s11.TryCreateException(msg, mf, out ex), "#1");
            // foobar -> false
            Assert.IsFalse(s11.TryCreateException(msg, MessageFault.CreateFault(new FaultCode("foobar"), new FaultReason("foobar reason")), out ex), "#2");
            // SOAP 1.1 ActionNotSupported -> true
            Assert.IsTrue(s11.TryCreateException(msg, MessageFault.CreateFault(new FaultCode("ActionNotSupported", Constants.WsaNamespace), new FaultReason("foobar reason")), out ex), "#3");
            Assert.IsTrue(ex is ActionNotSupportedException, "#3-2");
            Assert.IsTrue(ex.Message.IndexOf("foobar") >= 0, "#3-3");

            // SOAP 1.1 Sender/ActionNotSupported -> false
            mf = MessageFault.CreateFault(new FaultCode("Sender", new FaultCode("ActionNotSupported", Constants.WsaNamespace)), new FaultReason("foobar reason"));
            Assert.IsFalse(s11.TryCreateException(msg, mf, out ex), "#4");
            // SOAP 1.2 ActionNotSupported -> false
            mf = MessageFault.CreateFault(new FaultCode("ActionNotSupported", Constants.WsaNamespace), new FaultReason("foobar reason"));
            Assert.IsFalse(s12.TryCreateException(msg, mf, out ex), "#5");
            // SOAP 1.2 Sender/ActionNotSupported -> true
            mf = MessageFault.CreateFault(new FaultCode("Sender", new FaultCode("ActionNotSupported", Constants.WsaNamespace)), new FaultReason("foobar reason"));
            Assert.IsTrue(s12.TryCreateException(msg, mf, out ex), "#6");
            Assert.IsTrue(ex is ActionNotSupportedException, "#6-2");
            Assert.IsTrue(ex.Message.IndexOf("foobar") >= 0, "#6-3");
        }
Esempio n. 10
0
        /// <summary>
        /// Factory used to create the expected <see cref="MessageFault"/> to be used when returning this fault type.
        /// </summary>
        /// <param name="fault">The <see cref="ActionNotSupportedFault"/> to create a <see cref="MessageFault"/> from.</param>
        /// <returns>The appropriate <see cref="MessageFault"/> for the supplied <see cref="SlaViolationFault"/>.</returns>
        public static MessageFault CreateStandardFault(ActionNotSupportedFault fault)
        {
            var faultCode   = CreateStandardCode();
            var faultReason = CreateStandardReason();

            return(MessageFault.CreateFault(faultCode, faultReason, fault));
        }
Esempio n. 11
0
        public int GetFactorialNumber(int number)
        {
            if (number <= 0)
            {
                throw new FaultException(
                          MessageFault.CreateFault(
                              FaultCode.CreateSenderFaultCode(
                                  new FaultCode(
                                      "E01",
                                      "www.google.com"
                                      )
                                  ),
                              new FaultReason(
                                  new FaultReasonText(
                                      "Number should be greater than zero",
                                      CultureInfo.CurrentUICulture
                                      )
                                  )
                              )
                          , "Check the fault reason");
            }

            if (number == 1)
            {
                return(1);
            }
            return(number * GetFactorialNumber(--number));
        }
 private static void SetCommunicationStatusFlags(ref Message reply, IRuntime runtime)
 {
     if (!reply.IsFault)
     {
         return;
     }
     try
     {
         var buffer = reply.CreateBufferedCopy(int.MaxValue);
         var copy   = buffer.CreateMessage();
         if (!copy.IsFault)
         {
             return;
         }
         var fault = MessageFault.CreateFault(copy, int.MaxValue);
         var error = fault.Reason.GetMatchingTranslation().Text;
         reply = buffer.CreateMessage();
         var exception = new CommunicationException(error);
         SetConnectivityErrorFlag(exception, runtime);
     }
     catch (Exception ex)
     {
         SetConnectivityErrorFlag(ex, runtime);
     }
 }
 static ProtocolException CreateReceiveShutdownReturnedNonNull(Message message)
 {
     if (message.IsFault)
     {
         try
         {
             MessageFault    fault  = MessageFault.CreateFault(message, 64 * 1024);
             FaultReasonText reason = fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture);
             string          text   = String.Format(ExceptionMessages.ReceiveShutdownReturnedFault, reason.Text);
             return(new ProtocolException(text));
         }
         catch (QuotaExceededException)
         {
             string text = String.Format(ExceptionMessages.ReceiveShutdownReturnedLargeFault,
                                         message.Headers.Action);
             return(new ProtocolException(text));
         }
     }
     else
     {
         string text = String.Format(ExceptionMessages.ReceiveShutdownReturnedMessage,
                                     message.Headers.Action);
         return(new ProtocolException(text));
     }
 }
Esempio n. 14
0
        public void RunBasicFaultTest()
        {
            for
            (
                MessageVersion version = MessageVersion.Soap11;
                version != null;
                version = (version == MessageVersion.Soap11) ? MessageVersion.Soap12WSAddressing10 : null
            )
            {
                var translations = new List <FaultReasonText>
                {
                    new FaultReasonText("Reason: auto-generated fault for testing.", "en-us"),
                    new FaultReasonText("Raison: auto-generat error pour examiner.", "fr")
                };

                var    reason = new FaultReason(translations);
                object detail = "Sample fault detail content.";

                MessageFault fault   = MessageFault.CreateFault(new FaultCode("Sender"), reason, detail, new System.Runtime.Serialization.DataContractSerializer(typeof(string)), "", "");
                Message      message = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, fault, "http://www.w3.org/2005/08/addressing/fault");
                Message      m2      = MessageTestUtilities.SendAndReceiveMessage(message);
                MessageFault f2      = MessageFault.CreateFault(m2, int.MaxValue);

                IsFaultEqual(fault, f2);
            }
        }
        public void TestCreateMessageFault()
        {
            EmptyFaultException e = new EmptyFaultException();

            Assert.IsTrue(
                AreEqual(MessageFault.CreateFault(e.Code, e.Reason), e.CreateMessageFault()));
        }
Esempio n. 16
0
        private void ValidateReply(Message reply, string replyAction)
        {
            if (base.interoperating)
            {
                if (!base.coordinationService.Security.CheckIdentity(this, reply))
                {
                    throw Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WsatReceiveFailureException(Microsoft.Transactions.SR.GetString("ReplyServerCredentialMismatch")));
                }
                if (!base.coordinationService.GlobalAcl.AccessCheckReply(reply, BindingStrings.InteropBindingQName(base.protocolVersion)))
                {
                    throw Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WsatReceiveFailureException(Microsoft.Transactions.SR.GetString("ReplyServerIdentityAccessDenied", new object[] { base.to.Uri })));
                }
            }
            string action = reply.Headers.Action;

            if ((reply.IsFault || (action == base.atomicTransactionStrings.FaultAction)) || (action == base.coordinationStrings.FaultAction))
            {
                MessageFault fault = MessageFault.CreateFault(reply, 0x10000);
                throw Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WsatFaultException(fault, action));
            }
            if (action != replyAction)
            {
                throw Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WsatReceiveFailureException(Microsoft.Transactions.SR.GetString("InvalidMessageAction", new object[] { action })));
            }
        }
            public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
            {
                FaultException <DomainServiceFault> faultError = error as FaultException <DomainServiceFault>;

                if (faultError != null)
                {
                    if (this.format == WebContentFormat.Json)
                    {
                        // Create a fault message containing our FaultContract object.
                        fault = Message.CreateMessage(version, faultError.Action, faultError.Detail, new DataContractJsonSerializer(faultError.Detail.GetType()));
                        fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(this.format));

                        // Return custom error code.
                        var rmp = new HttpResponseMessageProperty();
                        rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError;
                        rmp.Headers[System.Net.HttpResponseHeader.ContentType] = "text/json";
                        fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
                    }
                    else
                    {
                        // serialize in the SOAP fault format so that Silverlight throws the right exception
                        MessageFault messageFault = MessageFault.CreateFault(faultError.Code, faultError.Reason, faultError.Detail);
                        fault = Message.CreateMessage(MessageVersion.None, messageFault, null);
                        var rmp = new HttpResponseMessageProperty();
                        rmp.StatusCode = System.Net.HttpStatusCode.OK;
                        fault.Properties.Add(HttpResponseMessageProperty.Name, rmp);
                    }
                }
            }
Esempio n. 18
0
        private Message TransformOutputMessage(Message value, MessageVersion clientMsgVersion)
        {
            Message toSend;

            if (value.Version == clientMsgVersion)
            {
                toSend = value;
            }
            else
            {
                if (value.IsFault)
                {
                    MessageFault fault = MessageFault.CreateFault(value, 100000);

                    MessageFault fault2 = MessageFault.CreateFault(fault.Code, fault.Reason);

                    toSend = Message.CreateMessage(
                        clientMsgVersion, //versione
                        fault2,
                        value.Headers.Action);
                }
                else
                {
                    //trasforma il messaggio d restituire in una versione compatibile con il chiamante originale
                    toSend = Message.CreateMessage(clientMsgVersion, value.Headers.Action, value.GetReaderAtBodyContents());
                }
            }
            return(toSend);
        }
Esempio n. 19
0
        public static AdwsFault ConstructFault(Message response)
        {
            AdwsFault     adwsFault;
            MessageBuffer buffer       = AdwsMessage.MessageToBuffer(response);
            MessageFault  messageFault = MessageFault.CreateFault(AdwsMessage.BufferToMessage(buffer), 0x500000);
            object        obj          = null;

            if (messageFault.HasDetail)
            {
                try
                {
                    string str  = string.Concat(messageFault.Code.SubCode.Namespace, ":", messageFault.Code.SubCode.Name);
                    Type   item = (Type)AdwsFaultUtil._faultSubCodeType[str];
                    if (item != null)
                    {
                        XmlReader     readerAtDetailContents = messageFault.GetReaderAtDetailContents();
                        XmlSerializer xmlSerializer          = new XmlSerializer(item);
                        obj = xmlSerializer.Deserialize(readerAtDetailContents);
                    }
                }
                catch (Exception exception)
                {
                }
            }
            if (obj == null)
            {
                adwsFault = new AdwsFault(messageFault);
            }
            else
            {
                adwsFault = new AdwsFault(messageFault, obj);
            }
            return(adwsFault);
        }
Esempio n. 20
0
        public void OnPremiseResponseReceiver_ReceiveResponse_FaultMessage()
        {
            MockDispatcher dispatcher = new MockDispatcher();

            AzureResponseReceiver receiver = new AzureResponseReceiver(dispatcher);

            Message emptyMessage = Message.CreateMessage(MessageVersion.Default, string.Empty);

            MessageFault fault = MessageFault.CreateFault(FaultCode.CreateReceiverFaultCode("Error", Constant.HpcHeaderNS), string.Empty);

            DispatchData data = new DispatchData("1", 0, "1")
            {
                BrokerQueueItem = new BrokerQueueItem(null, emptyMessage, null),

                Client = new MockClient()
                {
                    Response = Message.CreateMessage(MessageVersion.Default, fault, string.Empty)
                }
            };

            receiver.ReceiveResponse(data);

            Assert.AreEqual(data.Exception, null, "Exception is not expected to happen in ReceiveResponse method.");

            Assert.AreEqual(data.ReplyMessage.IsFault, true, "Expected to receive fault message ReceiveResponse method.");
        }
Esempio n. 21
0
        void ThrowFaultException(Message message)
        {
            string       action = message.Headers.Action;
            MessageFault fault  = MessageFault.CreateFault(message, (int)_bindingElement.MaxReceivedMessageSize);

            throw new FaultException(fault);
        }
Esempio n. 22
0
        /// <summary>
        /// Gets the data from specified <see cref="Message"/> object.
        /// </summary>
        /// <typeparam name="T">Type of returned object with data.</typeparam>
        /// <param name="data">The <see cref="Message"/> with data.</param>
        /// <returns>Object with data.</returns>
        public static T GetData <T>(Message data)
        {
            RoboFramework.Tools.RandomLogHelper.GetLog().Debug("SynchronizationHelper::T GetData<T>(Message data)");
            using (data)
            {
                if (data == null)
                {
                    return(default(T));
                }

                if (data.IsFault == true)
                {
                    MessageFault fault = MessageFault.CreateFault(data, 500000);
                    if (fault.HasDetail)
                    {
                        System.ServiceModel.ExceptionDetail excDet = fault.GetDetail <System.ServiceModel.ExceptionDetail>();
                        Type      excType = String.IsNullOrEmpty(excDet.Type) ? null : Type.GetType(excDet.Type);
                        Exception e       = (excType == null) ? new Exception() : (Exception)Activator.CreateInstance(excType);

                        FieldInfo innerExceptionField = typeof(Exception).GetField("_innerException", BindingFlags.NonPublic | BindingFlags.Instance);
                        FieldInfo messageField        = typeof(Exception).GetField("_message", BindingFlags.NonPublic | BindingFlags.Instance);
                        FieldInfo stackTraceField     = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.NonPublic | BindingFlags.Instance);
                        innerExceptionField.SetValue(e, excDet.InnerException);
                        messageField.SetValue(e, excDet.Message);
                        stackTraceField.SetValue(e, excDet.StackTrace);
                        throw e;
                    }
                }

                return(data.GetBody <T>());
            }
        }
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (reply.IsFault || IsHttpInternalErrorFault(reply))
            {
                ExceptionFault fault = null;
                var            mf    = MessageFault.CreateFault(reply, int.MaxValue);
                try
                {
                    if (mf.HasDetail && mf.Reason.ToString() == "UnhandledException")
                    {
                        var detail = mf.GetDetail <ExceptionFault>();
                        fault = detail;
                    }
                }
#pragma warning disable RECS0022 // A catch clause that catches System.Exception and has an empty body
                catch
#pragma warning restore RECS0022 // A catch clause that catches System.Exception and has an empty body
                {
                    // do nothing
                }

                if (fault != null)
                {
                    fault.ReThrow();
                }
                else
                {
                    var operation  = _runtime.ClientOperations.FirstOrDefault(p => p.Action == (string)correlationState);
                    var faultTypes = _contract.Operations.Where(p => operation == null || p.Name == operation.Name).SelectMany(p => p.Faults.Select(x => x.DetailType)).Distinct().ToArray();

                    var ex = FaultException.CreateFault(mf, reply.Headers.Action, faultTypes);
                    ExceptionDispatchInfo.Capture(ex).Throw();
                }
            }
        }
Esempio n. 24
0
        private XmlElement Complete(X509Certificate2 sessionCert, RequestSecurityTokenResponse response)
        {
            //we expect SignChallenge, which we need to return as SignChallengeResponse using the body cert/key.
            if (response.RequestSecurityTokenResponse1.SignChallenge == null)
            {
                throw new InvalidOperationException("eHealth WS-Trust service didn't return sign challenge response");
            }
            response.RequestSecurityTokenResponse1.SignChallengeResponse = response.RequestSecurityTokenResponse1.SignChallenge;
            response.RequestSecurityTokenResponse1.SignChallenge         = null;

            //create a secondary channel to send the challenge
            ChannelFactory <IWsTrustPortFixed> channelFactory = new ChannelFactory <IWsTrustPortFixed>(base.Endpoint.Binding, base.Endpoint.Address);

            channelFactory.Credentials.ClientCertificate.Certificate = sessionCert;
            IWsTrustPortFixed secondary = channelFactory.CreateChannel();

            //send the (signed) Challenge, get the reponse as message to not break the internal signature
            Message responseMsg = secondary.Challenge(response);

            if (responseMsg.IsFault)
            {
                throw new FaultException(MessageFault.CreateFault(responseMsg, 10240), responseMsg.Headers.Action);
            }
            var responseBody = new XmlDocument();

            responseBody.PreserveWhitespace = true;
            responseBody.Load(responseMsg.GetReaderAtBodyContents());

            //better to check if correcty wrapped, but for now we do not care.

            return((XmlElement)responseBody.GetElementsByTagName("Assertion", "urn:oasis:names:tc:SAML:1.0:assertion")[0]);
        }
Esempio n. 25
0
        /// <summary>
        /// Factory used to create the expected <see cref="MessageFault"/> to be used when returning this fault type.
        /// </summary>
        /// <param name="fault">The <see cref="SlaViolationFault"/> to create a <see cref="MessageFault"/> from.</param>
        /// <returns>The appropriate <see cref="MessageFault"/> for the supplied <see cref="SlaViolationFault"/>.</returns>
        public static MessageFault CreateStandardFault(SlaViolationFault fault)
        {
            var faultCode   = CreateStandardCode();
            var faultReason = CreateStandardReason();

            return(MessageFault.CreateFault(faultCode, faultReason, fault));
        }
            private void ThrowIfFaultMessage(Message wcfMessage)
            {
                Exception exception;

                if (wcfMessage.IsFault)
                {
                    MessagingClientEtwProvider.TraceClient(() => {
                    });
                    string         action       = wcfMessage.Headers.Action;
                    MessageFault   messageFault = MessageFault.CreateFault(wcfMessage, 65536);
                    FaultConverter property     = this.innerChannel.GetProperty <FaultConverter>();
                    if (property == null || !property.TryCreateException(wcfMessage, messageFault, out exception))
                    {
                        if (!messageFault.HasDetail)
                        {
                            throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsWarning(new FaultException(messageFault, action), null);
                        }
                        ExceptionDetail detail = messageFault.GetDetail <ExceptionDetail>();
                        if (!this.clientMode && string.Equals(detail.Type, typeof(CommunicationException).FullName, StringComparison.Ordinal))
                        {
                            MessagingClientEtwProvider.TraceClient(() => MessagingClientEtwProvider.Provider.EventWriteRuntimeChannelFaulting(this.innerChannel.GetType().Name, this.innerChannel.LocalAddress.Uri.AbsoluteUri, this.innerChannel.RemoteAddress.Uri.AbsoluteUri, this.innerChannel.Via.AbsoluteUri, this.innerChannel.Session.Id, string.Concat("ThrowIfFaultMessage: Received CommunicationException as fault message. ", detail.ToString())));
                            base.Fault();
                        }
                        if (!this.includeExceptionDetails)
                        {
                            throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsInformation(new FaultException <ExceptionDetailNoStackTrace>(new ExceptionDetailNoStackTrace(detail, true), messageFault.Reason, messageFault.Code, action), null);
                        }
                        throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsInformation(new FaultException <ExceptionDetail>(detail, messageFault.Reason, messageFault.Code, action), null);
                    }
                    throw Fx.Exception.AsWarning(exception, null);
                }
            }
Esempio n. 27
0
 private void ProvideFaultOfLastResort(Exception error, ref ErrorHandlerFaultInfo faultInfo)
 {
     if (faultInfo.Fault == null)
     {
         FaultCode code = new FaultCode(FaultCodeConstants.Codes.InternalServiceFault, FaultCodeConstants.Namespaces.NetDispatch);
         code = FaultCode.CreateReceiverFaultCode(code);
         string       action = FaultCodeConstants.Actions.NetDispatcher;
         MessageFault fault;
         if (_debug)
         {
             faultInfo.DefaultFaultAction = action;
             fault = MessageFault.CreateFault(code, new FaultReason(error.Message), new ExceptionDetail(error));
         }
         else
         {
             string reason = _isOnServer ? SRServiceModel.SFxInternalServerError : SRServiceModel.SFxInternalCallbackError;
             fault = MessageFault.CreateFault(code, new FaultReason(reason));
         }
         faultInfo.IsConsideredUnhandled = true;
         faultInfo.Fault = Message.CreateMessage(_messageVersion, fault, action);
     }
     //if this is an InternalServiceFault coming from another service dispatcher we should treat it as unhandled so that the channels are cleaned up
     else if (error != null)
     {
         FaultException e = error as FaultException;
         if (e != null && e.Fault != null && e.Fault.Code != null && e.Fault.Code.SubCode != null &&
             string.Compare(e.Fault.Code.SubCode.Namespace, FaultCodeConstants.Namespaces.NetDispatch, StringComparison.Ordinal) == 0 &&
             string.Compare(e.Fault.Code.SubCode.Name, FaultCodeConstants.Codes.InternalServiceFault, StringComparison.Ordinal) == 0)
         {
             faultInfo.IsConsideredUnhandled = true;
         }
     }
 }
Esempio n. 28
0
        private MessageFault BuildFault(Exception error)
        {
            ServiceExceptionDetail exceptionDetail = new ServiceExceptionDetail(error);
            FaultCode code = FaultCode.CreateReceiverFaultCode(ServiceExceptionDetail.FaultSubCodeName, ServiceExceptionDetail.FaultSubCodeNamespace);

            return(MessageFault.CreateFault(code, new FaultReason(error.Message), exceptionDetail));
        }
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
            MessageFault messageFault = MessageFault.CreateFault(new FaultCode("FaultCode"), new FaultReason(error.Message));

            fault = Message.CreateMessage(version, messageFault, "FaultAction");
        }
Esempio n. 30
0
        public CoreWCF.Channels.Message Untyped_MethodReturns(CoreWCF.Channels.Message msgIn)
        {
            MessageVersion mv = MessageVersion.Soap11;

            if (null != msgIn)
            {
                string faultString = GetTestStrFromMsg(msgIn);
                switch (faultString)
                {
                case VarSomeFault:
                    return(Message.CreateMessage(mv, MessageFault.CreateFault(new FaultCode("Sender"), new FaultReason("Unspecified ServiceModel Fault"), (object)new ServiceContract.SomeFault(123456789, "SomeFault"),
                                                                              new System.Runtime.Serialization.DataContractSerializer(typeof(ServiceContract.SomeFault)), "", ""), "http://tempuri.org/ITestDataContractFault/Untyped_MethodReturnsSomeFaultFault"));

                case VarOuterFault:
                    ServiceContract.SomeFault  sf = new ServiceContract.SomeFault(123456789, "SomeFault as innerfault");
                    ServiceContract.OuterFault of = new ServiceContract.OuterFault
                    {
                        InnerFault = sf
                    };
                    return(Message.CreateMessage(mv, MessageFault.CreateFault(new FaultCode("Sender"), new FaultReason("Unspecified ServiceModel Fault"), (object)of,
                                                                              new System.Runtime.Serialization.DataContractSerializer(typeof(ServiceContract.OuterFault)), "", ""), "http://tempuri.org/ITestDataContractFault/Untyped_MethodReturnsOuterFaultFault"));

                case VarComplexFault:
                    ServiceContract.ComplexFault cf = GetComplexFault();
                    return(Message.CreateMessage(mv, MessageFault.CreateFault(new FaultCode("Sender"), new FaultReason("Unspecified ServiceModel Fault"), (object)cf,
                                                                              new System.Runtime.Serialization.DataContractSerializer(typeof(ServiceContract.ComplexFault)), "", ""), "http://tempuri.org/ITestDataContractFault/Untyped_MethodReturnsComplexFaultFault"));

                default:
                    throw new ApplicationException("Unknown value of FaultString specified: " + faultString);
                }
            }

            return(Message.CreateMessage(mv, MessageFault.CreateFault(new FaultCode("Sender"), new FaultReason("Unspecified ServiceModel Fault"), "unspecified",
                                                                      new System.Runtime.Serialization.DataContractSerializer(typeof(string)), "", ""), "http://www.w3.org/2005/08/addressing/fault"));
        }