public override void SetUp() { base.SetUp(); this.exception = new ProtocolException("Some failure"); this.response = new FailedAuthenticationResponse(this.exception); }
public void CtorWithTextMessageAndInnerException() { Exception innerException = new Exception(); ProtocolException ex = new ProtocolException("message", innerException); Assert.AreEqual("message", ex.Message); Assert.AreSame(innerException, ex.InnerException); }
private static HttpResponseMessage BearerHttpResponseMessageError(ProtocolException protocolException) { var faultResponseException = protocolException as ProtocolFaultResponseException; var unauthResponse = faultResponseException.ErrorResponseMessage as UnauthorizedResponse; var bearerResponse = BuildBearerAuthorizeResponse(unauthResponse.HttpStatusCode, unauthResponse.ErrorCode, unauthResponse.ErrorDescription); return bearerResponse; }
/// <summary> /// Discovers what access the client should have considering the access token in the current request. /// </summary> /// <param name="requestMessage">The request message.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="requiredScopes">The set of scopes required to approve this request.</param> /// <returns> /// The access token describing the authorization the client has. Never <c>null</c>. /// </returns> /// <exception cref="ProtocolFaultResponseException">Thrown when the client is not authorized. This exception should be caught and the /// <see cref="ProtocolFaultResponseException.ErrorResponseMessage" /> message should be returned to the client.</exception> public virtual async Task <AccessToken> GetAccessTokenAsync(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default(CancellationToken), params string[] requiredScopes) { Requires.NotNull(requestMessage, "requestMessage"); Requires.NotNull(requiredScopes, "requiredScopes"); RequiresEx.ValidState(this.ScopeSatisfiedCheck != null, Strings.RequiredPropertyNotYetPreset); AccessToken accessToken; AccessProtectedResourceRequest request = null; try { request = await this.Channel.TryReadFromRequestAsync <AccessProtectedResourceRequest>(requestMessage, cancellationToken); if (request != null) { accessToken = this.AccessTokenAnalyzer.DeserializeAccessToken(request, request.AccessToken); ErrorUtilities.VerifyHost(accessToken != null, "IAccessTokenAnalyzer.DeserializeAccessToken returned a null result."); if (string.IsNullOrEmpty(accessToken.User) && string.IsNullOrEmpty(accessToken.ClientIdentifier)) { Logger.OAuth.Error("Access token rejected because both the username and client id properties were null or empty."); ErrorUtilities.ThrowProtocol(ResourceServerStrings.InvalidAccessToken); } var requiredScopesSet = OAuthUtilities.ParseScopeSet(requiredScopes); if (!this.ScopeSatisfiedCheck.IsScopeSatisfied(requiredScope: requiredScopesSet, grantedScope: accessToken.Scope)) { var response = UnauthorizedResponse.InsufficientScope(request, requiredScopesSet); throw new ProtocolFaultResponseException(this.Channel, response); } return(accessToken); } else { var ex = new ProtocolException(ResourceServerStrings.MissingAccessToken); var response = UnauthorizedResponse.InvalidRequest(ex); throw new ProtocolFaultResponseException(this.Channel, response, innerException: ex); } } catch (ProtocolException ex) { if (ex is ProtocolFaultResponseException) { // This doesn't need to be wrapped again. throw; } var response = request != null?UnauthorizedResponse.InvalidToken(request, ex) : UnauthorizedResponse.InvalidRequest(ex); throw new ProtocolFaultResponseException(this.Channel, response, innerException: ex); } }
void SetupSecurityIfNecessary(StreamUpgradeAcceptor upgradeAcceptor) { StreamSecurityUpgradeAcceptor securityUpgradeAcceptor = upgradeAcceptor as StreamSecurityUpgradeAcceptor; if (securityUpgradeAcceptor != null) { security = securityUpgradeAcceptor.GetRemoteSecurity(); if (security == null) { Exception securityFailedException = new ProtocolException( SR.Format(SR.RemoteSecurityNotNegotiatedOnStreamUpgrade, Via)); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(securityFailedException); } } }
private void SetupSecurityIfNecessary(StreamUpgradeAcceptor upgradeAcceptor) { StreamSecurityUpgradeAcceptor securityUpgradeAcceptor = upgradeAcceptor as StreamSecurityUpgradeAcceptor; if (securityUpgradeAcceptor != null) { this.security = securityUpgradeAcceptor.GetRemoteSecurity(); if (this.security == null) { Exception exception = new ProtocolException(System.ServiceModel.SR.GetString("RemoteSecurityNotNegotiatedOnStreamUpgrade", new object[] { this.Via })); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception); } this.WriteAuditEvent(securityUpgradeAcceptor, AuditLevel.Success, null); } }
bool HandleCloseInputSession(IAsyncResult result, bool isStillSynchronous) { Message message = this.channel.messageSource.EndReceive(result); if (message != null) { using (message) { ProtocolException error = ProtocolException.ReceiveShutdownReturnedNonNull(message); throw TraceUtility.ThrowHelperError(error, message); } } this.channel.OnInputSessionClosed(); return(this.ScheduleCompleteClose(isStillSynchronous)); }
private bool HandleCloseInputSession(IAsyncResult result, bool isStillSynchronous) { Message message = this.channel.messageSource.EndReceive(result); if (message != null) { using (message) { Type type = typeof(ProtocolException); object[] objArray = new object[] { message }; ProtocolException protocolException = (ProtocolException)InvokeHelper.InvokeStaticMethod(type, "ReceiveShutdownReturnedNonNull", objArray); throw TraceUtility.ThrowHelperError(protocolException, message); } } this.channel.OnInputSessionClosed(); return(this.ScheduleCompleteClose(isStillSynchronous)); }
private void SetupSecurityIfNecessary(StreamUpgradeAcceptor upgradeAcceptor) { StreamSecurityUpgradeAcceptor streamSecurityUpgradeAcceptor = upgradeAcceptor as StreamSecurityUpgradeAcceptor; if (streamSecurityUpgradeAcceptor != null) { this.security = streamSecurityUpgradeAcceptor.GetRemoteSecurity(); if (this.security == null) { string remoteSecurityNotNegotiatedOnStreamUpgrade = Resources.RemoteSecurityNotNegotiatedOnStreamUpgrade; object[] via = new object[] { this.Via }; Exception protocolException = new ProtocolException(Microsoft.ServiceBus.SR.GetString(remoteSecurityNotNegotiatedOnStreamUpgrade, via)); throw Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.ThrowHelperError(protocolException); } this.WriteAuditEvent(streamSecurityUpgradeAcceptor, AuditLevel.Success, null); } }
public void LogOn_post_should_add_openId_exception_message_in_modelState_when_exception_occurrs() { var authRequest = new Mock <IAuthenticationRequest>(); controller.MockHttpContext("/", "~/LogOn", "Post"); openIdRelayingParty.Setup(o => o.CreateRequest(It.IsAny <Identifier>(), It.IsAny <Realm>())).Returns(authRequest.Object); var exception = new ProtocolException("Exception Message"); authRequest.Setup(r => r.RedirectToProvider()).Throws(exception); controller.LogOn(new LogOnCommand { UserName = "******", RememberMe = false }); Assert.Equal(exception.Message, controller.ModelState[AuthenticationController.ModelStateUserNameKey].Errors[0].ErrorMessage); }
// 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); }
public static Fault Resolve( ProtocolException exception, Type[] expectedFaults, out string serializedFault) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } serializedFault = null; if (!(exception.InnerException is WebException wx)) { return(null); } return(Resolve(wx, expectedFaults, out serializedFault)); }
protected override void OnClose(TimeSpan timeout) { TimeoutHelper helper = new TimeoutHelper(timeout); this.CloseOutputSession(helper.RemainingTime()); if (!this.isInputSessionClosed) { Message message = this.messageSource.Receive(helper.RemainingTime()); if (message != null) { using (message) { throw TraceUtility.ThrowHelperError(ProtocolException.ReceiveShutdownReturnedNonNull(message), message); } } this.OnInputSessionClosed(); } this.CompleteClose(helper.RemainingTime()); }
public static void UnknownUrl_Throws_ProtocolException() { string protocolExceptionUri = Endpoints.HttpProtocolError_Address; BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(10000); using (ChannelFactory <IWcfService> factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(protocolExceptionUri))) { IWcfService serviceProxy = factory.CreateChannel(); ProtocolException exception = Assert.Throws <ProtocolException>(() => { string response = serviceProxy.Echo("Hello"); }); // On .Net Native retail, exception message is stripped to include only parameter Assert.True(exception.Message.Contains(protocolExceptionUri), string.Format("Expected exception message to contain '{0}'", protocolExceptionUri)); } }
private static void SetupSecurityIfNecessary(FramingConnection connection) { if (connection.StreamUpgradeAcceptor is StreamSecurityUpgradeAcceptor securityUpgradeAcceptor) { Security.SecurityMessageProperty remoteSecurity = securityUpgradeAcceptor.GetRemoteSecurity(); if (remoteSecurity == null) { Exception securityFailedException = new ProtocolException( SR.Format(SR.RemoteSecurityNotNegotiatedOnStreamUpgrade, connection.Via)); //WriteAuditFailure(securityUpgradeAcceptor, securityFailedException); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(securityFailedException); } else { connection.SecurityMessageProperty = remoteSecurity; // Audit Authentication Success //WriteAuditEvent(securityUpgradeAcceptor, AuditLevel.Success, null); } } }
protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); this.CloseOutputSession(timeoutHelper.RemainingTime()); if (!this.isInputSessionClosed) { Message message = this.messageSource.Receive(timeoutHelper.RemainingTime()); if (message != null) { using (message) { Type type = typeof(ProtocolException); object[] objArray = new object[] { message }; ProtocolException protocolException = (ProtocolException)InvokeHelper.InvokeStaticMethod(type, "ReceiveShutdownReturnedNonNull", objArray); throw TraceUtility.ThrowHelperError(protocolException, message); } } this.OnInputSessionClosed(); } this.CompleteClose(timeoutHelper.RemainingTime()); }
void SetupSecurityIfNecessary() { StreamSecurityUpgradeAcceptor securityUpgradeAcceptor = upgradeAcceptor as StreamSecurityUpgradeAcceptor; if (securityUpgradeAcceptor != null) { RemoteSecurity = securityUpgradeAcceptor.GetRemoteSecurity(); if (RemoteSecurity == null) { Exception securityFailedException = new ProtocolException( SR.Format(SR.RemoteSecurityNotNegotiatedOnStreamUpgrade, Via)); WriteAuditFailure(securityUpgradeAcceptor, securityFailedException); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(securityFailedException); } else { // Audit Authentication Success // WriteAuditEvent(securityUpgradeAcceptor, AuditLevel.Success, null); } } }
public static Neo4jException ParseServerException(string code, string message) { Neo4jException error; var parts = code.Split('.'); var classification = parts[1].ToLowerInvariant(); switch (classification) { case "clienterror": if (AuthenticationException.IsAuthenticationError(code)) { error = new AuthenticationException(message); } else if (ProtocolException.IsProtocolError(code)) { error = new ProtocolException(code, message); } else if (FatalDiscoveryException.IsFatalDiscoveryError(code)) { error = new FatalDiscoveryException(code, message); } else { error = new ClientException(code, message); } break; case "transienterror": error = new TransientException(code, message); break; default: error = new DatabaseException(code, message); break; } return(error); }
/// <inheritdoc /> public void ConvertFrom(Type givenType, object instance, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (instance == null) { return; } if (!givenType.IsInstanceOfType(instance)) { throw new InvalidOperationException(String.Format("Instance type '{0}' mismatch from the given '{1}'.", instance.GetType(), givenType)); } ProtocolException exception = ((Exception)instance).AsHttpException(); ResponseInfo responseInfo = (ResponseInfo)response; var message = String.Format( "{0:000} {1} \"{2}\"", (uint)exception.HResult % 999, exception.Source ?? responseInfo.Request.Url.Host, System.Web.HttpUtility.JavaScriptStringEncode(exception.Message)); responseInfo.Headers.Add(new Header(Header.Warning, message)); responseInfo.Status = exception.Status; using (var writer = new StreamWriter(responseInfo.Body, responseInfo.Encoding)) { writer.Write( "{{{0}\t\"title\":\"{2}\",{0}\t\"details\":\"{3}\",\"status\":{1}{0}}}", Environment.NewLine, (int)exception.Status, System.Web.HttpUtility.JavaScriptStringEncode(exception.Message), System.Web.HttpUtility.JavaScriptStringEncode(exception.InnerException != null ? exception.InnerException.StackTrace : exception.StackTrace)); } }
public void ProtocolExceptionConstructorTest2() { string errorMessage = "Unauthorized"; string errorCode = "401"; string source = "Intuit.Ipp.Test"; System.Exception innerException = new ArgumentNullException(); ProtocolException target = new ProtocolException(errorMessage, errorCode, source, innerException); ProtocolException newTarget = null; using (Stream s = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(s, target); s.Position = 0; // Reset stream position newTarget = (ProtocolException)formatter.Deserialize(s); } Assert.IsNotNull(newTarget); Assert.AreEqual(newTarget.Message, errorMessage); Assert.AreEqual(newTarget.ErrorCode, errorCode); Assert.AreEqual(newTarget.Source, source); Assert.ReferenceEquals(newTarget.InnerException, innerException); }
protected override async Task InitializeAsync() { FrameReader stream = Reader; var code = (ErrorCode)await stream.ReadIntAsync().ConfigureAwait(false); string msg = await stream.ReadStringAsync().ConfigureAwait(false); switch (code) { case ErrorCode.Unavailable: { var cl = (CqlConsistency)await stream.ReadShortAsync().ConfigureAwait(false); int required = await stream.ReadIntAsync().ConfigureAwait(false); int alive = await stream.ReadIntAsync().ConfigureAwait(false); Exception = new UnavailableException(msg, cl, required, alive); break; } case ErrorCode.WriteTimeout: { var cl = (CqlConsistency)await stream.ReadShortAsync().ConfigureAwait(false); int received = await stream.ReadIntAsync().ConfigureAwait(false); int blockFor = await stream.ReadIntAsync().ConfigureAwait(false); string writeType = await stream.ReadStringAsync().ConfigureAwait(false); Exception = new WriteTimeOutException(msg, cl, received, blockFor, writeType); break; } case ErrorCode.ReadTimeout: { var cl = (CqlConsistency)await stream.ReadShortAsync().ConfigureAwait(false); int received = await stream.ReadIntAsync().ConfigureAwait(false); int blockFor = await stream.ReadIntAsync().ConfigureAwait(false); bool dataPresent = 0 != await stream.ReadByteAsync().ConfigureAwait(false); Exception = new ReadTimeOutException(msg, cl, received, blockFor, dataPresent); break; } case ErrorCode.Syntax: Exception = new SyntaxException(msg); break; case ErrorCode.Unauthorized: Exception = new UnauthorizedException(msg); break; case ErrorCode.Invalid: Exception = new InvalidException(msg); break; case ErrorCode.AlreadyExists: string keyspace = await stream.ReadStringAsync().ConfigureAwait(false); string table = await stream.ReadStringAsync().ConfigureAwait(false); Exception = new AlreadyExistsException(msg, keyspace, table); break; case ErrorCode.Unprepared: byte[] unknownId = await stream.ReadShortBytesAsync().ConfigureAwait(false); Exception = new UnpreparedException(msg, unknownId); break; default: Exception = new ProtocolException(code, msg); break; } }
/// <summary> /// Prepares the return value for the GetRequest method in the event of an exception. /// </summary> /// <param name="ex">The exception that forms the basis of the error response. Must not be null.</param> /// <param name="request">The incoming HTTP request. Must not be null.</param> /// <param name="incomingMessage">The incoming message. May be null in the case that it was malformed.</param> /// <returns> /// Either the <see cref="IRequest"/> to return to the host site or null to indicate no response could be reasonably created and that the caller should rethrow the exception. /// </returns> private IRequest GetErrorResponse(ProtocolException ex, HttpRequestMessage request, IDirectedProtocolMessage incomingMessage) { Requires.NotNull(ex, "ex"); Requires.NotNull(request, "request"); Logger.OpenId.ErrorException("An exception was generated while processing an incoming OpenID request.", ex); IErrorMessage errorMessage; // We must create the appropriate error message type (direct vs. indirect) // based on what we see in the request. string returnTo = HttpUtility.ParseQueryString(request.RequestUri.Query)[Protocol.Default.openid.return_to]; if (returnTo != null) { // An indirect request message from the RP // We need to return an indirect response error message so the RP can consume it. // Consistent with OpenID 2.0 section 5.2.3. var indirectRequest = incomingMessage as SignedResponseRequest; if (indirectRequest != null) { errorMessage = new IndirectErrorResponse(indirectRequest); } else { errorMessage = new IndirectErrorResponse(Protocol.Default.Version, new Uri(returnTo)); } } else if (request.Method == HttpMethod.Post) { // A direct request message from the RP // We need to return a direct response error message so the RP can consume it. // Consistent with OpenID 2.0 section 5.1.2.2. errorMessage = new DirectErrorResponse(Protocol.Default.Version, incomingMessage); } else { // This may be an indirect request from an RP that was so badly // formed that we cannot even return an error to the RP. // The best we can do is display an error to the user. // Returning null cues the caller to "throw;" return(null); } errorMessage.ErrorMessage = ex.ToStringDescriptive(); // Allow host to log this error and issue a ticket #. // We tear off the field to a local var for thread safety. IErrorReporting hostErrorHandler = this.ErrorReporting; if (hostErrorHandler != null) { errorMessage.Contact = hostErrorHandler.Contact; errorMessage.Reference = hostErrorHandler.LogError(ex); } if (incomingMessage != null) { return(new AutoResponsiveRequest(incomingMessage, errorMessage, this.SecuritySettings)); } else { return(new AutoResponsiveRequest(errorMessage, this.SecuritySettings)); } }
public static void VerifyPtvsdVersionError(PtvsdVersionArguments args, ProtocolException ex) { ShowPtvsdVersionMessage(Strings.InstalledPtvsdOutdatedMessage.FormatUI("unknown", PtvsdVersion.Version)); }
public bool ProcessInfo(WsrmMessageInfo info, RequestContext context, bool throwException) { Exception e; if (info.ParsingException != null) { WsrmFault fault; if (this.SequenceID != null) { string reason = SR.GetString(SR.CouldNotParseWithAction, info.Action); fault = SequenceTerminatedFault.CreateProtocolFault(this.SequenceID, reason, null); } else { fault = null; } e = new ProtocolException(SR.GetString(SR.MessageExceptionOccurred), info.ParsingException); this.OnLocalFault(throwException ? null : e, fault, context); } else if (info.FaultReply != null) { e = info.FaultException; this.OnLocalFault(throwException ? null : e, info.FaultReply, context); } else if ((info.WsrmHeaderFault != null) && (info.WsrmHeaderFault.SequenceID != this.InputID) && (info.WsrmHeaderFault.SequenceID != this.OutputID)) { e = new ProtocolException(SR.GetString(SR.WrongIdentifierFault, FaultException.GetSafeReasonText(info.WsrmHeaderFault.Reason))); this.OnLocalFault(throwException ? null : e, (Message)null, context); } else if (info.FaultInfo != null) { if (this.isSessionClosed) { UnknownSequenceFault unknownSequenceFault = info.FaultInfo as UnknownSequenceFault; if (unknownSequenceFault != null) { UniqueId sequenceId = unknownSequenceFault.SequenceID; if (((this.OutputID != null) && (this.OutputID == sequenceId)) || ((this.InputID != null) && (this.InputID == sequenceId))) { if (this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { info.Message.Close(); return false; } else if (this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) { return true; } else { throw Fx.AssertAndThrow("Unknown version."); } } } } e = info.FaultException; if (context != null) context.Close(); this.OnRemoteFault(throwException ? null : e); } else { return true; } info.Message.Close(); if (throwException) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e); else return false; }
// makes sure that appropriate HTTP level headers are included in the received Message private Exception ProcessHttpAddressing(Message message) { Exception result = null; AddProperties(message); // check if user is receiving WS-1 messages if (message.Version.Addressing == AddressingVersion.None) { bool actionAbsent = false; try { actionAbsent = (message.Headers.Action == null); } catch (XmlException) { } catch (CommunicationException) { } if (!actionAbsent) { result = new ProtocolException(SR.Format(SR.HttpAddressingNoneHeaderOnWire, XD.AddressingDictionary.Action.Value)); } bool toAbsent = false; try { toAbsent = (message.Headers.To == null); } catch (XmlException) { } catch (CommunicationException) { } if (!toAbsent) { result = new ProtocolException(SR.Format(SR.HttpAddressingNoneHeaderOnWire, XD.AddressingDictionary.To.Value)); } message.Headers.To = message.Properties.Via; } if (_isRequest) { string action = null; if (message.Version.Envelope == EnvelopeVersion.Soap11) { action = SoapActionHeader; } else if (message.Version.Envelope == EnvelopeVersion.Soap12 && !String.IsNullOrEmpty(ContentType)) { MediaTypeHeaderValue parsedContentType = MediaTypeHeaderValue.Parse(ContentType); foreach (NameValueHeaderValue actionParam in parsedContentType.Parameters) { if (actionParam.Name == "action") { action = actionParam.Value; break; } } } if (action != null) { action = UrlUtility.UrlDecode(action, Encoding.UTF8); if (action.Length >= 2 && action[0] == '"' && action[action.Length - 1] == '"') { action = action.Substring(1, action.Length - 2); } if (message.Version.Addressing == AddressingVersion.None) { message.Headers.Action = action; } try { if (action.Length > 0 && string.Compare(message.Headers.Action, action, StringComparison.Ordinal) != 0) { result = new ActionMismatchAddressingException(SR.Format(SR.HttpSoapActionMismatchFault, message.Headers.Action, action), message.Headers.Action, action); } } catch (XmlException) { } catch (CommunicationException) { } } } return result; }
protected override bool OnTryCreateException(Message message, MessageFault fault, out Exception exception) { bool isSenderFault; bool isReceiverFault; FaultCode subCode; exception = null; if ((string.Compare(fault.Code.Namespace, this.version.Envelope.Namespace, StringComparison.Ordinal) == 0) && (string.Compare(fault.Code.Name, "MustUnderstand", StringComparison.Ordinal) == 0)) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } if (this.version.Envelope == EnvelopeVersion.Soap11) { isSenderFault = true; isReceiverFault = true; subCode = fault.Code; } else { isSenderFault = fault.Code.IsSenderFault; isReceiverFault = fault.Code.IsReceiverFault; subCode = fault.Code.SubCode; } if (subCode != null) { if (subCode.Namespace == null) { return false; } if (isSenderFault && (string.Compare(subCode.Namespace, this.version.Addressing.Namespace, StringComparison.Ordinal) == 0)) { if (string.Compare(subCode.Name, "ActionNotSupported", StringComparison.Ordinal) == 0) { exception = new ActionNotSupportedException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } if (string.Compare(subCode.Name, "DestinationUnreachable", StringComparison.Ordinal) == 0) { exception = new EndpointNotFoundException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } if (string.Compare(subCode.Name, "InvalidAddressingHeader", StringComparison.Ordinal) == 0) { if (((subCode.SubCode != null) && (string.Compare(subCode.SubCode.Namespace, this.version.Addressing.Namespace, StringComparison.Ordinal) == 0)) && (string.Compare(subCode.SubCode.Name, "InvalidCardinality", StringComparison.Ordinal) == 0)) { exception = new MessageHeaderException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text, true); return true; } } else if (this.version.Addressing == AddressingVersion.WSAddressing10) { if (string.Compare(subCode.Name, "MessageAddressingHeaderRequired", StringComparison.Ordinal) == 0) { exception = new MessageHeaderException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } if (string.Compare(subCode.Name, "InvalidAddressingHeader", StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } } else { if (string.Compare(subCode.Name, "MessageInformationHeaderRequired", StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } if (string.Compare(subCode.Name, "InvalidMessageInformationHeader", StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } } } if ((isReceiverFault && (string.Compare(subCode.Namespace, this.version.Addressing.Namespace, StringComparison.Ordinal) == 0)) && (string.Compare(subCode.Name, "EndpointUnavailable", StringComparison.Ordinal) == 0)) { exception = new ServerTooBusyException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } } return false; }
private void ProcessRequest(RequestContext context, WsrmMessageInfo info) { bool flag = true; bool flag2 = true; try { EndpointAddress address; bool flag3; if (!base.ReliableSession.ProcessInfo(info, context)) { flag = false; flag2 = false; return; } if (!base.ReliableSession.VerifySimplexProtocolElements(info, context)) { flag = false; flag2 = false; return; } base.ReliableSession.OnRemoteActivity(false); if (info.CreateSequenceInfo == null) { goto Label_0104; } if (WsrmUtilities.ValidateCreateSequence <IInputSessionChannel>(info, base.Listener, base.Binder.Channel, out address)) { Message response = WsrmUtilities.CreateCreateSequenceResponse(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion, false, info.CreateSequenceInfo, base.Listener.Ordered, base.ReliableSession.InputID, address); using (context) { using (response) { if (base.Binder.AddressResponse(info.Message, response)) { context.Reply(response, base.DefaultSendTimeout); } } goto Label_00FB; } } base.ReliableSession.OnLocalFault(info.FaultException, info.FaultReply, context); Label_00FB: flag = false; flag2 = false; return; Label_0104: flag3 = false; bool allAdded = false; bool flag5 = false; WsrmFault fault = null; Message message2 = null; Exception e = null; bool flag6 = base.Listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005; bool flag7 = base.Listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11; bool flag8 = info.AckRequestedInfo != null; if (info.SequencedMessageInfo != null) { lock (base.ThisLock) { if (base.Aborted || (base.State == CommunicationState.Faulted)) { return; } long sequenceNumber = info.SequencedMessageInfo.SequenceNumber; bool isLast = flag6 && info.SequencedMessageInfo.LastMessage; if (!base.Connection.IsValid(sequenceNumber, isLast)) { if (flag6) { fault = new LastMessageNumberExceededFault(base.ReliableSession.InputID); } else { message2 = new SequenceClosedFault(base.ReliableSession.InputID).CreateMessage(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion); if (PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MessageDropped(base.perfCounterId); } } } else if (base.Connection.Ranges.Contains(sequenceNumber)) { if (PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MessageDropped(base.perfCounterId); } } else if (flag6 && (info.Action == "http://schemas.xmlsoap.org/ws/2005/02/rm/LastMessage")) { base.Connection.Merge(sequenceNumber, isLast); allAdded = base.Connection.AllAdded; } else if (base.State == CommunicationState.Closing) { if (flag6) { fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedSessionClosedBeforeDone"), System.ServiceModel.SR.GetString("SessionClosedBeforeDone")); } else { message2 = new SequenceClosedFault(base.ReliableSession.InputID).CreateMessage(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion); if (PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MessageDropped(base.perfCounterId); } } } else if (base.DeliveryStrategy.CanEnqueue(sequenceNumber) && (base.Listener.Ordered || base.Connection.CanMerge(sequenceNumber))) { base.Connection.Merge(sequenceNumber, isLast); flag3 = base.DeliveryStrategy.Enqueue(info.Message, sequenceNumber); allAdded = base.Connection.AllAdded; flag2 = false; } else if (PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MessageDropped(base.perfCounterId); } goto Label_05CE; } } if (flag6 && (info.TerminateSequenceInfo != null)) { bool flag11; lock (base.ThisLock) { flag11 = !base.Connection.Terminate(); } if (!flag11) { return; } fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedEarlyTerminateSequence"), System.ServiceModel.SR.GetString("EarlyTerminateSequence")); } else if (flag7 && ((info.TerminateSequenceInfo != null) || (info.CloseSequenceInfo != null))) { bool flag13 = info.TerminateSequenceInfo != null; WsrmRequestInfo info2 = flag13 ? ((WsrmRequestInfo)info.TerminateSequenceInfo) : ((WsrmRequestInfo)info.CloseSequenceInfo); long last = flag13 ? info.TerminateSequenceInfo.LastMsgNumber : info.CloseSequenceInfo.LastMsgNumber; if (!WsrmUtilities.ValidateWsrmRequest(base.ReliableSession, info2, base.Binder, context)) { flag2 = false; flag = false; return; } bool isLastLargeEnough = true; bool flag15 = true; lock (base.ThisLock) { if (!base.Connection.IsLastKnown) { if (flag13) { if (base.Connection.SetTerminateSequenceLast(last, out isLastLargeEnough)) { allAdded = true; } else if (isLastLargeEnough) { e = new ProtocolException(System.ServiceModel.SR.GetString("EarlyTerminateSequence")); } } else { allAdded = base.Connection.SetCloseSequenceLast(last); isLastLargeEnough = allAdded; } if (allAdded) { base.ReliableSession.SetFinalAck(base.Connection.Ranges); base.DeliveryStrategy.Dispose(); } } else { flag15 = last == base.Connection.Last; if ((flag13 && flag15) && base.Connection.IsSequenceClosed) { flag5 = true; } } } if (!isLastLargeEnough) { fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedSmallLastMsgNumber"), System.ServiceModel.SR.GetString("SmallLastMsgNumberExceptionString")); } else if (!flag15) { fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedInconsistentLastMsgNumber"), System.ServiceModel.SR.GetString("InconsistentLastMsgNumberExceptionString")); } else { message2 = flag13 ? WsrmUtilities.CreateTerminateResponseMessage(base.Listener.MessageVersion, info2.MessageId, base.ReliableSession.InputID) : WsrmUtilities.CreateCloseSequenceResponse(base.Listener.MessageVersion, info2.MessageId, base.ReliableSession.InputID); flag8 = true; } } Label_05CE: if (fault != null) { base.ReliableSession.OnLocalFault(fault.CreateException(), fault, context); flag2 = false; flag = false; } else { if ((message2 != null) && flag8) { base.AddAcknowledgementHeader(message2); } else if (message2 == null) { message2 = base.CreateAcknowledgmentMessage(); } using (message2) { context.Reply(message2); } if (flag5) { lock (base.ThisLock) { base.Connection.Terminate(); } } if (e != null) { base.ReliableSession.OnRemoteFault(e); } else { if (flag3) { base.Dispatch(); } if (allAdded) { ActionItem.Schedule(new Action <object>(this.ShutdownCallback), null); } } } } finally { if (flag2) { info.Message.Close(); } if (flag) { context.Close(); } } }
public void CtorDefault() { ProtocolException ex = new ProtocolException(); }
public void CtorWithTextMessage() { ProtocolException ex = new ProtocolException("message"); Assert.AreEqual("message", ex.Message); }
void OnConnectionModeKnown(ListenerConnectionModeReader modeReader) { lock (ThisLock) { if (isDisposed) { return; } connectionReaders.Remove(modeReader); } try { FramingMode framingMode = modeReader.GetConnectionMode(); switch (framingMode) { case FramingMode.Duplex: OnDuplexConnection(modeReader); break; case FramingMode.Singleton: OnSingletonConnection(modeReader); break; default: { Exception inner = new InvalidDataException(SR.GetString( SR.FramingModeNotSupported, framingMode)); Exception exception = new ProtocolException(inner.Message, inner); FramingEncodingString.AddFaultString(exception, FramingEncodingString.UnsupportedModeFault); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception); } } } catch (ProtocolException exception) { DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); modeReader.Dispose(); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } DiagnosticUtility.TraceHandledException(exception, TraceEventType.Error); // containment -- abort the errant reader modeReader.Dispose(); } }
internal static ProtocolException CreateHttpProtocolException(string message, HttpStatusCode statusCode, string statusDescription) { ProtocolException exception = new ProtocolException(message); exception.Data.Add(HttpChannelUtilities.HttpStatusCodeExceptionKey, statusCode); if (statusDescription != null && statusDescription.Length > 0) { exception.Data.Add(HttpChannelUtilities.HttpStatusDescriptionExceptionKey, statusDescription); } return exception; }
public bool ProcessInfo(WsrmMessageInfo info, RequestContext context, bool throwException) { Exception faultException; if (info.ParsingException != null) { WsrmFault fault; if (this.SequenceID != null) { string faultReason = System.ServiceModel.SR.GetString("CouldNotParseWithAction", new object[] { info.Action }); fault = SequenceTerminatedFault.CreateProtocolFault(this.SequenceID, faultReason, null); } else { fault = null; } faultException = new ProtocolException(System.ServiceModel.SR.GetString("MessageExceptionOccurred"), info.ParsingException); this.OnLocalFault(throwException ? null : faultException, fault, context); } else if (info.FaultReply != null) { faultException = info.FaultException; this.OnLocalFault(throwException ? null : faultException, info.FaultReply, context); } else if (((info.WsrmHeaderFault != null) && (info.WsrmHeaderFault.SequenceID != this.InputID)) && (info.WsrmHeaderFault.SequenceID != this.OutputID)) { faultException = new ProtocolException(System.ServiceModel.SR.GetString("WrongIdentifierFault", new object[] { FaultException.GetSafeReasonText(info.WsrmHeaderFault.Reason) })); this.OnLocalFault(throwException ? null : faultException, (Message)null, context); } else { if (info.FaultInfo == null) { return(true); } if (this.isSessionClosed) { UnknownSequenceFault faultInfo = info.FaultInfo as UnknownSequenceFault; if (faultInfo != null) { UniqueId sequenceID = faultInfo.SequenceID; if (((this.OutputID != null) && (this.OutputID == sequenceID)) || ((this.InputID != null) && (this.InputID == sequenceID))) { if (this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { info.Message.Close(); return(false); } if (this.settings.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11) { throw Fx.AssertAndThrow("Unknown version."); } return(true); } } } faultException = info.FaultException; if (context != null) { context.Close(); } this.OnRemoteFault(throwException ? null : faultException); } info.Message.Close(); if (throwException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(faultException); } return(false); }
void OnConnectionModeKnownCore(ConnectionModeReader modeReader, bool isCached) { lock (ThisLock) { if (isDisposed) { return; } this.connectionReaders.Remove(modeReader); } bool closeReader = true; try { FramingMode framingMode; try { framingMode = modeReader.GetConnectionMode(); } catch (CommunicationException exception) { TraceEventType eventType = modeReader.Connection.ExceptionEventType; DiagnosticUtility.TraceHandledException(exception, eventType); return; } catch (TimeoutException exception) { if (!isCached) { exception = new TimeoutException(SR.GetString(SR.ChannelInitializationTimeout, this.channelInitializationTimeout), exception); System.ServiceModel.Dispatcher.ErrorBehavior.ThrowAndCatch(exception); } if (TD.ChannelInitializationTimeoutIsEnabled()) { TD.ChannelInitializationTimeout(SR.GetString(SR.ChannelInitializationTimeout, this.channelInitializationTimeout)); } TraceEventType eventType = modeReader.Connection.ExceptionEventType; DiagnosticUtility.TraceHandledException(exception, eventType); return; } switch (framingMode) { case FramingMode.Duplex: OnDuplexConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; case FramingMode.Singleton: OnSingletonConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; default: { Exception inner = new InvalidDataException(SR.GetString( SR.FramingModeNotSupported, framingMode)); Exception exception = new ProtocolException(inner.Message, inner); FramingEncodingString.AddFaultString(exception, FramingEncodingString.UnsupportedModeFault); System.ServiceModel.Dispatcher.ErrorBehavior.ThrowAndCatch(exception); return; } } closeReader = false; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!ExceptionHandler.HandleTransportExceptionHelper(e)) { throw; } // containment -- the reader is aborted, no need for additional containment } finally { if (closeReader) { modeReader.Dispose(); } } }
private void ProcessRequest(RequestContext context, WsrmMessageInfo info) { bool flag = true; bool flag2 = true; try { EndpointAddress address; bool flag3; if (!base.ReliableSession.ProcessInfo(info, context)) { flag = false; flag2 = false; return; } if (!base.ReliableSession.VerifySimplexProtocolElements(info, context)) { flag = false; flag2 = false; return; } base.ReliableSession.OnRemoteActivity(false); if (info.CreateSequenceInfo == null) { goto Label_0104; } if (WsrmUtilities.ValidateCreateSequence<IInputSessionChannel>(info, base.Listener, base.Binder.Channel, out address)) { Message response = WsrmUtilities.CreateCreateSequenceResponse(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion, false, info.CreateSequenceInfo, base.Listener.Ordered, base.ReliableSession.InputID, address); using (context) { using (response) { if (base.Binder.AddressResponse(info.Message, response)) { context.Reply(response, base.DefaultSendTimeout); } } goto Label_00FB; } } base.ReliableSession.OnLocalFault(info.FaultException, info.FaultReply, context); Label_00FB: flag = false; flag2 = false; return; Label_0104: flag3 = false; bool allAdded = false; bool flag5 = false; WsrmFault fault = null; Message message2 = null; Exception e = null; bool flag6 = base.Listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005; bool flag7 = base.Listener.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11; bool flag8 = info.AckRequestedInfo != null; if (info.SequencedMessageInfo != null) { lock (base.ThisLock) { if (base.Aborted || (base.State == CommunicationState.Faulted)) { return; } long sequenceNumber = info.SequencedMessageInfo.SequenceNumber; bool isLast = flag6 && info.SequencedMessageInfo.LastMessage; if (!base.Connection.IsValid(sequenceNumber, isLast)) { if (flag6) { fault = new LastMessageNumberExceededFault(base.ReliableSession.InputID); } else { message2 = new SequenceClosedFault(base.ReliableSession.InputID).CreateMessage(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion); if (PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MessageDropped(base.perfCounterId); } } } else if (base.Connection.Ranges.Contains(sequenceNumber)) { if (PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MessageDropped(base.perfCounterId); } } else if (flag6 && (info.Action == "http://schemas.xmlsoap.org/ws/2005/02/rm/LastMessage")) { base.Connection.Merge(sequenceNumber, isLast); allAdded = base.Connection.AllAdded; } else if (base.State == CommunicationState.Closing) { if (flag6) { fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedSessionClosedBeforeDone"), System.ServiceModel.SR.GetString("SessionClosedBeforeDone")); } else { message2 = new SequenceClosedFault(base.ReliableSession.InputID).CreateMessage(base.Listener.MessageVersion, base.Listener.ReliableMessagingVersion); if (PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MessageDropped(base.perfCounterId); } } } else if (base.DeliveryStrategy.CanEnqueue(sequenceNumber) && (base.Listener.Ordered || base.Connection.CanMerge(sequenceNumber))) { base.Connection.Merge(sequenceNumber, isLast); flag3 = base.DeliveryStrategy.Enqueue(info.Message, sequenceNumber); allAdded = base.Connection.AllAdded; flag2 = false; } else if (PerformanceCounters.PerformanceCountersEnabled) { PerformanceCounters.MessageDropped(base.perfCounterId); } goto Label_05CE; } } if (flag6 && (info.TerminateSequenceInfo != null)) { bool flag11; lock (base.ThisLock) { flag11 = !base.Connection.Terminate(); } if (!flag11) { return; } fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedEarlyTerminateSequence"), System.ServiceModel.SR.GetString("EarlyTerminateSequence")); } else if (flag7 && ((info.TerminateSequenceInfo != null) || (info.CloseSequenceInfo != null))) { bool flag13 = info.TerminateSequenceInfo != null; WsrmRequestInfo info2 = flag13 ? ((WsrmRequestInfo) info.TerminateSequenceInfo) : ((WsrmRequestInfo) info.CloseSequenceInfo); long last = flag13 ? info.TerminateSequenceInfo.LastMsgNumber : info.CloseSequenceInfo.LastMsgNumber; if (!WsrmUtilities.ValidateWsrmRequest(base.ReliableSession, info2, base.Binder, context)) { flag2 = false; flag = false; return; } bool isLastLargeEnough = true; bool flag15 = true; lock (base.ThisLock) { if (!base.Connection.IsLastKnown) { if (flag13) { if (base.Connection.SetTerminateSequenceLast(last, out isLastLargeEnough)) { allAdded = true; } else if (isLastLargeEnough) { e = new ProtocolException(System.ServiceModel.SR.GetString("EarlyTerminateSequence")); } } else { allAdded = base.Connection.SetCloseSequenceLast(last); isLastLargeEnough = allAdded; } if (allAdded) { base.ReliableSession.SetFinalAck(base.Connection.Ranges); base.DeliveryStrategy.Dispose(); } } else { flag15 = last == base.Connection.Last; if ((flag13 && flag15) && base.Connection.IsSequenceClosed) { flag5 = true; } } } if (!isLastLargeEnough) { fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedSmallLastMsgNumber"), System.ServiceModel.SR.GetString("SmallLastMsgNumberExceptionString")); } else if (!flag15) { fault = SequenceTerminatedFault.CreateProtocolFault(base.ReliableSession.InputID, System.ServiceModel.SR.GetString("SequenceTerminatedInconsistentLastMsgNumber"), System.ServiceModel.SR.GetString("InconsistentLastMsgNumberExceptionString")); } else { message2 = flag13 ? WsrmUtilities.CreateTerminateResponseMessage(base.Listener.MessageVersion, info2.MessageId, base.ReliableSession.InputID) : WsrmUtilities.CreateCloseSequenceResponse(base.Listener.MessageVersion, info2.MessageId, base.ReliableSession.InputID); flag8 = true; } } Label_05CE: if (fault != null) { base.ReliableSession.OnLocalFault(fault.CreateException(), fault, context); flag2 = false; flag = false; } else { if ((message2 != null) && flag8) { base.AddAcknowledgementHeader(message2); } else if (message2 == null) { message2 = base.CreateAcknowledgmentMessage(); } using (message2) { context.Reply(message2); } if (flag5) { lock (base.ThisLock) { base.Connection.Terminate(); } } if (e != null) { base.ReliableSession.OnRemoteFault(e); } else { if (flag3) { base.Dispatch(); } if (allAdded) { ActionItem.Schedule(new Action<object>(this.ShutdownCallback), null); } } } } finally { if (flag2) { info.Message.Close(); } if (flag) { context.Close(); } } }
protected override bool OnTryCreateException(Message message, MessageFault fault, out Exception exception) { exception = null; // SOAP MustUnderstand if (string.Compare(fault.Code.Namespace, _version.Envelope.Namespace, StringComparison.Ordinal) == 0 && string.Compare(fault.Code.Name, MessageStrings.MustUnderstandFault, StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } bool checkSender; bool checkReceiver; FaultCode code; if (_version.Envelope == EnvelopeVersion.Soap11) { checkSender = true; checkReceiver = true; code = fault.Code; } else { checkSender = fault.Code.IsSenderFault; checkReceiver = fault.Code.IsReceiverFault; code = fault.Code.SubCode; } if (code == null) { return false; } if (code.Namespace == null) { return false; } if (checkSender) { // WS-Addressing if (string.Compare(code.Namespace, _version.Addressing.Namespace, StringComparison.Ordinal) == 0) { if (string.Compare(code.Name, AddressingStrings.ActionNotSupported, StringComparison.Ordinal) == 0) { exception = new ActionNotSupportedException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } else if (string.Compare(code.Name, AddressingStrings.DestinationUnreachable, StringComparison.Ordinal) == 0) { exception = new EndpointNotFoundException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } else if (string.Compare(code.Name, Addressing10Strings.InvalidAddressingHeader, StringComparison.Ordinal) == 0) { if (code.SubCode != null && string.Compare(code.SubCode.Namespace, _version.Addressing.Namespace, StringComparison.Ordinal) == 0 && string.Compare(code.SubCode.Name, Addressing10Strings.InvalidCardinality, StringComparison.Ordinal) == 0) { exception = new MessageHeaderException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text, true); return true; } } else if (_version.Addressing == AddressingVersion.WSAddressing10) { if (string.Compare(code.Name, Addressing10Strings.MessageAddressingHeaderRequired, StringComparison.Ordinal) == 0) { exception = new MessageHeaderException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } else if (string.Compare(code.Name, Addressing10Strings.InvalidAddressingHeader, StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } } else { if (string.Compare(code.Name, Addressing200408Strings.MessageInformationHeaderRequired, StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } else if (string.Compare(code.Name, Addressing200408Strings.InvalidMessageInformationHeader, StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } } } } if (checkReceiver) { // WS-Addressing if (string.Compare(code.Namespace, _version.Addressing.Namespace, StringComparison.Ordinal) == 0) { if (string.Compare(code.Name, AddressingStrings.EndpointUnavailable, StringComparison.Ordinal) == 0) { exception = new ServerTooBusyException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return true; } } } return false; }
private Exception ProcessHttpAddressing(Message message) { Exception result = null; AddProperties(message); // check if user is receiving WS-1 messages if (message.Version.Addressing == AddressingVersion.None) { bool actionAbsent = false; try { actionAbsent = (message.Headers.Action == null); // message.Headers.Action uses an XmlDictionaryReader. If the xml is malformed, // an XmlException might be thrown when trying to parse the response data. // CommunicationException is the base type for any ServiceModel exceptions. If anything went // wrong in any ServiceModel code, an exception deriving from CommunicationException will be // thrown. // In these cases, be tolerant of the failure and treat it as though the action is absent. } catch (XmlException) { } catch (CommunicationException) { } if (!actionAbsent) { result = new ProtocolException(SR.Format(SR.HttpAddressingNoneHeaderOnWire, XD.AddressingDictionary.Action.Value)); } bool toAbsent = false; try { toAbsent = (message.Headers.To == null); // message.Headers.To has the same failure modes as for the Action header. } catch (XmlException) { } catch (CommunicationException) { } if (!toAbsent) { result = new ProtocolException(SR.Format(SR.HttpAddressingNoneHeaderOnWire, XD.AddressingDictionary.To.Value)); } message.Headers.To = message.Properties.Via; } return result; }
public void it_should_leave_ProtocolException_as_is() { var exception = new ProtocolException(HttpStatusCode.Conflict); exception.AsHttpException().Should().Be(exception); }
private void OnConnectionModeKnownCore(ConnectionModeReader modeReader, bool isCached) { lock (this.ThisLock) { if (this.isDisposed) { return; } this.connectionReaders.Remove(modeReader); } bool flag = true; try { FramingMode connectionMode; try { connectionMode = modeReader.GetConnectionMode(); } catch (CommunicationException exception) { TraceEventType exceptionEventType = modeReader.Connection.ExceptionEventType; if (DiagnosticUtility.ShouldTrace(exceptionEventType)) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, exceptionEventType); } return; } catch (TimeoutException exception2) { if (!isCached) { exception2 = new TimeoutException(System.ServiceModel.SR.GetString("ChannelInitializationTimeout", new object[] { this.channelInitializationTimeout }), exception2); ErrorBehavior.ThrowAndCatch(exception2); } TraceEventType type = modeReader.Connection.ExceptionEventType; if (DiagnosticUtility.ShouldTrace(type)) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, type); } return; } switch (connectionMode) { case FramingMode.Singleton: this.OnSingletonConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; case FramingMode.Duplex: this.OnDuplexConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; default: { Exception innerException = new InvalidDataException(System.ServiceModel.SR.GetString("FramingModeNotSupported", new object[] { connectionMode })); Exception exception4 = new ProtocolException(innerException.Message, innerException); FramingEncodingString.AddFaultString(exception4, "http://schemas.microsoft.com/ws/2006/05/framing/faults/UnsupportedMode"); ErrorBehavior.ThrowAndCatch(exception4); return; } } flag = false; } catch (Exception exception5) { if (Fx.IsFatal(exception5)) { throw; } if (!System.ServiceModel.Dispatcher.ExceptionHandler.HandleTransportExceptionHelper(exception5)) { throw; } } finally { if (flag) { modeReader.Dispose(); } } }
/// <summary> /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class. /// </summary> /// <param name="request">The request.</param> /// <param name="exception">The exception.</param> internal UnauthorizedResponse(IDirectedProtocolMessage request, ProtocolException exception) : this(request) { Contract.Requires<ArgumentNullException>(exception != null); this.ErrorMessage = exception.Message; }
/// <summary> /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class /// to inform the client that the bearer token included in the request was rejected. /// </summary> /// <param name="request">The request.</param> /// <param name="exception">The exception.</param> /// <returns>The error message.</returns> internal static UnauthorizedResponse InvalidToken(IDirectedProtocolMessage request, ProtocolException exception) { Requires.NotNull(request, "request"); Requires.NotNull(exception, "exception"); var message = new UnauthorizedResponse(request) { ErrorCode = Protocol.BearerTokenErrorCodes.InvalidToken, ErrorDescription = exception.Message, HttpStatusCode = System.Net.HttpStatusCode.Unauthorized, }; return(message); }
/// <summary> /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class /// to inform the client that the request was invalid. /// </summary> /// <param name="exception">The exception.</param> /// <param name="version">The version of OAuth 2 that is in use.</param> /// <returns>The error message.</returns> internal static UnauthorizedResponse InvalidRequest(ProtocolException exception, Version version = null) { Requires.NotNull(exception, "exception"); var message = new UnauthorizedResponse(version) { ErrorCode = Protocol.BearerTokenErrorCodes.InvalidRequest, ErrorDescription = exception.Message, HttpStatusCode = System.Net.HttpStatusCode.BadRequest, }; return message; }
/// <summary> /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class /// to inform the client that the bearer token included in the request was rejected. /// </summary> /// <param name="request">The request.</param> /// <param name="exception">The exception.</param> /// <returns>The error message.</returns> internal static UnauthorizedResponse InvalidToken(IDirectedProtocolMessage request, ProtocolException exception) { Requires.NotNull(request, "request"); Requires.NotNull(exception, "exception"); var message = new UnauthorizedResponse(request) { ErrorCode = Protocol.BearerTokenErrorCodes.InvalidToken, ErrorDescription = exception.Message, HttpStatusCode = System.Net.HttpStatusCode.Unauthorized, }; return message; }
/// <summary> /// Prepares the return value for the GetRequest method in the event of an exception. /// </summary> /// <param name="ex">The exception that forms the basis of the error response. Must not be null.</param> /// <param name="httpRequestInfo">The incoming HTTP request. Must not be null.</param> /// <param name="incomingMessage">The incoming message. May be null in the case that it was malformed.</param> /// <returns> /// Either the <see cref="IRequest"/> to return to the host site or null to indicate no response could be reasonably created and that the caller should rethrow the exception. /// </returns> private IRequest GetErrorResponse(ProtocolException ex, HttpRequestInfo httpRequestInfo, IDirectedProtocolMessage incomingMessage) { Contract.Requires<ArgumentNullException>(ex != null); Contract.Requires<ArgumentNullException>(httpRequestInfo != null); Logger.OpenId.Error("An exception was generated while processing an incoming OpenID request.", ex); IErrorMessage errorMessage; // We must create the appropriate error message type (direct vs. indirect) // based on what we see in the request. string returnTo = httpRequestInfo.QueryString[Protocol.Default.openid.return_to]; if (returnTo != null) { // An indirect request message from the RP // We need to return an indirect response error message so the RP can consume it. // Consistent with OpenID 2.0 section 5.2.3. var indirectRequest = incomingMessage as SignedResponseRequest; if (indirectRequest != null) { errorMessage = new IndirectErrorResponse(indirectRequest); } else { errorMessage = new IndirectErrorResponse(Protocol.Default.Version, new Uri(returnTo)); } } else if (httpRequestInfo.HttpMethod == "POST") { // A direct request message from the RP // We need to return a direct response error message so the RP can consume it. // Consistent with OpenID 2.0 section 5.1.2.2. errorMessage = new DirectErrorResponse(Protocol.Default.Version, incomingMessage); } else { // This may be an indirect request from an RP that was so badly // formed that we cannot even return an error to the RP. // The best we can do is display an error to the user. // Returning null cues the caller to "throw;" return null; } errorMessage.ErrorMessage = ex.ToStringDescriptive(); // Allow host to log this error and issue a ticket #. // We tear off the field to a local var for thread safety. IErrorReporting hostErrorHandler = this.ErrorReporting; if (hostErrorHandler != null) { errorMessage.Contact = hostErrorHandler.Contact; errorMessage.Reference = hostErrorHandler.LogError(ex); } if (incomingMessage != null) { return new AutoResponsiveRequest(incomingMessage, errorMessage, this.SecuritySettings); } else { return new AutoResponsiveRequest(errorMessage, this.SecuritySettings); } }
protected void Decode(byte[] data) { var receivedTime = DateTime.UtcNow; using (var inputStream = new MemoryStream(data)) { // create avro binary decoder to read from memory stream var decoder = new BinaryDecoder(inputStream); var record = Activator.CreateInstance <MessageHeader>(); var reader = new SpecificReader <MessageHeader>(new EtpSpecificReader(record.Schema, record.Schema)); MessageHeader header = reader.Read(record, decoder); // string message = Encoding.UTF8.GetString(inputStream.ToArray()); if (header.Protocol == 0 && header.MessageType == 2) { lock (m_ConnectionLock) { m_HasConnected = true; } var recordSession = Activator.CreateInstance <OpenSession>(); var readerSession = new SpecificReader <OpenSession>(new EtpSpecificReader(recordSession.Schema, recordSession.Schema)); readerSession.Read(recordSession, decoder); string message = ToString(recordSession); var timediff = receivedTime - m_Time; Message?.Invoke(message, timediff.TotalMilliseconds, TraceLevel.Info); } else if (header.Protocol == 3 && header.MessageType == 2) { var responce = Activator.CreateInstance <GetResourcesResponse>(); var bodyreader = new SpecificReader <GetResourcesResponse>(new EtpSpecificReader(responce.Schema, responce.Schema)); GetResourcesResponse bodyheader = bodyreader.Read(responce, decoder); RequestInformation parent; lock (m_RequestInformation) { parent = m_RequestInformation[header.CorrelationId]; } var timediff = receivedTime - parent.RequestTime; string message = ToString(responce); Message?.Invoke(message, timediff.TotalMilliseconds, TraceLevel.Info); if (parent.ChannelItem == null) { ChannelItem channelItem = new ChannelItem() { Name = responce.Resource.Name, Uid = responce.Resource.Uuid, Eml = responce.Resource.Uri, Level = 0, ChildrensCount = responce.Resource.HasChildren }; ChannelItemsReceived?.Invoke(channelItem); } else { ChannelItem channelItem = new ChannelItem() { Name = responce.Resource.Name, Uid = responce.Resource.Uuid, Eml = responce.Resource.Uri, Level = parent.ChannelItem.Level + 1, ChildrensCount = responce.Resource.HasChildren }; ChannelChildrensReceived?.Invoke(channelItem, parent.ChannelItem); } } else if (header.Protocol == 1 && header.MessageType == 2) { var timediff = receivedTime - m_Time; string message = "Channels received: ["; var recordMetadata = Activator.CreateInstance <ChannelMetadata>(); var readerMetadata = new SpecificReader <ChannelMetadata>(new EtpSpecificReader(recordMetadata.Schema, recordMetadata.Schema)); readerMetadata.Read(recordMetadata, decoder); ChannelMetadata metadata = new ChannelMetadata(); metadata.Channels = new List <ChannelMetadataRecord>(); lock (m_ChannelStreamingInfo) { foreach (var channel in recordMetadata.Channels) { if (m_LogCurveEml.Contains(channel.ChannelUri, StringComparer.InvariantCultureIgnoreCase)) { metadata.Channels.Add(channel); ChannelStreamingInfo channelStreamingInfo = new ChannelStreamingInfo() { ChannelId = channel.ChannelId, StartIndex = new StreamingStartIndex() { Item = null }, ReceiveChangeNotification = true }; m_ChannelStreamingInfo.Add(channelStreamingInfo); message = message + $"\n{channel.ChannelId} {channel.ChannelName}"; ChannelMetaDataVM channelMetaData_VM = ETPMapper.Instance().Map <ChannelMetaDataVM>(channel); string json = JsonConvert.SerializeObject(channelMetaData_VM, Formatting.Indented); Message?.Invoke(json, timediff.TotalMilliseconds, TraceLevel.Info); } } ChannelInfoReceived?.Invoke(metadata); } message = message + "\n]"; Message?.Invoke(message, timediff.TotalMilliseconds, TraceLevel.Info); HasDescribing = false; } else if (header.Protocol == 1 && header.MessageType == 3) { var recordData = Activator.CreateInstance <ChannelData>(); var readerdata = new SpecificReader <ChannelData>(new EtpSpecificReader(recordData.Schema, recordData.Schema)); readerdata.Read(recordData, decoder); ChannelDataReceived?.Invoke(recordData.Data); } else if (header.MessageType == 1000) { var timediff = receivedTime - m_Time; var bodyrecord = Activator.CreateInstance <ProtocolException>(); var bodyreader = new SpecificReader <ProtocolException>(new EtpSpecificReader(bodyrecord.Schema, bodyrecord.Schema)); ProtocolException bodyheader = bodyreader.Read(bodyrecord, decoder); string message = $"Error Received ({bodyrecord.ErrorCode}): {bodyrecord.ErrorMessage}"; Message?.Invoke(message, timediff.TotalMilliseconds, TraceLevel.Error); HasDescribing = false; } else { HasDescribing = false; } } }
private Exception ProcessHttpAddressing(Message message) { Exception exception = null; this.AddProperties(message); if (message.Version.Addressing == AddressingVersion.None) { bool flag = false; try { flag = message.Headers.Action == null; } catch (XmlException exception2) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information); } } catch (CommunicationException exception3) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Information); } } if (!flag) { exception = new ProtocolException(System.ServiceModel.SR.GetString("HttpAddressingNoneHeaderOnWire", new object[] { XD.AddressingDictionary.Action.Value })); } bool flag2 = false; try { flag2 = message.Headers.To == null; } catch (XmlException exception4) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception4, TraceEventType.Information); } } catch (CommunicationException exception5) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception5, TraceEventType.Information); } } if (!flag2) { exception = new ProtocolException(System.ServiceModel.SR.GetString("HttpAddressingNoneHeaderOnWire", new object[] { XD.AddressingDictionary.To.Value })); } message.Headers.To = message.Properties.Via; } if (this.isRequest) { string soapActionHeader = null; if (message.Version.Envelope == EnvelopeVersion.Soap11) { soapActionHeader = this.SoapActionHeader; } else if ((message.Version.Envelope == EnvelopeVersion.Soap12) && !string.IsNullOrEmpty(this.ContentType)) { System.Net.Mime.ContentType type = new System.Net.Mime.ContentType(this.ContentType); if ((type.MediaType == "multipart/related") && type.Parameters.ContainsKey("start-info")) { soapActionHeader = new System.Net.Mime.ContentType(type.Parameters["start-info"]).Parameters["action"]; } if (soapActionHeader == null) { soapActionHeader = type.Parameters["action"]; } } if (soapActionHeader != null) { soapActionHeader = UrlUtility.UrlDecode(soapActionHeader, Encoding.UTF8); if (((soapActionHeader.Length >= 2) && (soapActionHeader[0] == '"')) && (soapActionHeader[soapActionHeader.Length - 1] == '"')) { soapActionHeader = soapActionHeader.Substring(1, soapActionHeader.Length - 2); } if (message.Version.Addressing == AddressingVersion.None) { message.Headers.Action = soapActionHeader; } try { if ((soapActionHeader.Length > 0) && (string.Compare(message.Headers.Action, soapActionHeader, StringComparison.Ordinal) != 0)) { exception = new ActionMismatchAddressingException(System.ServiceModel.SR.GetString("HttpSoapActionMismatchFault", new object[] { message.Headers.Action, soapActionHeader }), message.Headers.Action, soapActionHeader); } } catch (XmlException exception6) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception6, TraceEventType.Information); } } catch (CommunicationException exception7) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception7, TraceEventType.Information); } } } } this.ApplyChannelBinding(message); if (DiagnosticUtility.ShouldUseActivity) { TraceUtility.TransferFromTransport(message); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, 0x40013, System.ServiceModel.SR.GetString("TraceCodeMessageReceived"), MessageTransmitTraceRecord.CreateReceiveTraceRecord(message), this, null, message); } if (MessageLogger.LoggingEnabled && (message.Version.Addressing == AddressingVersion.None)) { MessageLogger.LogMessage(ref message, MessageLoggingSource.LastChance | MessageLoggingSource.TransportReceive); } return(exception); }
protected override bool OnTryCreateException(Message message, MessageFault fault, out Exception exception) { exception = null; // SOAP MustUnderstand if (string.Compare(fault.Code.Namespace, version.Envelope.Namespace, StringComparison.Ordinal) == 0 && string.Compare(fault.Code.Name, MessageStrings.MustUnderstandFault, StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return(true); } bool checkSender; bool checkReceiver; FaultCode code; if (version.Envelope == EnvelopeVersion.Soap11) { checkSender = true; checkReceiver = true; code = fault.Code; } else { checkSender = fault.Code.IsSenderFault; checkReceiver = fault.Code.IsReceiverFault; code = fault.Code.SubCode; } if (code == null) { return(false); } if (code.Namespace == null) { return(false); } if (checkSender) { // WS-Addressing if (string.Compare(code.Namespace, version.Addressing.Namespace, StringComparison.Ordinal) == 0) { if (string.Compare(code.Name, AddressingStrings.ActionNotSupported, StringComparison.Ordinal) == 0) { exception = new ActionNotSupportedException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return(true); } else if (string.Compare(code.Name, AddressingStrings.DestinationUnreachable, StringComparison.Ordinal) == 0) { exception = new EndpointNotFoundException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return(true); } else if (string.Compare(code.Name, Addressing10Strings.InvalidAddressingHeader, StringComparison.Ordinal) == 0) { if (code.SubCode != null && string.Compare(code.SubCode.Namespace, version.Addressing.Namespace, StringComparison.Ordinal) == 0 && string.Compare(code.SubCode.Name, Addressing10Strings.InvalidCardinality, StringComparison.Ordinal) == 0) { exception = new MessageHeaderException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text, true); return(true); } } else if (version.Addressing == AddressingVersion.WSAddressing10) { if (string.Compare(code.Name, Addressing10Strings.MessageAddressingHeaderRequired, StringComparison.Ordinal) == 0) { exception = new MessageHeaderException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return(true); } else if (string.Compare(code.Name, Addressing10Strings.InvalidAddressingHeader, StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return(true); } } else { if (string.Compare(code.Name, Addressing200408Strings.MessageInformationHeaderRequired, StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return(true); } else if (string.Compare(code.Name, Addressing200408Strings.InvalidMessageInformationHeader, StringComparison.Ordinal) == 0) { exception = new ProtocolException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return(true); } } } } if (checkReceiver) { // WS-Addressing if (string.Compare(code.Namespace, version.Addressing.Namespace, StringComparison.Ordinal) == 0) { if (string.Compare(code.Name, AddressingStrings.EndpointUnavailable, StringComparison.Ordinal) == 0) { exception = new ServerTooBusyException(fault.Reason.GetMatchingTranslation(CultureInfo.CurrentCulture).Text); return(true); } } } return(false); }
internal static void VerifyProtocol(bool condition, string message, params object[] args) { Contract.Requires(args != null); Contract.Ensures(condition); Contract.EnsuresOnThrow<ProtocolException>(!condition); Contract.Assume(message != null); if (!condition) { var exception = new ProtocolException(string.Format(CultureInfo.CurrentCulture, message, args)); if (Logger.Messaging.IsErrorEnabled) { Logger.Messaging.Error( string.Format( CultureInfo.CurrentCulture, "Protocol error: {0}{1}{2}", exception.Message, Environment.NewLine, new StackTrace())); } throw exception; } }
private Exception ProcessHttpAddressing(Message message) { Exception exception = null; this.AddProperties(message); if (message.Version.Addressing == AddressingVersion.None) { bool flag = false; try { flag = message.Headers.Action == null; } catch (XmlException exception2) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception2, TraceEventType.Information); } } catch (CommunicationException exception3) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception3, TraceEventType.Information); } } if (!flag) { exception = new ProtocolException(System.ServiceModel.SR.GetString("HttpAddressingNoneHeaderOnWire", new object[] { XD.AddressingDictionary.Action.Value })); } bool flag2 = false; try { flag2 = message.Headers.To == null; } catch (XmlException exception4) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception4, TraceEventType.Information); } } catch (CommunicationException exception5) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception5, TraceEventType.Information); } } if (!flag2) { exception = new ProtocolException(System.ServiceModel.SR.GetString("HttpAddressingNoneHeaderOnWire", new object[] { XD.AddressingDictionary.To.Value })); } message.Headers.To = message.Properties.Via; } if (this.isRequest) { string soapActionHeader = null; if (message.Version.Envelope == EnvelopeVersion.Soap11) { soapActionHeader = this.SoapActionHeader; } else if ((message.Version.Envelope == EnvelopeVersion.Soap12) && !string.IsNullOrEmpty(this.ContentType)) { System.Net.Mime.ContentType type = new System.Net.Mime.ContentType(this.ContentType); if ((type.MediaType == "multipart/related") && type.Parameters.ContainsKey("start-info")) { soapActionHeader = new System.Net.Mime.ContentType(type.Parameters["start-info"]).Parameters["action"]; } if (soapActionHeader == null) { soapActionHeader = type.Parameters["action"]; } } if (soapActionHeader != null) { soapActionHeader = UrlUtility.UrlDecode(soapActionHeader, Encoding.UTF8); if (((soapActionHeader.Length >= 2) && (soapActionHeader[0] == '"')) && (soapActionHeader[soapActionHeader.Length - 1] == '"')) { soapActionHeader = soapActionHeader.Substring(1, soapActionHeader.Length - 2); } if (message.Version.Addressing == AddressingVersion.None) { message.Headers.Action = soapActionHeader; } try { if ((soapActionHeader.Length > 0) && (string.Compare(message.Headers.Action, soapActionHeader, StringComparison.Ordinal) != 0)) { exception = new ActionMismatchAddressingException(System.ServiceModel.SR.GetString("HttpSoapActionMismatchFault", new object[] { message.Headers.Action, soapActionHeader }), message.Headers.Action, soapActionHeader); } } catch (XmlException exception6) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception6, TraceEventType.Information); } } catch (CommunicationException exception7) { if (DiagnosticUtility.ShouldTraceInformation) { DiagnosticUtility.ExceptionUtility.TraceHandledException(exception7, TraceEventType.Information); } } } } this.ApplyChannelBinding(message); if (DiagnosticUtility.ShouldUseActivity) { TraceUtility.TransferFromTransport(message); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, 0x40013, System.ServiceModel.SR.GetString("TraceCodeMessageReceived"), MessageTransmitTraceRecord.CreateReceiveTraceRecord(message), this, null, message); } if (MessageLogger.LoggingEnabled && (message.Version.Addressing == AddressingVersion.None)) { MessageLogger.LogMessage(ref message, MessageLoggingSource.LastChance | MessageLoggingSource.TransportReceive); } return exception; }
private void ThrowHttpProtocolException(string message, HttpStatusCode statusCode, string statusDescription) { ProtocolException exception = new ProtocolException(message, this.webException); exception.Data.Add("System.ServiceModel.Channels.HttpInput.HttpStatusCode", statusCode); if ((statusDescription != null) && (statusDescription.Length > 0)) { exception.Data.Add("System.ServiceModel.Channels.HttpInput.HttpStatusDescription", statusDescription); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception); }
private void OnConnectionModeKnownCore(Microsoft.ServiceBus.Channels.ConnectionModeReader modeReader, bool isCached) { Microsoft.ServiceBus.Channels.FramingMode connectionMode; lock (this.ThisLock) { if (!this.isClosed) { this.connectionReaders.Remove(modeReader); } else { return; } } bool flag = true; try { try { try { connectionMode = modeReader.GetConnectionMode(); } catch (CommunicationException communicationException1) { CommunicationException communicationException = communicationException1; TraceEventType exceptionEventType = modeReader.Connection.ExceptionEventType; if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTrace(exceptionEventType)) { Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.TraceHandledException(communicationException, exceptionEventType); } return; } catch (TimeoutException timeoutException1) { TimeoutException timeoutException = timeoutException1; if (!isCached) { string channelInitializationTimeout = Resources.ChannelInitializationTimeout; object[] objArray = new object[] { this.channelInitializationTimeout }; timeoutException = new TimeoutException(Microsoft.ServiceBus.SR.GetString(channelInitializationTimeout, objArray), timeoutException); ErrorBehavior.ThrowAndCatch(timeoutException); } TraceEventType traceEventType = modeReader.Connection.ExceptionEventType; if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTrace(traceEventType)) { Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.TraceHandledException(timeoutException, traceEventType); } return; } switch (connectionMode) { case Microsoft.ServiceBus.Channels.FramingMode.Singleton: { this.OnSingletonConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; } case Microsoft.ServiceBus.Channels.FramingMode.Duplex: { this.OnDuplexConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; } default: { string framingModeNotSupported = Resources.FramingModeNotSupported; object[] objArray1 = new object[] { connectionMode }; Exception invalidDataException = new InvalidDataException(Microsoft.ServiceBus.SR.GetString(framingModeNotSupported, objArray1)); Exception protocolException = new ProtocolException(invalidDataException.Message, invalidDataException); Microsoft.ServiceBus.Channels.FramingEncodingString.AddFaultString(protocolException, "http://schemas.microsoft.com/ws/2006/05/framing/faults/UnsupportedMode"); ErrorBehavior.ThrowAndCatch(protocolException); return; } } flag = false; } catch (Exception exception1) { Exception exception = exception1; if (Fx.IsFatal(exception)) { throw; } TraceEventType exceptionEventType1 = modeReader.Connection.ExceptionEventType; if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTrace(exceptionEventType1)) { Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, exceptionEventType1); } } } finally { if (flag) { modeReader.Dispose(); } } }
public void CtorWithProtocolMessage() { IProtocolMessage message = new Mocks.TestDirectedMessage(); ProtocolException ex = new ProtocolException("message", message); Assert.AreSame(message, ex.FaultedMessage); }
/// <summary> /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class. /// </summary> /// <param name="exception">The exception.</param> /// <param name="version">The protocol version.</param> internal UnauthorizedResponse(ProtocolException exception, Version version = null) : base(version ?? Protocol.Default.Version) { Contract.Requires<ArgumentNullException>(exception != null); this.ErrorMessage = exception.Message; }
public bool ProcessInfo(WsrmMessageInfo info, RequestContext context, bool throwException) { Exception faultException; if (info.ParsingException != null) { WsrmFault fault; if (this.SequenceID != null) { string faultReason = System.ServiceModel.SR.GetString("CouldNotParseWithAction", new object[] { info.Action }); fault = SequenceTerminatedFault.CreateProtocolFault(this.SequenceID, faultReason, null); } else { fault = null; } faultException = new ProtocolException(System.ServiceModel.SR.GetString("MessageExceptionOccurred"), info.ParsingException); this.OnLocalFault(throwException ? null : faultException, fault, context); } else if (info.FaultReply != null) { faultException = info.FaultException; this.OnLocalFault(throwException ? null : faultException, info.FaultReply, context); } else if (((info.WsrmHeaderFault != null) && (info.WsrmHeaderFault.SequenceID != this.InputID)) && (info.WsrmHeaderFault.SequenceID != this.OutputID)) { faultException = new ProtocolException(System.ServiceModel.SR.GetString("WrongIdentifierFault", new object[] { FaultException.GetSafeReasonText(info.WsrmHeaderFault.Reason) })); this.OnLocalFault(throwException ? null : faultException, (Message) null, context); } else { if (info.FaultInfo == null) { return true; } if (this.isSessionClosed) { UnknownSequenceFault faultInfo = info.FaultInfo as UnknownSequenceFault; if (faultInfo != null) { UniqueId sequenceID = faultInfo.SequenceID; if (((this.OutputID != null) && (this.OutputID == sequenceID)) || ((this.InputID != null) && (this.InputID == sequenceID))) { if (this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { info.Message.Close(); return false; } if (this.settings.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11) { throw Fx.AssertAndThrow("Unknown version."); } return true; } } } faultException = info.FaultException; if (context != null) { context.Close(); } this.OnRemoteFault(throwException ? null : faultException); } info.Message.Close(); if (throwException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(faultException); } return false; }