public static Exception GetExceptionByStatusCode(this RemoteInvokeResultMessage message)
        {
            Exception exception = null;

            switch (message.StatusCode)
            {
            case StatusCode.BusinessError:
                exception = new BusinessException(message.ExceptionMessage);
                break;

            case StatusCode.CommunicationError:
                exception = new CommunicationException(message.ExceptionMessage);
                break;

            case StatusCode.RequestError:
            case StatusCode.CPlatformError:
            case StatusCode.UnKnownError:
                exception = new CPlatformException(message.ExceptionMessage, message.StatusCode);
                break;

            case StatusCode.DataAccessError:
                exception = new DataAccessException(message.ExceptionMessage);
                break;

            case StatusCode.UnAuthentication:
                exception = new UnAuthenticationException(message.ExceptionMessage);
                break;

            case StatusCode.UnAuthorized:
                exception = new UnAuthorizedException(message.ExceptionMessage);
                break;

            case StatusCode.UserFriendly:
                exception = new UserFriendlyException(message.ExceptionMessage);
                break;

            case StatusCode.ValidateError:
                exception = new ValidateException(message.ExceptionMessage);
                break;

            default:
                exception = new CPlatformException(message.ExceptionMessage, message.StatusCode);
                break;
            }

            return(exception);
        }
コード例 #2
0
    // Asking for PeerTrust alone should throw SecurityNegotiationException
    // if the certificate is not in the TrustedPeople store.  For this test
    // we use a valid chain-trusted certificate that we know is not in the
    // TrustedPeople store.
    public static void NetTcp_SecModeTrans_CertValMode_PeerTrust_Fails_Not_In_TrustedPeople()
    {
        EndpointAddress endpointAddress               = null;
        string          testString                    = "Hello";
        ChannelFactory <IWcfService> factory          = null;
        IWcfService            serviceProxy           = null;
        CommunicationException communicationException = null;

        try
        {
            // *** SETUP *** \\
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;

            endpointAddress = new EndpointAddress(new Uri(
                                                      Endpoints.Tcp_CustomBinding_SslStreamSecurity_Address));

            factory = new ChannelFactory <IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            try
            {
                serviceProxy.Echo(testString);
            }
            catch (CommunicationException ce)
            {
                communicationException = ce;
            }

            // *** VALIDATE *** \\
            Assert.True(communicationException != null, "Expected CommunicationException but no exception was thrown.");
            Assert.True(communicationException.GetType().Name == "SecurityNegotiationException",
                        String.Format("Expected SecurityNegotiationException but received {0}",
                                      communicationException.ToString()));

            // *** CLEANUP *** \\
            // objects are in faulted state and will throw, so only use finally style cleanup
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
コード例 #3
0
        public void NewHostedServiceProcess()
        {
            string                   serviceName;
            Action <string>          action = null;
            CreateHostedServiceInput createHostedServiceInput = new CreateHostedServiceInput();

            createHostedServiceInput.ServiceName = this.ServiceName;
            if (string.IsNullOrEmpty(this.Label))
            {
                serviceName = this.ServiceName;
            }
            else
            {
                serviceName = this.Label;
            }
            string str = serviceName;

            createHostedServiceInput.Label         = ServiceManagementHelper.EncodeToBase64String(str);
            createHostedServiceInput.Description   = this.Description;
            createHostedServiceInput.AffinityGroup = this.AffinityGroup;
            createHostedServiceInput.Location      = this.Location;
            using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
            {
                try
                {
                    CmdletExtensions.WriteVerboseOutputForObject(this, createHostedServiceInput);
                    NewAzureServiceCommand newAzureServiceCommand = this;
                    if (action == null)
                    {
                        action = (string s) => base.Channel.CreateHostedService(s, createHostedServiceInput);
                    }
                    ((CmdletBase <IServiceManagement>)newAzureServiceCommand).RetryCall(action);
                    Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
                    ManagementOperationContext managementOperationContext = new ManagementOperationContext();
                    managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
                    managementOperationContext.set_OperationId(operation.OperationTrackingId);
                    managementOperationContext.set_OperationStatus(operation.Status);
                    ManagementOperationContext managementOperationContext1 = managementOperationContext;
                    base.WriteObject(managementOperationContext1, true);
                }
                catch (CommunicationException communicationException1)
                {
                    CommunicationException communicationException = communicationException1;
                    this.WriteErrorDetails(communicationException);
                }
            }
        }
コード例 #4
0
ファイル: WebStream.cs プロジェクト: YunLi1988/ServiceBusFake
        public WebStream Open()
        {
            int       num;
            Exception communicationException = null;
            int       num1 = 5;

            do
            {
                int num2 = num1 - 1;
                try
                {
                    MessagingClientEtwProvider.Provider.WebStreamConnecting(base.Activity, this.factoryEndpointUri.AbsoluteUri, this.sbUri.AbsoluteUri, num2);
                    if (this.Connect())
                    {
                        MessagingClientEtwProvider.Provider.WebStreamConnectCompleted(base.Activity, this.factoryEndpointUri.AbsoluteUri, this.sbUri.AbsoluteUri, num2);
                        return(this);
                    }
                }
                catch (WebException webException1)
                {
                    WebException webException = webException1;
                    if (Fx.IsFatal(webException))
                    {
                        throw;
                    }
                    string str = WebStream.CloseResponseInWebException(webException);
                    communicationException = new CommunicationException(string.Concat(webException.Message, str), webException);
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    if (Fx.IsFatal(exception))
                    {
                        throw;
                    }
                    communicationException = exception;
                }
                string str1 = (communicationException != null ? communicationException.ToString() : "Failed to connect. No exception thrown.");
                MessagingClientEtwProvider.Provider.WebStreamConnectFailed(base.Activity, this.factoryEndpointUri.AbsoluteUri, this.sbUri.AbsoluteUri, num2, str1);
                this.Reset();
                this.disposed = false;
                num           = num1 - 1;
                num1          = num;
            }while (num > 0);
            this.disposed = true;
            throw Fx.Exception.AsError(new CommunicationException(SRClient.HTTPConnectivityMode, communicationException), null);
        }
コード例 #5
0
        protected void OnMessageException(Message message, CommunicationException exception)
        {
            DebugTrace.Trace(TraceLevel.Warning, "{0} - {1} reading datagram with action {2}: {3}", base.GetType().Name, exception.GetType().Name, message.Headers.Action, exception.Message);
            EndpointAddress faultToHeader = Library.GetFaultToHeader(message.Headers, this.protocolVersion);

            if (faultToHeader == null)
            {
                DebugTrace.Trace(TraceLevel.Warning, "Ignoring invalid datagram - a fault-to header could not be obtained");
            }
            else
            {
                DatagramProxy proxy = null;
                try
                {
                    proxy = this.CreateFaultProxy(faultToHeader);
                }
                catch (CreateChannelFailureException exception2)
                {
                    Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Warning);
                    DebugTrace.Trace(TraceLevel.Warning, "Ignoring invalid datagram: {0}", exception2.Message);
                }
                if (proxy != null)
                {
                    try
                    {
                        IAsyncResult ar = proxy.BeginSendFault(message.Headers.MessageId, Faults.Version(this.protocolVersion).InvalidParameters, null, null);
                        proxy.EndSendMessage(ar);
                        if (DebugTrace.Warning)
                        {
                            DebugTrace.Trace(TraceLevel.Warning, "Sent InvalidParameters fault to {0}", proxy.To.Uri);
                        }
                    }
                    catch (WsatSendFailureException exception3)
                    {
                        Microsoft.Transactions.Bridge.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Warning);
                        if (DebugTrace.Warning)
                        {
                            DebugTrace.Trace(TraceLevel.Warning, "{0} sending InvalidParameters fault to {1}: {2}", exception3.GetType().Name, proxy.To.Uri, exception3.Message);
                        }
                    }
                    finally
                    {
                        proxy.Release();
                    }
                }
            }
        }
