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();
                }
            }
        }
        protected virtual WsTrustResponse ReadResponse(Message message)
        {
            if (message.IsFault)
            {
                // TODO: Create constant for FaultMaxBufferSize
                var fault     = MessageFault.CreateFault(message, 20 * 1024);
                var action    = message.Headers?.Action;
                var exception = FaultException.CreateFault(fault, action);
                // TODO: add tracing
                throw exception;
            }

            var response = null as WsTrustResponse;

            using (var reader = message.GetReaderAtBodyContents())
                response = _serializer.ReadResponse(reader);

            foreach (var rstr in response.RequestSecurityTokenResponseCollection)
            {
                var element = rstr.RequestedSecurityToken?.TokenElement;
                if (element == null)
                {
                    continue;
                }
                var created = rstr.Lifetime?.Created ?? DateTime.UtcNow;
                var expires = rstr.Lifetime?.Expires ?? DateTime.UtcNow.AddMinutes(5);
                var proof   = null as SecurityKey;
                var internalTokenReference = null as GenericXmlSecurityKeyIdentifierClause;
                var externalTokenReference = null as GenericXmlSecurityKeyIdentifierClause;
                if (rstr.RequestedProofToken != null)
                {
                    if (rstr.RequestedProofToken.BinarySecret != null)
                    {
                        proof = new SymmetricSecurityKey(rstr.RequestedProofToken.BinarySecret.Data);
                    }
                }
                if (rstr.AttachedReference != null)
                {
                    internalTokenReference = CreateKeyIdentifierClause(rstr.AttachedReference, true);
                }
                if (rstr.UnattachedReference != null)
                {
                    externalTokenReference = CreateKeyIdentifierClause(rstr.UnattachedReference, false);
                }

                rstr.RequestedSecurityToken.SecurityToken = new GenericXmlSecurityToken(
                    element,
                    created,
                    expires,
                    securityKey: proof,
                    internalTokenReference: internalTokenReference,
                    externalTokenReference: externalTokenReference
                    );
            }

            return(response);
        }
        public void ThrowMessageFault()
        {
            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));

            throw fe;
        }
Exemplo n.º 4
0
 /// <summary>
 /// Processa a respota recebida.
 /// </summary>
 /// <param name="reply"></param>
 /// <param name="correlationState"></param>
 public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
 {
     if (reply.IsFault)
     {
         var buffer = reply.CreateBufferedCopy(Int32.MaxValue);
         var copy   = buffer.CreateMessage();
         reply = buffer.CreateMessage();
         var messageFault = MessageFault.CreateFault(copy, 0x10000);
         throw FaultException.CreateFault(messageFault);
     }
 }
Exemplo n.º 5
0
 public static Exception ConvertToError(MessageFault fault)
 {
     if (fault.Code.Namespace != "http://schemas.microsoft.com/netservices/2009/05/servicebus/relay")
     {
         return(FaultException.CreateFault(fault, new Type[0]));
     }
     if (fault.Code.Name == "AddressAlreadyInUseFault")
     {
         return(new AddressAlreadyInUseException(string.Concat("The specified address already exists.", fault.Reason)));
     }
     if (fault.Code.Name == "AddressNotFoundFault")
     {
         return(new AddressNotFoundException("The address was not found. Please check whether the service at the specified name is currently running."));
     }
     if (fault.Code.Name == "AddressReplacedFault")
     {
         return(new AddressReplacedException("The address was re-registered by a service at another location. Please check whether another instance of this service is now running."));
     }
     if (fault.Code.Name == "AuthorizationFailedFault")
     {
         return(new AuthorizationFailedException(AuthorizationFailedException.FailureCode.Generic, string.Concat("There was an authorization failure. Make sure you have specified the correct SharedSecret, SimpleWebToken, SharedAccessSignature, or Saml transport client credentials. ", fault.Reason)));
     }
     if (fault.Code.Name == "EndpointNotFoundFault")
     {
         string      str = string.Concat("The endpoint was not found. ", fault.Reason);
         CultureInfo invariantCulture = CultureInfo.InvariantCulture;
         object[]    objArray         = new object[] { str, 9350 };
         return(new EndpointNotFoundException(string.Format(invariantCulture, "{0}. Please ensure that you can connect to the internet using HTTP port 80 and TCP port {1}.", objArray)));
     }
     if (fault.Code.Name == "RelayNotFoundFault")
     {
         return(new RelayNotFoundException(fault.Reason.ToString()));
     }
     if (fault.Code.Name == "NoTransportSecurityFault")
     {
         return(new NoTransportSecurityException(string.Concat("Transport security is required for this connection. ", fault.Reason)));
     }
     if (fault.Code.Name == "InvalidRequestFault")
     {
         return(new InvalidRequestException(string.Concat("The request was rejected by the server as invalid. ", fault.Reason)));
     }
     if (fault.Code.Name == "ConnectionFailedFault")
     {
         return(new InvalidRequestException(string.Concat("The connection was failed. ", fault.Reason)));
     }
     if (fault.Code.Name == "QuotaExceededFault")
     {
         return(new QuotaExceededException(string.Concat("User quota was exceeded. ", fault.Reason)));
     }
     return(new ServerErrorException(string.Concat("The server had an error while processing request. ", fault.Reason)));
 }
        protected void DeserializeRequestInternal(Message message, object[] parameters)
        {
            var provider = ObjectBuilder.GetModelProvider();

            var serializer = ObjectBuilder.GetSerializer();

            var compressionType = GetMessageCompressionTypeOptions(message);

            CompressionProvider compressionProvider = null;

            if (compressionType != CompressionTypeOptions.None)
            {
                compressionProvider = new CompressionProvider();
            }

            var reader = message.GetReaderAtBodyContents();

            reader.Read();

            for (var i = 0; i < parameters.Length; i++)
            {
                var model = provider.CreateModelInfo(ParameterTypes[i].Type, ModeType.Wcf);

                reader.Read();

                var val = reader.Value;

                var data = BinaryConverter.FromString(val);

                if (compressionProvider != null)
                {
                    data = compressionProvider.DeCompress(data, compressionType);
                }

                object retVal;
                try
                {
                    retVal = serializer.Deserialize(data, model.MetaData, ParameterTypes[i].Type, ModeType.Wcf);
                }
                catch (SerializationException)
                {
                    throw FaultException.CreateFault(
                              MessageFault.CreateFault(
                                  new FaultCode(Constants.SerializationFaultCode.ToString(CultureInfo.InvariantCulture)),
                                  "Serialization failed, meta data removal is recommended."));
                }

                parameters[i] = retVal;
            }
        }
