protected override bool HandleReceiveComplete(IAsyncResult result)
 {
     RequestContext context;
     if (!base.Binder.EndTryReceive(result, out context))
     {
         return true;
     }
     if (context == null)
     {
         bool flag2 = false;
         lock (base.ThisLock)
         {
             flag2 = base.Connection.Terminate();
         }
         if (!flag2 && (base.Binder.State == CommunicationState.Opened))
         {
             Exception e = new CommunicationException(System.ServiceModel.SR.GetString("EarlySecurityClose"));
             base.ReliableSession.OnLocalFault(e, (Message) null, null);
         }
         return false;
     }
     WsrmMessageInfo info = WsrmMessageInfo.Get(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion, base.Binder.Channel, base.Binder.GetInnerSession(), context.RequestMessage);
     base.StartReceiving(false);
     this.ProcessRequest(context, info);
     return false;
 }
 /// <summary>
 /// is not found communication exception
 /// </summary>
 /// <param name="exception">Communication Exception</param>
 /// <returns>true if exception caused by resource not found, otherwise, false</returns>
 public static bool IsNotFoundCommunicationException(CommunicationException exception)
 {
     ServiceManagementError error = null;
     string operationId = string.Empty;
     ErrorHelper.TryGetExceptionDetails(exception, out error, out operationId);
     return error != null && error.Code == HttpStatusCode.NotFound.ToString();
 }
        /// <summary>
        /// Get current storage account from azure subscription
        /// </summary>
        /// <returns>A storage account</returns>
        private CloudStorageAccount GetStorageAccountFromSubscription()
        {
            string CurrentStorageAccountName = CurrentSubscription.CurrentStorageAccountName;

            if (string.IsNullOrEmpty(CurrentStorageAccountName))
            {
                throw new ArgumentException(Resources.DefaultStorageCredentialsNotFound);
            }
            else
            {
                WriteDebugLog(String.Format(Resources.UseCurrentStorageAccountFromSubscription, CurrentStorageAccountName, CurrentSubscription.SubscriptionName));

                try
                {
                    //The service channel initialized by subscription
                    return(CurrentSubscription.GetCloudStorageAccount());
                }
                catch (ServiceModel.CommunicationException e)
                {
                    WriteVerboseWithTimestamp(Resources.CannotGetSotrageAccountFromSubscription);

                    if (e.IsNotFoundException())
                    {
                        //Repack the 404 error
                        string errorMessage = String.Format(Resources.CurrentStorageAccountNotFoundOnAzure, CurrentStorageAccountName, CurrentSubscription.SubscriptionName);
                        ServiceModel.CommunicationException exception = new ServiceModel.CommunicationException(errorMessage, e);
                        throw exception;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
 private void Handle(CommunicationException cEx, string additionalInformation = null)
 {
     base.StopWorker();
     _service = null;
     OpenServiceCommunicationAsync();
     Log($"{$"{additionalInformation}: " ?? ""}{cEx}", LogLevel.WARNING);
 }
        public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out HttpStatusCode httpStatusCode, out string operationId)
        {
            errorDetails = null;
            httpStatusCode = 0;
            operationId = null;

            if (exception == null)
            {
                return false;
            }

            if (exception.Message == "Internal Server Error")
            {
                httpStatusCode = HttpStatusCode.InternalServerError;
                return true;
            }

            var wex = exception.InnerException as WebException;

            if (wex == null)
            {
                return false;
            }

            var response = wex.Response as HttpWebResponse;
            if (response == null)
            {
                return false;
            }

            if (response.Headers != null)
            {
                operationId = response.Headers[Constants.OperationTrackingIdHeader];
            }

            using (var s = response.GetResponseStream())
            {
                try
                {
                    if (s == null || s.Length == 0)
                    {
                        return false;
                    }

                    var reader = XmlDictionaryReader.CreateTextReader(s, new XmlDictionaryReaderQuotas());
                    var ser = new DataContractSerializer(typeof(ServiceManagementError));
                    errorDetails = (ServiceManagementError)ser.ReadObject(reader, true);
                }
                catch (Exception)
                {
                    return false;
                }
            }

            return true;
        }
 /// <summary>
 /// Shows <see cref="MessageBox"/> dialog with information about <paramref name="communicationException"/>.
 /// </summary>
 /// <param name="caption">The caption.</param>
 /// <param name="communicationException">The <see cref="CommunicationException"/> which information will be display on <see cref="MessageBox"/>.</param>
 protected void ShowError(string caption, CommunicationException communicationException)
 {
     if (communicationException != null)
       {
     ModalDialogService.ShowMessageBox(ModalDialogService, ServiceFactory, MessageBoxImage.Error, caption,
                                   communicationException.Message,
                                   MessageBoxButton.OK,
                                   (communicationException.InnerException != null)
                                     ? communicationException.InnerException.Message
                                     : string.Empty);
       }
 }
		private static bool IsStatusResourceNotFound(CommunicationException ex)
		{
			WebException innerException = ex.InnerException as WebException;
			if (innerException != null)
			{
				HttpWebResponse response = innerException.Response as HttpWebResponse;
				if (response != null && response.StatusCode == HttpStatusCode.NotFound)
				{
					return true;
				}
			}
			return false;
		}
        /// <summary>
        /// Handles the exception and updates the parameters accodingly
        /// </summary>
        /// <param name="ex">The base exception</param>
        public void HandleException(CommunicationException ex)
        {
            // Checking if the exception came from the code
            if (ex is FaultException)
            {
                // Checking if a log is reqired
                if (_logErrors)
                {
                    _logger.LogTechnicalError(LOG_CATEGORY, _businessErrorMessage + ACTUAL_ERROR_MESSAGE_DELIMITER + ExtractMultiLevelErrorMessage(ex));
                    NeedToRetry = false;
                }

                // Has to be done after the log, because it ends the execution
                if (_throwErrors)
                {
                    // Indicating a business exception
                    throw new Exception(_businessErrorMessage + ACTUAL_ERROR_MESSAGE_DELIMITER + ex.Message, ex);
                }
            }
            else
            {
                // The exception occured in the communication
                // Indicating a failed attempt
                _retriesLeft--;

                // Checking if there are any retries left
                if (AnyRetriesLeft)
                {
                    // Waiting for the cooldown to expire
                    Thread.Sleep(_retryCooldown);
                }
                else
                {
                    // Checking if a log is reqired
                    if (_logErrors)
                    {
                        _logger.LogTechnicalError(LOG_CATEGORY, _connectionErrorMessage + ACTUAL_ERROR_MESSAGE_DELIMITER + ExtractMultiLevelErrorMessage(ex));
                        NeedToRetry = false;
                    }

                    // Has to be done after the log, because it ends the execution
                    if (_throwErrors)
                    {
                        // Indicating a connection exception
                        throw new Exception(_connectionErrorMessage + ACTUAL_ERROR_MESSAGE_DELIMITER + ex.Message, ex);
                    }
                }
            }
        }
        private static string GetDetailedMessage(CommunicationException inner)
        {
            ServiceManagementError error = null;
            ServiceManagementHelper.TryGetExceptionDetails(inner, out error);

            if (error == null)
            {
                return inner.Message;
            }
            else
            {
                string errorDetails = string.Format(
                    CultureInfo.InvariantCulture,
                    "HTTP Status Code: {0} - HTTP Error Message: {1}",
                    error.Code,
                    error.Message);
                return errorDetails;
            }
        }
 public void IsNotFoundExceptionTest()
 {
     string message = "CommunicationExceptionUtilTest";
     CommunicationException exception = new CommunicationException(message);
     Assert.IsFalse(exception.IsNotFoundException());
 }
        static Exception ConvertTransferException(SocketException socketException, TimeSpan timeout, Exception originalException,
            TransferOperation transferOperation, bool aborted, string timeoutErrorString, TransferOperation timeoutErrorTransferOperation,
            SocketConnection socketConnection, TimeSpan remainingTime)
        {
            if (socketException.ErrorCode == UnsafeNativeMethods.ERROR_INVALID_HANDLE)
            {
                return new CommunicationObjectAbortedException(socketException.Message, socketException);
            }

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

            TraceEventType exceptionEventType = socketConnection == null ? TraceEventType.Error : socketConnection.ExceptionEventType;

            // 10053 can occur due to our timeout sockopt firing, so map to TimeoutException in that case
            if (socketException.ErrorCode == UnsafeNativeMethods.WSAECONNABORTED &&
                remainingTime <= TimeSpan.Zero)
            {
                TimeoutException timeoutException = new TimeoutException(SR.GetString(SR.TcpConnectionTimedOut, timeout), originalException);
                if (TD.TcpConnectionTimedOutIsEnabled())
                {
                    if (socketConnection != null)
                    {
                        int socketid = (socketConnection != null && socketConnection.socket != null) ? socketConnection.socket.GetHashCode() : -1;
                        TD.TcpConnectionTimedOut(socketid, socketConnection.RemoteEndpointAddress);
                    }
                }
                if (DiagnosticUtility.ShouldTrace(exceptionEventType))
                {
                    TraceUtility.TraceEvent(exceptionEventType, TraceCode.TcpConnectionTimedOut, GetEndpointString(SR.TcpConnectionTimedOut, timeout, null, socketConnection), timeoutException, null);
                }
                return timeoutException;
            }

            if (socketException.ErrorCode == UnsafeNativeMethods.WSAENETRESET ||
                socketException.ErrorCode == UnsafeNativeMethods.WSAECONNABORTED ||
                socketException.ErrorCode == UnsafeNativeMethods.WSAECONNRESET)
            {
                if (aborted)
                {
                    return new CommunicationObjectAbortedException(SR.GetString(SR.TcpLocalConnectionAborted), originalException);
                }
                else
                {
                    CommunicationException communicationException = new CommunicationException(SR.GetString(SR.TcpConnectionResetError, timeout), originalException);
                    if (TD.TcpConnectionResetErrorIsEnabled())
                    {
                        if (socketConnection != null)
                        {
                            int socketId = (socketConnection.socket != null) ? socketConnection.socket.GetHashCode() : -1;
                            TD.TcpConnectionResetError(socketId, socketConnection.RemoteEndpointAddress);
                        }
                    }
                    if (DiagnosticUtility.ShouldTrace(exceptionEventType))
                    {
                        TraceUtility.TraceEvent(exceptionEventType, TraceCode.TcpConnectionResetError, GetEndpointString(SR.TcpConnectionResetError, timeout, null, socketConnection), communicationException, null);
                    }
                    return communicationException;
                }
            }
            else if (socketException.ErrorCode == UnsafeNativeMethods.WSAETIMEDOUT)
            {
                TimeoutException timeoutException = new TimeoutException(SR.GetString(SR.TcpConnectionTimedOut, timeout), originalException);
                if (DiagnosticUtility.ShouldTrace(exceptionEventType))
                {
                    TraceUtility.TraceEvent(exceptionEventType, TraceCode.TcpConnectionTimedOut, GetEndpointString(SR.TcpConnectionTimedOut, timeout, null, socketConnection), timeoutException, null);
                }
                return timeoutException;
            }
            else
            {
                if (aborted)
                {
                    return new CommunicationObjectAbortedException(SR.GetString(SR.TcpTransferError, socketException.ErrorCode, socketException.Message), originalException);
                }
                else
                {
                    CommunicationException communicationException = new CommunicationException(SR.GetString(SR.TcpTransferError, socketException.ErrorCode, socketException.Message), originalException);
                    if (DiagnosticUtility.ShouldTrace(exceptionEventType))
                    {
                        TraceUtility.TraceEvent(exceptionEventType, TraceCode.TcpTransferError, GetEndpointString(SR.TcpTransferError, TimeSpan.MinValue, socketException, socketConnection), communicationException, null);
                    }
                    return communicationException;
                }
            }
        }
 protected void OnMessageException(Microsoft.Transactions.Wsat.Messaging.RequestAsyncResult result, Message message, CommunicationException exception, Fault fault)
 {
     DebugTrace.Trace(TraceLevel.Warning, "{0} - {1} reading request with action {2}: {3}", base.GetType().Name, exception.GetType().Name, message.Headers.Action, exception.Message);
     this.SendFaultReply(result, fault);
     DebugTrace.Trace(TraceLevel.Warning, "Replied with {0} fault", fault.Code.Name);
 }
Beispiel #13
0
 /// <summary>
 /// Handles communication exceptions
 /// </summary>
 void ThrowCommunicationException(CommunicationException ex)
 {
     System.Diagnostics.Debug.WriteLine(ex.Message + "\n" + ex.StackTrace);
       string message = "There was a problem communicating with the service.";
       throw new SockeyeChannelException(message);
 }
		public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out HttpStatusCode httpStatusCode, out string operationId)
		{
			bool flag;
			errorDetails = null;
			httpStatusCode = 0;
			operationId = null;
			if (exception != null)
			{
				if (exception.Message != "Internal Server Error")
				{
					WebException innerException = exception.InnerException as WebException;
					if (innerException != null)
					{
						HttpWebResponse response = innerException.Response as HttpWebResponse;
						if (response != null)
						{
							httpStatusCode = response.StatusCode;
							if ((int)httpStatusCode != 0x193)
							{
								if (response.Headers != null)
								{
									operationId = response.Headers["x-ms-request-id"];
								}
								Stream responseStream = response.GetResponseStream();
								using (responseStream)
								{
									if (responseStream.Length != (long)0)
									{
										try
										{
											XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateTextReader(responseStream, new XmlDictionaryReaderQuotas());
											using (xmlDictionaryReader)
											{
												DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(ServiceManagementError));
												errorDetails = (ServiceManagementError)dataContractSerializer.ReadObject(xmlDictionaryReader, true);
											}
										}
										catch (SerializationException serializationException)
										{
											flag = false;
											return flag;
										}
										return true;
									}
									else
									{
										flag = false;
									}
								}
								return flag;
							}
							else
							{
								try
								{
									Stream stream = response.GetResponseStream();
									using (stream)
									{
										XmlDictionaryReader xmlDictionaryReader1 = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
										using (xmlDictionaryReader1)
										{
											DataContractSerializer dataContractSerializer1 = new DataContractSerializer(typeof(ServiceManagementError));
											errorDetails = (ServiceManagementError)dataContractSerializer1.ReadObject(xmlDictionaryReader1, true);
										}
									}
								}
								catch
								{
								}
								return true;
							}
						}
						else
						{
							return false;
						}
					}
					else
					{
						return false;
					}
				}
				else
				{
					httpStatusCode = HttpStatusCode.InternalServerError;
					return true;
				}
			}
			else
			{
				return false;
			}
		}
Beispiel #15
0
 /// <summary>
 /// Handles a communication exception during publishing
 /// </summary>
 /// <param name="CommunicationException"></param>
 private void FinishWithCommunicationException(CommunicationException ce)
 {
     boolError = true;
     string statusMessage = "A Communication error occurred while trying to publish the survey.";
     AddStatusMessage(statusMessage);
     txtStatusSummary.Text = statusMessage;
     txtStatus.AppendText(ce.ToString());
     btnShowLog.Enabled = true;
     btnDetails.Visible = true;
     this.progressBar.Visible = false;
     this.Cursor = Cursors.Default;
     panel2.Visible = false;
     lblSuccessNotice.Text = "A Communication error occurred while trying to publish the survey.";
     lblSuccessNotice.BackColor = Color.FromArgb(243, 217, 217);
     panel3.Visible = true;
     lblSuccessNotice2.Visible = false;
     btnPublishForm.Enabled = false;
 }
        private IMethodReturn HandleCookieExpirationExceptionForIntegration(CommunicationException exception, IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            //Application crashes when launched while Active Directory credentials are expired (often due to not logging off overnight)
             //string ADExpired = "Your credentials have expired";
            string ADExpired = WebSealSettings.GetADAccountExpiredExceptionKeySetting();
             if (exception.Message.Contains(ADExpired))
             {
                 //It will immediately quit
                 return input.CreateExceptionMethodReturn(new ADCredentialsExpiredException());
             }

            WebException webException = exception.InnerException as WebException;
             if (webException == null)
             {
                 //Even if it is sessionRenewException, also will come to here.
                 return input.CreateExceptionMethodReturn(exception);
             }

             if ((!webException.Message.Contains("403")) && (!webException.Message.Contains("401")))
             {
                 return input.CreateExceptionMethodReturn(exception);
             }

             if (HiiP.Framework.Security.AccessControl.Authentication.AuthenticationManager.AuthenticationMode == AuthenticationMode.Integration)
             {
                 HiiP.Framework.Security.AccessControl.Authentication.AuthenticationManager.Login();
                 return this.Invoke(input, getNext);
             }

             return input.CreateExceptionMethodReturn(exception);
        }
 private void OnReceiveCompleted(IAsyncResult result)
 {
     RequestContext context;
     if (base.Binder.EndTryReceive(result, out context))
     {
         if (context != null)
         {
             using (context)
             {
                 Message requestMessage = context.RequestMessage;
                 base.ProcessMessage(requestMessage);
                 context.Close(this.DefaultCloseTimeout);
             }
             base.Binder.BeginTryReceive(TimeSpan.MaxValue, onReceiveCompleted, this);
         }
         else if (!base.Connection.Closed && (base.Binder.State == CommunicationState.Opened))
         {
             Exception e = new CommunicationException(System.ServiceModel.SR.GetString("EarlySecurityClose"));
             base.ReliableSession.OnLocalFault(e, (Message) null, null);
         }
     }
     else
     {
         base.Binder.BeginTryReceive(TimeSpan.MaxValue, onReceiveCompleted, this);
     }
 }
Beispiel #18
0
		public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out HttpStatusCode httpStatusCode, out string operationId)
		{
			bool flag;
			errorDetails = null;
			httpStatusCode = 0;
			operationId = null;
			if (exception != null)
			{
				if (exception.Message != "Internal Server Error")
				{
					WebException innerException = exception.InnerException as WebException;
					if (innerException != null)
					{
						HttpWebResponse response = innerException.Response as HttpWebResponse;
						if (response != null)
						{
							if (response.Headers != null)
							{
								operationId = response.Headers["x-ms-request-id"];
							}
							if (response.StatusCode != HttpStatusCode.NotFound)
							{
								Stream responseStream = response.GetResponseStream();
								using (responseStream)
								{
									if (responseStream.Length != (long)0)
									{
										try
										{
											errorDetails = new ServiceManagementError();
											responseStream.Seek((long)0, SeekOrigin.Begin);
											StreamReader streamReader = new StreamReader(responseStream);
											using (StringReader stringReader = new StringReader(streamReader.ReadToEnd()))
											{
												XmlReader xmlReader = XmlReader.Create(stringReader);
												while (xmlReader.Read())
												{
													XmlNodeType nodeType = xmlReader.NodeType;
													if (nodeType != XmlNodeType.Element)
													{
														continue;
													}
													if (xmlReader.Name != "Code")
													{
														if (xmlReader.Name != "Message")
														{
															continue;
														}
														xmlReader.Read();
														errorDetails.Message = xmlReader.Value;
													}
													else
													{
														xmlReader.Read();
														errorDetails.Code = xmlReader.Value;
													}
												}
											}
										}
										catch (SerializationException serializationException)
										{
											flag = false;
											return flag;
										}
										return true;
									}
									else
									{
										flag = false;
									}
								}
								return flag;
							}
							else
							{
								errorDetails = new ServiceManagementError();
								errorDetails.Message = string.Concat(response.ResponseUri.AbsoluteUri, " does not exist.");
								errorDetails.Code = response.StatusCode.ToString();
								return false;
							}
						}
						else
						{
							return false;
						}
					}
					else
					{
						return false;
					}
				}
				else
				{
					httpStatusCode = HttpStatusCode.InternalServerError;
					return true;
				}
			}
			else
			{
				return false;
			}
		}