コード例 #6
0
ファイル: ExceptionHelper.cs プロジェクト: xiaowu351/ZPW.Util
            /// <summary>
            /// 解析异常类型
            /// </summary>
            /// <param name="innerExp">Exception对象</param>
            /// <returns>返回详细信息</returns>
            private static string HandleException(Exception innerExp)
            {
                StringBuilder builder = new StringBuilder();

                while (innerExp != null)
                {
                    //服务端异常
                    FaultException <string> faultEx = innerExp as FaultException <string>;
                    if (faultEx != null)
                    {
                        builder.AppendFormat("-------------------{0}:{1}-----------------\r\n", faultEx.GetType().Name, faultEx.Message);
                        builder.AppendLine(faultEx.Detail);
                        break;
                    }

                    //SOAP 错误
                    FaultException faultEx1 = innerExp as FaultException;
                    if (faultEx1 != null)
                    {
                        builder.AppendLine(faultEx1.ToString());
                        break;
                    }

                    //给进程或操作分配的时间过期时引发的异常
                    TimeoutException timeoutEx = innerExp as TimeoutException;
                    if (timeoutEx != null)
                    {
                        builder.AppendLine("连接服务器发生异常,超时!");
                        builder.AppendLine(timeoutEx.ToString());
                        break;
                    }

                    //服务或客户端应用程序中的通信错误。
                    CommunicationException commuEx = innerExp as CommunicationException;
                    if (commuEx != null)
                    {
                        builder.AppendLine("连接服务器发生异常,通信错误!");
                        builder.AppendLine(commuEx.ToString());
                        break;
                    }

                    builder.AppendFormat("-----------------{0} : {1}--------------------\r\n{2}", innerExp.GetType().Name,
                                         innerExp.Message, innerExp.StackTrace);
                    innerExp = innerExp.InnerException;
                }
                return(builder.ToString());
            }