Exemplo n.º 7
0
        private void OnReceive(ref Message reply)
        {
            if (reply.IsFault && reply.Headers.Action == FaultMessage.FaultAction)
            {
                var fault = MessageFault.CreateFault(reply, int.MaxValue);
                if (fault.Code.SubCode.Name == FaultMessage.FaultSubCodeName &&
                    fault.Code.SubCode.Namespace == FaultMessage.FaultSubCodeNamespace)
                {
                    var exception = (FaultException <FaultMessage>)FaultException
                                    .CreateFault(fault, typeof(FaultMessage));

                    throw GetException(exception.Detail);
                }
            }
        }
 /// <summary>
 /// Processa a respota recebida.
 /// </summary>
 /// <param name="reply"></param>
 /// <param name="correlationState"></param>
 public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
 {
     if (reply.IsFault)
     {
         var buffer = reply.CreateBufferedCopy(Int32.MaxValue);
         var copy   = buffer.CreateMessage();
         reply = buffer.CreateMessage();
         var messageFault = MessageFault.CreateFault(copy, 0x10000);
         if ((messageFault.Code.Name == InvalidTokenFaultReasonCode || messageFault.Code.Name == EmptyTokenFaultReasonCode) && messageFault.Code.Namespace == Namespace)
         {
             throw new InvalidSecurityTokenException(messageFault.Reason.ToString(), FaultException.CreateFault(messageFault));
         }
         throw FaultException.CreateFault(messageFault);
     }
 }
Exemplo n.º 9
0
 public static FaultException ConstructFaultException(Message response)
 {
     Type[] typeArray = new Type[9];
     typeArray[0] = typeof(FragmentDialect);
     typeArray[1] = typeof(AttributeTypeNotValid);
     typeArray[2] = typeof(EnumerateFault);
     typeArray[3] = typeof(FaultDetail);
     typeArray[4] = typeof(FaultDetail1);
     typeArray[5] = typeof(SupportedSelectOrSortDialect);
     typeArray[6] = typeof(SupportedDialect);
     typeArray[7] = typeof(PullFault);
     typeArray[8] = typeof(RenewFault);
     Type[] typeArray1 = typeArray;
     return(FaultException.CreateFault(MessageFault.CreateFault(response, 0x500000), typeArray1));
 }
Exemplo n.º 10
0
        public void ServiceModel()
        {
            AddressHeaderCollection ahc = new AddressHeaderCollection();

            try {
                ahc.FindAll("name", "namespace");
            }
            catch (NotImplementedException) {
                // feature is not available, but the symbol itself is needed
            }

            try {
                FaultException.CreateFault(new TestFault(), String.Empty, Array.Empty <Type> ());
            }
            catch (NotImplementedException) {
                // feature is not available, but the symbol itself is needed
            }
        }