Beispiel #19
0
        private bool shouldRetry(CommunicationException ce)
        {
            for (Exception e = ce; e != null; e = e.InnerException)
            {
                // there was a temporary communication error
                System.Net.Sockets.SocketException se = e as System.Net.Sockets.SocketException;
                if (se != null)
                {
                    return true;
                }
                // continue to inner exception
            }

            // do not retry
            return false;
        }
		public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails)
		{
			HttpStatusCode httpStatusCode = 0;
			string str = null;
			return ServiceManagementHelper.TryGetExceptionDetails(exception, out errorDetails, out httpStatusCode, out str);
		}
        public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out HttpStatusCode httpStatusCode, out string operationId)
        {
            errorDetails = null;
            httpStatusCode = 0;
            operationId = null;

            if (exception == null)
            {
                return false;
            }

            if (exception.Message == "Internal Server Error")
            {
                httpStatusCode = HttpStatusCode.InternalServerError;
                return true;
            }

            WebException wex = exception.InnerException as WebException;

            if (wex == null)
            {
                return false;
            }

            HttpWebResponse response = wex.Response as HttpWebResponse;
            if (response == null)
            {
                return false;
            }

            //httpStatusCode = response.StatusCode;
            //if (httpStatusCode == HttpStatusCode.Forbidden)
            //{
            //    return true;
            //}

            if (response.Headers != null)
            {
                operationId = response.Headers[Constants.OperationTrackingIdHeader];
            }

            // Don't wrap responseStream in a using statement to prevent it
            // from being disposed twice (as it's disposed by reader if it is
            // successfully disposed).
            Stream responseStream = null;
            try
            {
                responseStream = response.GetResponseStream();
                if (responseStream.Length == 0)
                {
                    return false;
                }

                try
                {
                    using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(responseStream, new XmlDictionaryReaderQuotas()))
                    {
                        // Release the reference to responseStream since it
                        // will be closed when the reader is diposed
                        responseStream = null;

                        DataContractSerializer ser = new DataContractSerializer(typeof(ServiceManagementError));
                        errorDetails = (ServiceManagementError)ser.ReadObject(reader, true);
                    }
                }
                catch (SerializationException)
                {
                    return false;
                }
            }
            finally
            {
                if (responseStream != null)
                {
                    responseStream.Dispose();
                }
            }

            return true;
        }
        void OnInactivityElapsed(object state)
        {
            WsrmFault fault;
            Exception e;
            string exceptionMessage = SR.GetString(SR.SequenceTerminatedInactivityTimeoutExceeded, this.settings.InactivityTimeout);

            if (TD.InactivityTimeoutIsEnabled())
            {
                TD.InactivityTimeout(exceptionMessage);
            }

            if (this.SequenceID != null)
            {
                string faultReason = SR.GetString(SR.SequenceTerminatedInactivityTimeoutExceeded, this.settings.InactivityTimeout);
                fault = SequenceTerminatedFault.CreateCommunicationFault(this.SequenceID, faultReason, exceptionMessage);
                e = fault.CreateException();
            }
            else
            {
                fault = null;
                e = new CommunicationException(exceptionMessage);
            }

            OnLocalFault(e, fault, null);
        }
        internal void ProcessMessage11(ref MessageRpc rpc)
        {
            rpc.NextProcessor = this.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.GetString(SR.SFxOneWayMessageToTwoWayMethod0));
                    throw TraceUtility.ThrowHelperError(error, rpc.Request);
                }

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

                    if (this.isOnServer)
                    {
                        EndpointAddress remoteAddress = rpc.Channel.RemoteAddress;
                        if ((remoteAddress != null) && !remoteAddress.IsAnonymous)
                        {
                            MessageHeaders headers = rpc.Request.Headers;
                            Uri remoteUri = remoteAddress.Uri;

                            if ((replyTo != null) && !replyTo.IsAnonymous && (remoteUri != replyTo.Uri))
                            {
                                string text = SR.GetString(SR.SFxRequestHasInvalidReplyToOnServer, replyTo.Uri, remoteUri);
                                Exception error = new InvalidOperationException(text);
                                throw TraceUtility.ThrowHelperError(error, rpc.Request);
                            }

                            EndpointAddress faultTo = headers.FaultTo;
                            if ((faultTo != null) && !faultTo.IsAnonymous && (remoteUri != faultTo.Uri))
                            {
                                string text = SR.GetString(SR.SFxRequestHasInvalidFaultToOnServer, faultTo.Uri, remoteUri);
                                Exception error = new InvalidOperationException(text);
                                throw TraceUtility.ThrowHelperError(error, rpc.Request);
                            }

                            if (rpc.RequestVersion.Addressing == AddressingVersion.WSAddressingAugust2004)
                            {
                                EndpointAddress from = headers.From;
                                if ((from != null) && !from.IsAnonymous && (remoteUri != from.Uri))
                                {
                                    string text = SR.GetString(SR.SFxRequestHasInvalidFromOnServer, from.Uri, remoteUri);
                                    Exception error = new InvalidOperationException(text);
                                    throw TraceUtility.ThrowHelperError(error, rpc.Request);
                                }
                            }
                        }
                    }
                }
            }

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

            if (this.authenticationBehavior != null)
            {
                this.authenticationBehavior.Authenticate(ref rpc);
            }

            if (this.authorizationBehavior != null)
            {
                this.authorizationBehavior.Authorize(ref rpc);
            }

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

            this.AcquireDynamicInstanceContext(ref rpc);

            if (!rpc.IsPaused)
            {
                this.ProcessMessage2(ref rpc);
            }
        }
 public void IsNotFoundExceptionTest()
 {
     string message = "CommunicationExceptionUtilTest";
     CommunicationException exception = new CommunicationException(message);
 }