コード例 #7
0
        /// <summary>
        /// Method show authentication dialog for proxy server until user enter valid credentials or cancels the dialog.
        /// </summary>
        /// <param name="licenseActivator">License activator.</param>
        /// <param name="licenseUserName">License username.</param>
        /// <param name="licensePassword">License password.</param>
        /// <param name="proxyEx">Initial proxy authentication required exception.</param>
        /// <returns></returns>
        private void _AuthenticateProxyServerAndGetLicense(
            Func <string, string, LicenseInfo> licenseActivator,
            string licenseUserName,
            string licensePassword,
            CommunicationException proxyEx)
        {
            bool    userPressedOK    = false;
            bool    wrongCredentials = false;
            License license          = null;
            CommunicationException proxyException = proxyEx; // proxy exception that will be thrown if proxy won't be authenticated

            do                                               // repeat showing auth dialog until user either enters correct credentials or presses cancel
            {
                wrongCredentials = false;

                // ask about proxy credentials
                if (userPressedOK = ProxyServerAuthenticator.AskAndSetProxyCredentials(
                        _proxyConfigurationService))
                {
                    try
                    {
                        // and repeat license activation if user entered credential and pressed OK
                        var licenseInfo = licenseActivator(licenseUserName, licensePassword); // exception
                        license = licenseInfo.License;
                    }
                    catch (CommunicationException ex)
                    {
                        if (ex.ErrorCode == CommunicationError.ProxyAuthenticationRequired)
                        {
                            wrongCredentials = true;
                            proxyException   = ex;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            } while (userPressedOK && wrongCredentials);

            // if license wasn't obtained - then throw the last proxy exception
            if (license == null)
            {
                throw proxyException;
            }
        }
コード例 #8
0
        /// <summary>
        /// Handles IoT Hub exception and transform it as an <see cref="ApiException"/> with a well-known application error code.
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="iotHubException"></param>
        /// <param name="apiException"></param>
        /// <returns></returns>
        private bool TryHandleIotHubException(string deviceId, IotHubException iotHubException, out ApiException apiException)
        {
            switch (iotHubException)
            {
            // thrown when there's no IoT Hub device registration OR there's an enabled IoT Hub device registration but device did not establish connection yet
            case DeviceNotFoundException ex:
                apiException = new IdNotFoundException(ErrorCodes.DeviceNotFound, deviceId, ex);
                break;

            // thrown when an attempt to communicate with the IoT Hub fails
            case IotHubCommunicationException ex:
                m_Logger.LogWarning($"An IotHubCommunicationException occurred: {ex}");
                apiException = new CommunicationException(ErrorCodes.CommunicationError, ex.Message, ex);
                break;

            // thrown when the IoT Hub returns an error code (i.e. device registration is disable which prevent the actual device from establishing a connection)
            case ServerErrorException ex:
                m_Logger.LogWarning($"A ServerErrorException occurred: {ex}");
                apiException = new CommunicationException(ErrorCodes.GatewayError, ErrorMessages.GetGatewayErrorMessage(), ex);
                break;

            // thrown when the maximum number of IoT Hub messages has been reached
            case QuotaExceededException ex:
                apiException = new CommunicationException(ErrorCodes.QuotaExceeded, ErrorMessages.GetQuotaExceededErrorMessage(), ex);
                break;

            // thrown when the message size is greater than the max size allowed (131072 bytes)
            case MessageTooLargeException ex:
                apiException = new InvalidResultException(ErrorCodes.MessageTooLarge, ErrorMessages.GetMessageTooLargeErrorMessage(), ex);
                break;

            // thrown when an error occurs during device client operation (i.e. device doesn't repond within the configured time out)
            // shall always be kept last
            case IotHubException ex:
                m_Logger.LogWarning($"An IotHubException occurred: {ex}");
                apiException = new OperationException(ErrorCodes.DeviceOperationError, ErrorMessages.GetOperationErrorMessage(), ex);
                break;

            // exception won't be transformed and therefore will be logged accordingly
            default:
                apiException = null;
                break;
            }

            return(apiException != null);
        }
コード例 #9
0
        public void TestTimeoutSet()
        {
            var uri     = "net.pipe://127.0.0.1/testpipename" + MethodBase.GetCurrentMethod().Name;
            var binding = new System.ServiceModel.NetNamedPipeBinding()
            {
                MaxConnections = 5
            };
            var timeout = 700;

            binding.ReceiveTimeout = TimeSpan.FromMilliseconds(timeout);
            var hang = TimeSpan.FromMilliseconds(timeout * 2);

            using (var server = new System.ServiceModel.ServiceHost(new Service(), new Uri(uri)))
            {
                server.AddServiceEndpoint(typeof(IService), binding, uri);
                server.Open();
                var channelFactory = new System.ServiceModel.ChannelFactory <IService>(binding);

                var client = channelFactory.CreateChannel(new EndpointAddress(uri));
                var result = client.Execute(TimeSpan.FromMilliseconds(0));
                Assert.AreEqual(TimeSpan.FromMilliseconds(0), result);
                CommunicationException timeoutHappenedException = null;
                try
                {
                    result = client.Execute(hang);
                }
                catch (CommunicationException ex)
                {
                    timeoutHappenedException = ex;
                }
                Assert.NotNull(timeoutHappenedException);
                Assert.AreEqual(typeof(System.IO.IOException), timeoutHappenedException.InnerException.GetType());
                var channel = client as IContextChannel;
                Assert.AreEqual(CommunicationState.Faulted, channel.State);
                try
                {
                    result = client.Execute(TimeSpan.FromMilliseconds(0));
                }
                catch (CommunicationObjectFaultedException afterTimeoutExeption)
                {
                }
                client = channelFactory.CreateChannel(new EndpointAddress(uri));
                result = client.Execute(TimeSpan.FromMilliseconds(0));
            }
        }
コード例 #10
0
        /// <summary>
        /// Determine the HttpStatusResponse from the protocol exception.
        /// When this fails the Assert.Fail method will be called to prevent further execution.
        /// </summary>
        /// <param name="communicationException">The protocol exception which might the HttpStatusCode</param>
        /// <returns>The HttpStatusResponse enumeration</returns>
        private static HttpStatusResponse DetermineHttpStatusResponse(CommunicationException communicationException)
        {
            if (communicationException != null && communicationException.InnerException != null)
            {
                var webException = communicationException.InnerException as WebException;
                if (webException != null && webException.Response != null)
                {
                    var response = webException.Response as HttpWebResponse;
                    if (response != null)
                    {
                        return(new HttpStatusResponse(response.StatusCode, response.StatusDescription));
                    }
                }
            }

            Assert.Fail("Failed to determine HttpStatusCode from CommunicationException.");
            return(new HttpStatusResponse(HttpStatusCode.InternalServerError, "Failed to determine HttpStatusCode from CommunicationException."));
        }
コード例 #11
0
        public void IncorrectKeyProducesResponseCodeForbidden()
        {
            var provider = BuildProvider("aaaaaaaaaaa");
            CommunicationException exception = null;

            try
            {
                var dto = provider.GetDataAsync(new string[1]).Result;
                Assert.IsNotNull(dto);
            }
            catch (AggregateException ex)
            {
                exception = (CommunicationException)ex.InnerException;
            }

            Assert.IsNotNull(exception, "returned object should not be null");
            Assert.AreEqual(HttpStatusCode.Forbidden, exception.ResponseCode, "Response code of the exception should be forbidden");
        }
コード例 #12
0
            public void then_should_throw_expected_exception()
            {
                CommunicationException exception = null;

                try
                {
                    SUT.VerifyResponse <ExampleModel>(restResponse);
                }
                catch (CommunicationException ex)
                {
                    exception = ex;
                }

                string expectedMessage = $"Error occured while sending message '{restResponse.StatusCode}'";

                exception.ShouldNotBeNull();
                exception.Message.ShouldEqual(expectedMessage);
            }
コード例 #13
0
        private void ReceiveBytes(byte[] bytes, CommunicationException communicationException, GuidClass messageGuid)
        {
            PlcResponseMessage plcResponseMessage = new PlcResponseMessage
            {
                comException         = communicationException,
                responseBytesMessage = bytes
            };

            lock (_lockObj)
            {
                m_responseMessageQueue.Add(messageGuid, plcResponseMessage);
            }

            lock (messageGuid)
            {
                Monitor.PulseAll(messageGuid);
            }
        }
コード例 #14
0
            private bool ContinueAfterCommunicationException(Exception exception)
            {
                if (exception == null)
                {
                    return(true);
                }
                CommunicationException communicationException = exception as CommunicationException;

                if (communicationException == null)
                {
                    base.Complete(exception);
                }
                else
                {
                    base.Complete(MessagingExceptionHelper.Unwrap(communicationException, false));
                }
                return(!base.IsCompleted);
            }
コード例 #15
0
        public void GetStorageKeysProcess()
        {
            Func <string, StorageService>     func = null;
            StorageServiceKeyOperationContext storageServiceKeyOperationContext = null;

            using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
            {
                try
                {
                    GetAzureStorageKeyCommand getAzureStorageKeyCommand = this;
                    if (func == null)
                    {
                        func = (string s) => base.Channel.GetStorageKeys(s, this.StorageAccountName);
                    }
                    StorageService storageService = ((CmdletBase <IServiceManagement>)getAzureStorageKeyCommand).RetryCall <StorageService>(func);
                    if (storageService != null)
                    {
                        StorageServiceKeyOperationContext storageAccountName = new StorageServiceKeyOperationContext();
                        storageAccountName.StorageAccountName = this.StorageAccountName;
                        storageAccountName.Primary            = storageService.StorageServiceKeys.Primary;
                        storageAccountName.Secondary          = storageService.StorageServiceKeys.Secondary;
                        storageServiceKeyOperationContext     = storageAccountName;
                    }
                    Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
                    storageServiceKeyOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
                    storageServiceKeyOperationContext.set_OperationId(operation.OperationTrackingId);
                    storageServiceKeyOperationContext.set_OperationStatus(operation.Status);
                    base.WriteObject(storageServiceKeyOperationContext, true);
                }
                catch (CommunicationException communicationException1)
                {
                    CommunicationException communicationException = communicationException1;
                    if (communicationException as EndpointNotFoundException == null || base.IsVerbose())
                    {
                        this.WriteErrorDetails(communicationException);
                    }
                    else
                    {
                        base.WriteObject(null);
                        return;
                    }
                }
            }
        }
コード例 #16
0
        private async Task StartReceivingAsync()
        {
            try
            {
                while (true)
                {
                    (bool success, RequestContext context) = await Binder.TryReceiveAsync(TimeSpan.MaxValue);

                    if (success)
                    {
                        if (context != null)
                        {
                            using (context)
                            {
                                Message requestMessage = context.RequestMessage;
                                await ProcessMessageAsync(requestMessage);

                                context.Close(DefaultCloseTimeout);
                            }
                        }
                        else
                        {
                            if (!Connection.Closed && (Binder.State == CommunicationState.Opened))
                            {
                                Exception e = new CommunicationException(SR.EarlySecurityClose);
                                ReliableSession.OnLocalFault(e, (Message)null, null);
                            }

                            // Null context means channel is closing
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                ReliableSession.OnUnknownException(e);
            }
        }
コード例 #17
0
        //  size:   sending => the size of the data being sent
        //          Receiving => the max message size we can receive
        //  remoteEndPoint: remote endpoint reported when error occured
        static Exception ConvertNetworkError(SocketException socketException, int size, TransferDirection direction, int timeToLive)
        {
            Exception result = null;

            if (socketException.ErrorCode == UnsafeNativeMethods.ERROR_INVALID_HANDLE)
            {
                //This would likely indicate a bug in our ref-counting
                //for instance, a channel is closing the socket multiple times...
                Fx.Assert("The socket appears to have been closed unexpectedly.  This probably indicates incorrect ref counting (i.e. a channel is closing the socket multiple times)");
                result = new CommunicationObjectAbortedException(socketException.Message, socketException);
            }
            else
            {
                string errorMessage;
                switch (socketException.SocketErrorCode)
                {
                case SocketError.MessageSize:     //10040
                    errorMessage = (direction == TransferDirection.Send ? SR.UdpMaxMessageSendSizeExceeded(size) : SR.MaxReceivedMessageSizeExceeded(size));
                    Exception inner = new QuotaExceededException(errorMessage, socketException);
                    result = new ProtocolException(errorMessage, inner);
                    break;

                case SocketError.NetworkReset:     //10052
                    //ICMP: Time Exceeded (TTL expired)
                    //see http://tools.ietf.org/html/rfc792
                    result = new CommunicationException(SR.IcmpTimeExpired(timeToLive), socketException);
                    break;

                case SocketError.ConnectionReset:     //10054
                    //ICMP: Destination Unreachable (target host/port/etc not reachable)
                    //see http://tools.ietf.org/html/rfc792
                    result = new CommunicationException(SR.IcmpDestinationUnreachable, socketException);
                    break;

                default:
                    errorMessage = (direction == TransferDirection.Send ? SR.UdpSendException : SR.UdpReceiveException);
                    result       = new CommunicationException(errorMessage, socketException);
                    break;
                }
            }

            Fx.Assert(result != null, "we should never return null");
            return(result);
        }
コード例 #18
0
        internal void ProcessMessage11(ref MessageRpc rpc)
        {
            rpc.NextProcessor = _processMessage2;

            if (rpc.Operation.IsOneWay)
            {
                rpc.RequestContext.Reply(null);
                rpc.OperationContext.RequestContext = null;
            }
            else
            {
                if (!rpc.Channel.IsReplyChannel &&
                    ((object)rpc.RequestID == null) &&
                    (rpc.Operation.Action != MessageHeaders.WildcardAction))
                {
                    CommunicationException error = new CommunicationException(SR.SFxOneWayMessageToTwoWayMethod0);
                    throw TraceUtility.ThrowHelperError(error, rpc.Request);
                }

                if (!_manualAddressing)
                {
                    EndpointAddress replyTo = rpc.ReplyToInfo.ReplyTo;
                    if (replyTo != null && replyTo.IsNone && rpc.Channel.IsReplyChannel)
                    {
                        CommunicationException error = new CommunicationException(SR.SFxRequestReplyNone);
                        throw TraceUtility.ThrowHelperError(error, rpc.Request);
                    }
                }
            }

            if (_concurrency.IsConcurrent(ref rpc))
            {
                rpc.Channel.IncrementActivity();
                rpc.SuccessfullyIncrementedActivity = true;
            }

            _instance.EnsureInstanceContext(ref rpc);
            this.TransferChannelFromPendingList(ref rpc);

            if (!rpc.IsPaused)
            {
                this.ProcessMessage2(ref rpc);
            }
        }
コード例 #19
0
        public void SetVirtualNetworkConfigProcess()
        {
            Action <string> action = null;

            this.ValidateParameters();
            FileStream fileStream = null;

            try
            {
                fileStream = new FileStream(this.ConfigurationPath, FileMode.Open);
                using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
                {
                    try
                    {
                        SetAzureVNetConfigCommand setAzureVNetConfigCommand = this;
                        if (action == null)
                        {
                            action = (string s) => base.Channel.SetNetworkConfiguration(s, fileStream);
                        }
                        ((CmdletBase <IServiceManagement>)setAzureVNetConfigCommand).RetryCall(action);
                        Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
                        ManagementOperationContext managementOperationContext = new ManagementOperationContext();
                        managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
                        managementOperationContext.set_OperationId(operation.OperationTrackingId);
                        managementOperationContext.set_OperationStatus(operation.Status);
                        ManagementOperationContext managementOperationContext1 = managementOperationContext;
                        base.WriteObject(managementOperationContext1, true);
                    }
                    catch (CommunicationException communicationException1)
                    {
                        CommunicationException communicationException = communicationException1;
                        this.WriteErrorDetails(communicationException);
                    }
                }
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
コード例 #20
0
        public TResult Excecute <TResult>(
            Func <TIService, TResult> serviceCall,
            int retryAttempts = 1,
            Action <CommunicationException> exceptionHandler = null)
        {
            var errors = 0;
            CommunicationException exception = null;

            while (errors < retryAttempts)
            {
                this.DisposeClient();

                try
                {
                    this._serviceClient = this.CreateClient();
                    return(serviceCall.Invoke(this._serviceClient));
                }
                catch (CommunicationException comsException)
                {
                    exception = comsException;

                    if (exceptionHandler != null)
                    {
                        try
                        {
                            exceptionHandler.Invoke(exception);
                        }
                        catch (CommunicationException reThrowException)
                        {
                            exception = reThrowException;
                        }
                    }

                    errors++;
                }
                finally
                {
                    this.DisposeClient();
                }
            }

            throw exception ?? new CommunicationException(@"Excecution unsuccessfull with no exceptions. Invalid state reached inside 'Service Client Wrapper' for opperation.");
        }
コード例 #21
0
        private void OnInactivityElapsed(object state)
        {
            WsrmFault fault;
            Exception exception;
            string    exceptionMessage = System.ServiceModel.SR.GetString("SequenceTerminatedInactivityTimeoutExceeded", new object[] { this.settings.InactivityTimeout });

            if (this.SequenceID != null)
            {
                string faultReason = System.ServiceModel.SR.GetString("SequenceTerminatedInactivityTimeoutExceeded", new object[] { this.settings.InactivityTimeout });
                fault     = SequenceTerminatedFault.CreateCommunicationFault(this.SequenceID, faultReason, exceptionMessage);
                exception = fault.CreateException();
            }
            else
            {
                fault     = null;
                exception = new CommunicationException(exceptionMessage);
            }
            this.OnLocalFault(exception, fault, null);
        }
コード例 #22
0
        protected override IAsyncResult OnBeginAcceptMessageSession(ReceiveMode receiveMode, TimeSpan serverWaitTime, TimeSpan timeout, AsyncCallback callback, object state)
        {
            IAsyncResult acceptMessageSessionForNamespaceAsyncResult;

            if (this.Settings.EnableRedirect)
            {
                throw new NotSupportedException(Microsoft.ServiceBus.SR.GetString(Resources.AcceptMessageSessionRedirectNotSupported, new object[0]));
            }
            try
            {
                acceptMessageSessionForNamespaceAsyncResult = new AcceptMessageSessionForNamespaceAsyncResult(this, receiveMode, this.PrefetchCount, this.acceptMessageSessionForNamespaceLinkSettings, serverWaitTime, timeout, callback, state);
            }
            catch (CommunicationException communicationException1)
            {
                CommunicationException communicationException = communicationException1;
                throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.AsError(MessagingExceptionHelper.Unwrap(communicationException), null);
            }
            return(acceptMessageSessionForNamespaceAsyncResult);
        }
コード例 #23
0
        public void StopVirtualMachineProcess()
        {
            StopAzureVMCommand.StopAzureVMCommand variable = null;
            string name;

            if (base.CurrentDeployment != null)
            {
                using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
                {
                    try
                    {
                        StopAzureVMCommand.StopAzureVMCommand variable1 = variable;
                        if (base.ParameterSetName == "ByName")
                        {
                            name = this.Name;
                        }
                        else
                        {
                            name = this.VM.RoleName;
                        }
                        variable1.roleName = name;
                        base.RetryCall((string s) => base.Channel.ShutdownRole(s, this.ServiceName, this.CurrentDeployment.Name, LambdaVar44));
                        Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
                        ManagementOperationContext managementOperationContext = new ManagementOperationContext();
                        managementOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
                        managementOperationContext.set_OperationId(operation.OperationTrackingId);
                        managementOperationContext.set_OperationStatus(operation.Status);
                        ManagementOperationContext managementOperationContext1 = managementOperationContext;
                        base.WriteObject(managementOperationContext1, true);
                    }
                    catch (CommunicationException communicationException1)
                    {
                        CommunicationException communicationException = communicationException1;
                        this.WriteErrorDetails(communicationException);
                    }
                }
                return;
            }
            else
            {
                return;
            }
        }
コード例 #24
0
        private void ReceiveString(string responseMessage, CommunicationException communicationException,
                                   GuidClass messageGuid)
        {
            PlcResponseMessage plcResponseMessage = new PlcResponseMessage
            {
                comException          = communicationException,
                responseStringMessage = responseMessage
            };

            lock (_lockObj)
            {
                m_responseMessageQueue.Add(messageGuid, plcResponseMessage);
            }

            lock (messageGuid)
            {
                Monitor.PulseAll(messageGuid);
            }
        }
コード例 #25
0
        public void UpdateDiskProcess()
        {
            string empty = string.Empty;

            using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
            {
                try
                {
                    Disk disk = new Disk();
                    disk.Name  = this.DiskName;
                    disk.Label = this.Label;
                    Disk disk1 = disk;
                    CmdletExtensions.WriteVerboseOutputForObject(this, disk1);
                    Disk disk2 = base.RetryCall <Disk>((string s) => base.Channel.UpdateDisk(s, this.DiskName, disk1));
                    if (disk2 != null)
                    {
                        DiskContext diskContext = new DiskContext();
                        diskContext.set_OperationId(empty);
                        diskContext.DiskName        = disk1.Name;
                        diskContext.Label           = disk1.Label;
                        diskContext.IsCorrupted     = disk1.IsCorrupted;
                        diskContext.AffinityGroup   = disk1.AffinityGroup;
                        diskContext.OS              = disk1.OS;
                        diskContext.Location        = disk1.Location;
                        diskContext.MediaLink       = disk1.MediaLink;
                        diskContext.DiskSizeInGB    = disk1.LogicalDiskSizeInGB;
                        diskContext.SourceImageName = disk1.SourceImageName;
                        diskContext.AttachedTo      = UpdateAzureDiskCommand.CreateRoleReference(disk1.AttachedTo);
                        DiskContext diskContext1 = diskContext;
                        Operation   operation    = base.WaitForOperation(base.CommandRuntime.ToString());
                        diskContext1.set_OperationDescription(base.CommandRuntime.ToString());
                        diskContext1.set_OperationId(operation.OperationTrackingId);
                        diskContext1.set_OperationStatus(operation.Status);
                        base.WriteObject(diskContext1, true);
                    }
                }
                catch (CommunicationException communicationException1)
                {
                    CommunicationException communicationException = communicationException1;
                    this.WriteErrorDetails(communicationException);
                }
            }
        }
コード例 #26
0
        /// <summary>
        /// Exceptions thrown during broker proxy and service host communication
        /// are wrapped into FaultException(ProxyFault) and passed back to
        /// AzureDispatcher. Here we check if the message is a fault message that
        /// carries ProxyFault. If so, extract the inner exception from ProxyFault
        /// and throw it out. Dispatcher will handle the exception as if it is
        /// talking to service host directly.
        /// </summary>
        /// <param name="message">response message</param>
        protected override void PostProcessMessage(Message message)
        {
            if (message.IsFault)
            {
                if (message.Headers.Action == ProxyFault.Action)
                {
                    MessageFault fault = MessageFault.CreateFault(message, int.MaxValue);

                    ProxyFault proxyFault = fault.GetDetail <ProxyFault>();

                    if (proxyFault != null)
                    {
                        // Create exception according to the FaultCode, and mark it as "indirect"
                        // by setting its source to IndirectExceptionMark. This mark will later
                        // be checked by dispatcher to determine if it need to recreate the
                        // underlying WCF channel. For indirect exception, we don't need to
                        // recreate the channel(between dispatcher and broker proxy).
                        Exception e;

                        if (proxyFault.FaultCode == ProxyFault.ProxyEndpointNotFound)
                        {
                            // will throw EndpointNotFoundException for ProxyFault.ProxyEndpointNotFound
                            e = new EndpointNotFoundException(proxyFault.Message);
                        }
                        else if (proxyFault.FaultCode == ProxyFault.ProxyCommunicationException)
                        {
                            // will throw CommunicationException for ProxyFault.ProxyCommunicationException
                            e = new CommunicationException(proxyFault.Message);
                        }
                        else
                        {
                            // will throw general exception for other FaultCode
                            e = new Exception(proxyFault.Message);
                        }

                        e.Source = IndirectExceptionMark;

                        throw e;
                    }
                }
            }
        }
コード例 #27
0
 public void SetStorageAccountProcess()
 {
     if (this.Label == null && this.Description == null)
     {
         base.ThrowTerminatingError(new ErrorRecord(new Exception("You must specify a value for either Label or Description."), string.Empty, ErrorCategory.InvalidData, null));
     }
     using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
     {
         try
         {
             UpdateStorageServiceInput updateStorageServiceInput = new UpdateStorageServiceInput();
             bool?geoReplicationEnabled = this.GeoReplicationEnabled;
             if (geoReplicationEnabled.HasValue)
             {
                 bool?nullable = this.GeoReplicationEnabled;
                 updateStorageServiceInput.GeoReplicationEnabled = new bool?(nullable.Value);
             }
             if (this.Description != null)
             {
                 updateStorageServiceInput.Description = this.Description;
             }
             if (this.Label != null)
             {
                 updateStorageServiceInput.Label = ServiceManagementHelper.EncodeToBase64String(this.Label);
             }
             CmdletExtensions.WriteVerboseOutputForObject(this, updateStorageServiceInput);
             base.RetryCall((string s) => base.Channel.UpdateStorageService(s, this.StorageAccountName, updateStorageServiceInput));
             Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
             ManagementOperationContext managementOperationContext = new ManagementOperationContext();
             managementOperationContext.OperationDescription = base.CommandRuntime.ToString();
             managementOperationContext.OperationId          = operation.OperationTrackingId;
             managementOperationContext.OperationStatus      = operation.Status;
             ManagementOperationContext managementOperationContext1 = managementOperationContext;
             base.WriteObject(managementOperationContext1, true);
         }
         catch (CommunicationException communicationException1)
         {
             CommunicationException communicationException = communicationException1;
             this.WriteErrorDetails(communicationException);
         }
     }
 }
コード例 #28
0
        protected override void WriteErrorDetails(CommunicationException exception)
        {
            ServiceManagementError serviceManagementError = null;

            GatewayManagementHelper.TryGetExceptionDetails(exception, out serviceManagementError);
            if (serviceManagementError != null)
            {
                object[] code = new object[2];
                code[0] = serviceManagementError.Code;
                code[1] = serviceManagementError.Message;
                string str = string.Format(CultureInfo.InvariantCulture, "HTTP Status Code: {0} - HTTP Error Message: {1}", code);
                base.WriteError(new ErrorRecord(new CommunicationException(str), string.Empty, ErrorCategory.CloseError, null));
                return;
            }
            else
            {
                base.WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.CloseError, null));
                return;
            }
        }
コード例 #29
0
        public void NewStorageKeyProcess()
        {
            Func <string, StorageService>     func = null;
            StorageServiceKeyOperationContext storageServiceKeyOperationContext = null;
            RegenerateKeys regenerateKey = new RegenerateKeys();

            regenerateKey.KeyType = this.KeyType;
            RegenerateKeys regenerateKey1 = regenerateKey;

            using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
            {
                try
                {
                    CmdletExtensions.WriteVerboseOutputForObject(this, regenerateKey1);
                    NewAzureStorageKeyCommand newAzureStorageKeyCommand = this;
                    if (func == null)
                    {
                        func = (string s) => base.Channel.RegenerateStorageServiceKeys(s, this.StorageAccountName, regenerateKey1);
                    }
                    StorageService storageService = ((CmdletBase <IServiceManagement>)newAzureStorageKeyCommand).RetryCall <StorageService>(func);
                    if (storageService != null)
                    {
                        StorageServiceKeyOperationContext storageAccountName = new StorageServiceKeyOperationContext();
                        storageAccountName.StorageAccountName = this.StorageAccountName;
                        storageAccountName.Primary            = storageService.StorageServiceKeys.Primary;
                        storageAccountName.Secondary          = storageService.StorageServiceKeys.Secondary;
                        storageServiceKeyOperationContext     = storageAccountName;
                    }
                    Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
                    storageServiceKeyOperationContext.set_OperationDescription(base.CommandRuntime.ToString());
                    storageServiceKeyOperationContext.set_OperationId(operation.OperationTrackingId);
                    storageServiceKeyOperationContext.set_OperationStatus(operation.Status);
                    base.WriteObject(storageServiceKeyOperationContext, true);
                }
                catch (CommunicationException communicationException1)
                {
                    CommunicationException communicationException = communicationException1;
                    this.WriteErrorDetails(communicationException);
                }
            }
        }
コード例 #30
0
        public void TestIsNameAvailableProcess()
        {
            AvailabilityResponse availabilityResponse;
            Func <string, AvailabilityResponse> func  = null;
            Func <string, AvailabilityResponse> func1 = null;

            using (OperationContextScope operationContextScope = new OperationContextScope((IContextChannel)base.Channel))
            {
                try
                {
                    SwitchParameter service = this.Service;
                    if (!service.IsPresent)
                    {
                        TestAzureNameCommand testAzureNameCommand = this;
                        if (func1 == null)
                        {
                            func1 = (string s) => base.Channel.IsStorageServiceAvailable(s, this.Name);
                        }
                        availabilityResponse = ((CmdletBase <IServiceManagement>)testAzureNameCommand).RetryCall <AvailabilityResponse>(func1);
                    }
                    else
                    {
                        TestAzureNameCommand testAzureNameCommand1 = this;
                        if (func == null)
                        {
                            func = (string s) => base.Channel.IsDNSAvailable(s, this.Name);
                        }
                        availabilityResponse = ((CmdletBase <IServiceManagement>)testAzureNameCommand1).RetryCall <AvailabilityResponse>(func);
                    }
                    Operation operation = base.WaitForOperation(base.CommandRuntime.ToString());
                    base.WriteDebug(string.Concat("OperationID: ", operation.OperationTrackingId));
                    bool result = !availabilityResponse.Result;
                    base.WriteObject(result, true);
                }
                catch (CommunicationException communicationException1)
                {
                    CommunicationException communicationException = communicationException1;
                    this.WriteErrorDetails(communicationException);
                }
            }
        }
コード例 #31
0
        /// <summary>
        /// Method show authentication dialog for proxy server until user enter valid credentials or cancels the dialog.
        /// </summary>
        /// <param name="licenseActivator">License activator.</param>
        /// <param name="licenseUserName">License username.</param>
        /// <param name="licensePassword">License password.</param>
        /// <param name="proxyEx">Initial proxy authentication required exception.</param>
        /// <returns></returns>
        private void _AuthenticateProxyServerAndGetLicense(
            Func<string, string, LicenseInfo> licenseActivator,
            string licenseUserName,
            string licensePassword,
            CommunicationException proxyEx)
        {
            bool userPressedOK = false;
            bool wrongCredentials = false;
            License license = null;
            CommunicationException proxyException = proxyEx; // proxy exception that will be thrown if proxy won't be authenticated

            do // repeat showing auth dialog until user either enters correct credentials or presses cancel
            {
                wrongCredentials = false;

                // ask about proxy credentials
                if (userPressedOK = ProxyServerAuthenticator.AskAndSetProxyCredentials(
                    _proxyConfigurationService))
                {
                    try
                    {
                        // and repeat license activation if user entered credential and pressed OK
                        var licenseInfo = licenseActivator(licenseUserName, licensePassword); // exception
                        license = licenseInfo.License;
                    }
                    catch(CommunicationException ex)
                    {
                        if (ex.ErrorCode == CommunicationError.ProxyAuthenticationRequired)
                        {
                            wrongCredentials = true;
                            proxyException = ex;
                        }
                        else
                            throw;
                    }
                }
            } while (userPressedOK && wrongCredentials);

            // if license wasn't obtained - then throw the last proxy exception
            if (license == null)
                throw proxyException;
        }
コード例 #32
0
        private static Exception ConvertTransferException(SocketException socketException, TimeSpan timeout, Exception originalException,
            TransferOperation transferOperation, bool aborted, string timeoutErrorString, TransferOperation timeoutErrorTransferOperation,
            SocketConnection socketConnection, TimeSpan remainingTime)
        {
            if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_INVALID_HANDLE)
            {
                return new CommunicationObjectAbortedException(socketException.Message, socketException);
            }

            if (timeoutErrorString != null)
            {
                return ConvertTimeoutErrorException(originalException, transferOperation, timeoutErrorString, timeoutErrorTransferOperation);
            }

            // 10053 can occur due to our timeout sockopt firing, so map to TimeoutException in that case
            if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNABORTED &&
                remainingTime <= TimeSpan.Zero)
            {
                TimeoutException timeoutException = new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout), originalException);
                return timeoutException;
            }

            if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENETRESET ||
                (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNABORTED ||
                (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNRESET)
            {
                if (aborted)
                {
                    return new CommunicationObjectAbortedException(SR.TcpLocalConnectionAborted, originalException);
                }
                else
                {
                    CommunicationException communicationException = new CommunicationException(SR.Format(SR.TcpConnectionResetError, timeout), originalException);
                    return communicationException;
                }
            }
            else if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAETIMEDOUT)
            {
                TimeoutException timeoutException = new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout), originalException);
                return timeoutException;
            }
            else
            {
                if (aborted)
                {
                    return new CommunicationObjectAbortedException(SR.Format(SR.TcpTransferError, (int)socketException.SocketErrorCode, socketException.Message), originalException);
                }
                else
                {
                    CommunicationException communicationException = new CommunicationException(SR.Format(SR.TcpTransferError, (int)socketException.SocketErrorCode, socketException.Message), originalException);
                    return communicationException;
                }
            }
        }