Exemplo n.º 11
0
        public void ServiceModel()
        {
            AddressHeaderCollection ahc = new AddressHeaderCollection();

            try {
                ahc.FindAll(null, null);
            }
            catch (NotImplementedException) {
                // feature is not available, but the symbol itself is needed
            }

            try {
                FaultException.CreateFault(null, String.Empty, null);
            }
            catch (NotImplementedException) {
                // feature is not available, but the symbol itself is needed
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Processa a respota recebida.
        /// </summary>
        /// <param name="reply">Mensagem da resposta.</param>
        /// <param name="correlationState">Estado de correlação.</param>
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            if (reply.IsFault)
            {
                var buffer = reply.CreateBufferedCopy(int.MaxValue);
                var copy   = buffer.CreateMessage();
                reply = buffer.CreateMessage();

                var messageFault = MessageFault.CreateFault(copy, 0x10000);

                if (messageFault.Code.Name == InvalidTokenFaultReasonCode ||
                    messageFault.Code.Name == EmptyTokenFaultReasonCode)
                {
                    throw new Colosoft.Net.InvalidSecurityTokenException(messageFault.Reason.ToString(), FaultException.CreateFault(messageFault));
                }

                throw FaultException.CreateFault(messageFault);
            }
        }
Exemplo n.º 13
0
 public List <Airline> GetAllAirline()
 {
     try
     {
         //throw new Exception("I really dont like you");
         return(new List <Airline>()
         {
             new Airline()
             {
                 Code = "xyz",
                 Name = "blah",
             }
         });
     }
     catch (Exception)
     {
         throw FaultException.CreateFault(MessageFault.CreateFault(new FaultCode("102"), "I still dont like you."));
     }
 }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            FaultCode code = FaultCode.CreateReceiverFaultCode(
                new FaultCode("CalculationErro", "http://www.lhl.com"));

            IList <FaultReasonText> reasonTexts = new List <FaultReasonText>();

            reasonTexts.Add(new FaultReasonText("parameter is invalid", "en-US"));
            reasonTexts.Add(new FaultReasonText("输入参数不合法", "zh-CN"));

            FaultReason reason = new FaultReason(reasonTexts);

            CalculationError detail = new CalculationError("Divide", "被除数为0");

            MessageFault messageFault = MessageFault.CreateFault(code, reason, detail, new DataContractSerializer(typeof(CalculationError)),
                                                                 "http://www.lhl.com/calculatorservice", "http://www.lhl.com/calculationcenter");
            var file1 = "faultsoap1.xml";
            var file2 = "faultsoap2.xml";

            WriteFault(messageFault, file1, EnvelopeVersion.Soap11);
            WriteFault(messageFault, file2, EnvelopeVersion.Soap12);

            Message message  = Message.CreateMessage(MessageVersion.Soap11WSAddressing10, messageFault, "http://www.lhl.com/calculatorfault");
            Message message1 = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, messageFault, "http://www.lhl.com/calculatorfault");

            using (XmlWriter writer = new XmlTextWriter("11-10.xml", Encoding.UTF8))

                using (XmlWriter writer1 = new XmlTextWriter("12-10.xml", Encoding.UTF8))
                {
                    message.WriteMessage(writer);
                    message1.WriteMessage(writer1);
                }

            FaultException <CalculationError> faultException = FaultException.CreateFault(messageFault, typeof(CalculationError)) as FaultException <CalculationError>;

            Console.WriteLine($"{ faultException.Code } { faultException.Code.SubCode.Namespace } { faultException.Detail.CalType } { faultException.Detail.Message }");

            //FaultException<ExceptionDetail>

            Console.Read();
        }
Exemplo n.º 15
0
 public List <AirLine> GetAllAirlines()
 {
     try
     {
         //throw new Exception(" i dont like u ");
         return(new List <AirLine>()
         {
             new AirLine()
             {
                 Code = "xyz",
                 Name = "Blah"
             }
         });
     }
     catch (Exception e)
     {
         throw FaultException.CreateFault(
                   MessageFault.CreateFault(
                       new FaultCode("101"), "creating fault exception"));
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Sends a <see cref="WsTrustRequest"/> to a STS to obtain a <see cref="WCFSecurityToken"/>.
        /// </summary>
        /// <param name="trustRequest">The <see cref="WsTrustRequest" /> sent to the STS.</param>
        /// <returns>A <see cref="WCFSecurityToken" /> issued by the STS.</returns>
        public async virtual Task <WCFSecurityToken> IssueAsync(WsTrustRequest trustRequest)
        {
            _ = trustRequest ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(trustRequest));

            Message requestMessage = CreateRequest(trustRequest);
            Message response       = await Task.Factory.FromAsync(RequestChannel.BeginRequest, RequestChannel.EndRequest, requestMessage, null, TaskCreationOptions.None).ConfigureAwait(false);

            if (response.IsFault)
            {
                MessageFault fault = MessageFault.CreateFault(response, FaultMaxBufferSize);
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(FaultException.CreateFault(fault, response.Headers?.Action));
            }

            WsTrustResponse  trustResponse = TrustSerializer.ReadResponse(response.GetReaderAtBodyContents());
            WCFSecurityToken token         = WSTrustUtilities.CreateGenericXmlSecurityToken(trustRequest, trustResponse, GetSerializationContext(trustRequest), null);

            if (token == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.Format(SR.TokenProviderUnableToGetToken, string.IsNullOrEmpty(Address) ? ToString() : Address)));
            }

            return(token);
        }
Exemplo n.º 17
0
 internal static Exception CreateSecurityFaultException(MessageFault fault)
 {
     return((Exception) new MessageSecurityException(SR.GetString("UnsecuredMessageFaultReceived"), (Exception)FaultException.CreateFault(fault, new System.Type[2] {
         typeof(string), typeof(object)
     })));
 }