Beispiel #25
0
 /// <summary>
 /// Validate the communicationException to see whether the HttpStatusCode matches the expectation
 /// </summary>
 /// <param name="communicationException"></param>
 /// <param name="httpStatusCode"></param>
 private static void ValidateHttpStatusResponse(CommunicationException communicationException, HttpStatusCode httpStatusCode)
 {
     HttpStatusResponse httpStatusResponse = DetermineHttpStatusResponse(communicationException);
     Assert.AreEqual(httpStatusCode, httpStatusResponse.HttpStatusCode, string.Format("Unexpected HttpStatusCode received : {0}", httpStatusResponse.HttpStatusDescription));
 }
Beispiel #26
0
 public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out string operationId)
 {
     HttpStatusCode httpStatusCode;
     return TryGetExceptionDetails(exception, out errorDetails, out httpStatusCode, out operationId);
 }
Beispiel #27
0
        protected void RethrowCommunicationError(CommunicationException ce, ServiceManagementError error)
        {
            String message = ce.Message;

            if (error != null)
            {
                message = error.Message + " (" + error.Code + ")";
            }
            else if (ce is MessageSecurityException)
            {
                message =
                    ce.Message + ". Check SubscriptionId is correct: " + SubscriptionId + " " +
                    "Check certificate with the thumbrint " + CertificateThumbprint + " " +
                    "is configured as management certificate in azure portal.";

            }
            throw new CSManageException(message, ce);
        }