コード例 #33
0
        internal static Exception ConvertAndTraceException(Exception ex, TimeSpan timeout, string operation)
        {
            ObjectDisposedException objectDisposedException = ex as ObjectDisposedException;
            if (objectDisposedException != null)
            {
                CommunicationObjectAbortedException communicationObjectAbortedException = new CommunicationObjectAbortedException(ex.Message, ex);
                FxTrace.Exception.AsWarning(communicationObjectAbortedException);
                return communicationObjectAbortedException;
            }

            AggregateException aggregationException = ex as AggregateException;
            if (aggregationException != null)
            {
                Exception exception = FxTrace.Exception.AsError<OperationCanceledException>(aggregationException);
                OperationCanceledException operationCanceledException = exception as OperationCanceledException;
                if (operationCanceledException != null)
                {
                    TimeoutException timeoutException = GetTimeoutException(exception, timeout, operation);
                    FxTrace.Exception.AsWarning(timeoutException);
                    return timeoutException;
                }
                else
                {
                    Exception communicationException = ConvertAggregateExceptionToCommunicationException(aggregationException);
                    if (communicationException is CommunicationObjectAbortedException)
                    {
                        FxTrace.Exception.AsWarning(communicationException);
                        return communicationException;
                    }
                    else
                    {
                        return FxTrace.Exception.AsError(communicationException);
                    }
                }
            }

            WebSocketException webSocketException = ex as WebSocketException;
            if (webSocketException != null)
            {
                switch (webSocketException.WebSocketErrorCode)
                {
                    case WebSocketError.InvalidMessageType:
                    case WebSocketError.UnsupportedProtocol:
                    case WebSocketError.UnsupportedVersion:
                        ex = new ProtocolException(ex.Message, ex);
                        break;
                    default:
                        ex = new CommunicationException(ex.Message, ex);
                        break;
                }
            }

            return FxTrace.Exception.AsError(ex);
        }
コード例 #34
0
        internal void ProcessMessage11(ref MessageRpc rpc)
        {
            rpc.NextProcessor = _processMessage2;

            if (rpc.Operation.IsOneWay)
            {
                rpc.RequestContext.Reply(null);
                rpc.OperationContext.RequestContext = null;
            }
            else
            {
                if (!rpc.Channel.IsReplyChannel &&
                    ((object)rpc.RequestID == null) &&
                    (rpc.Operation.Action != MessageHeaders.WildcardAction))
                {
                    CommunicationException error = new CommunicationException(SR.SFxOneWayMessageToTwoWayMethod0);
                    throw TraceUtility.ThrowHelperError(error, rpc.Request);
                }

                if (!_manualAddressing)
                {
                    EndpointAddress replyTo = rpc.ReplyToInfo.ReplyTo;
                    if (replyTo != null && replyTo.IsNone && rpc.Channel.IsReplyChannel)
                    {
                        CommunicationException error = new CommunicationException(SR.SFxRequestReplyNone);
                        throw TraceUtility.ThrowHelperError(error, rpc.Request);
                    }
                }
            }

            if (_concurrency.IsConcurrent(ref rpc))
            {
                rpc.Channel.IncrementActivity();
                rpc.SuccessfullyIncrementedActivity = true;
            }

            _instance.EnsureInstanceContext(ref rpc);
            this.TransferChannelFromPendingList(ref rpc);

            if (!rpc.IsPaused)
            {
                this.ProcessMessage2(ref rpc);
            }
        }