Beispiel #28
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.");
        }
 public CommunicationExceptionEx(CommunicationException inner)
     : base(GetDetailedMessage(inner),inner)
 {
 }
Beispiel #30
0
        public static bool TryGetExceptionDetails(CommunicationException exception, out ServiceManagementError errorDetails, out HttpStatusCode httpStatusCode, out string operationId)
        {
            errorDetails = null;
            httpStatusCode = 0;
            operationId = null;

            if (exception == null)
            {
                return false;
            }

            if (exception.Message == "Internal Server Error")
            {
                httpStatusCode = HttpStatusCode.InternalServerError;
                return false;
            }

            WebException wex = exception.InnerException as WebException;

            if (wex == null)
            {
                return false;
            }

            HttpWebResponse response = wex.Response as HttpWebResponse;
            if (response == null)
            {
                return false;
            }

            if (response.Headers != null)
            {
                operationId = response.Headers[Constants.OperationTrackingIdHeader];
            }

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                errorDetails = new ServiceManagementError();
                errorDetails.Message = response.ResponseUri.AbsoluteUri + " does not exist.";
                errorDetails.Code = response.StatusCode.ToString();
                return false;
            }

            using (var s = response.GetResponseStream())
            {
                if (s.Length == 0)
                {
                    return false;
                }

                try
                {
                    errorDetails = new ServiceManagementError();
                    s.Seek(0, SeekOrigin.Begin);

                    var sr = new StreamReader(s);
                    using (var err = new StringReader(sr.ReadToEnd()))
                    {
                        var reader = XmlReader.Create(err);

                        while (reader.Read())
                        {
                            switch (reader.NodeType)
                            {
                                case XmlNodeType.Element:
                                    {
                                        if (reader.Name == "Code")
                                        {
                                            reader.Read();
                                            errorDetails.Code = reader.Value;
                                        }
                                        else if (reader.Name == "Message")
                                        {
                                            reader.Read();
                                            errorDetails.Message = reader.Value;
                                        }

                                        break;
                                    }
                            }
                        }
                    }
                }
                catch
                {
                    errorDetails = null;
                    return false;
                }
            }

            return true;
        }
 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);
     }
 }