private void ProcessCloseOrTerminateReply(bool close, Message reply) { if (reply == null) { // In the close case, the requestor is configured to throw TimeoutException instead of returning null. // In the terminate case, this value can be null, but the caller should not call this method. throw Fx.AssertAndThrow("Argument reply cannot be null."); } ReliableMessagingVersion reliableMessagingVersion = settings.ReliableMessagingVersion; if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { if (close) { throw Fx.AssertAndThrow("Close does not exist in Feb2005."); } reply.Close(); } else if (reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) { WsrmMessageInfo info = closeRequestor.GetInfo(); // Close - Final ack made it. // Terminate - UnknownSequence. // Either way, message has been verified and does not belong to this thread. if (info != null) { return; } try { info = WsrmMessageInfo.Get(settings.MessageVersion, reliableMessagingVersion, binder.Channel, binder.GetInnerSession(), reply); session.ProcessInfo(info, null, true); session.VerifyDuplexProtocolElements(info, null, true); WsrmFault fault = close ? WsrmUtilities.ValidateCloseSequenceResponse(session, closeRequestor.MessageId, info, connection.Last) : WsrmUtilities.ValidateTerminateSequenceResponse(session, terminateRequestor.MessageId, info, connection.Last); if (fault != null) { session.OnLocalFault(null, fault, null); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(fault.CreateException()); } } finally { reply.Close(); } } else { throw Fx.AssertAndThrow("Reliable messaging version not supported."); } }
void ChangeUpgradeState(ref UpgradeState upgradeState, UpgradeState newState) { switch (newState) { case UpgradeState.None: throw Fx.AssertAndThrow("Invalid State Transition: currentState=" + upgradeState + ", newState=" + newState); case UpgradeState.VerifyingUpgradeRequest: if (upgradeState != UpgradeState.None && //starting first upgrade upgradeState != UpgradeState.UpgradeComplete) //completing one upgrade and starting another { throw Fx.AssertAndThrow("Invalid State Transition: currentState=" + upgradeState + ", newState=" + newState); } break; case UpgradeState.WritingUpgradeAck: if (upgradeState != UpgradeState.VerifyingUpgradeRequest) { throw Fx.AssertAndThrow("Invalid State Transition: currentState=" + upgradeState + ", newState=" + newState); } break; case UpgradeState.UpgradeAckSent: if (upgradeState != UpgradeState.WritingUpgradeAck) { throw Fx.AssertAndThrow("Invalid State Transition: currentState=" + upgradeState + ", newState=" + newState); } break; case UpgradeState.BeginUpgrade: if (upgradeState != UpgradeState.UpgradeAckSent) { throw Fx.AssertAndThrow("Invalid State Transition: currentState=" + upgradeState + ", newState=" + newState); } break; case UpgradeState.EndUpgrade: if (upgradeState != UpgradeState.BeginUpgrade) { throw Fx.AssertAndThrow("Invalid State Transition: currentState=" + upgradeState + ", newState=" + newState); } break; case UpgradeState.UpgradeComplete: if (upgradeState != UpgradeState.EndUpgrade) { throw Fx.AssertAndThrow("Invalid State Transition: currentState=" + upgradeState + ", newState=" + newState); } break; case UpgradeState.WritingPreambleEnd: if (upgradeState != UpgradeState.None && //no upgrade being used upgradeState != UpgradeState.UpgradeComplete) //upgrades are now complete, end the preamble handshake. { throw Fx.AssertAndThrow("Invalid State Transition: currentState=" + upgradeState + ", newState=" + newState); } break; case UpgradeState.PreambleEndSent: if (upgradeState != UpgradeState.WritingPreambleEnd) { throw Fx.AssertAndThrow("Invalid State Transition: currentState=" + upgradeState + ", newState=" + newState); } break; default: throw Fx.AssertAndThrow("Unexpected Upgrade State: " + newState); } upgradeState = newState; }
public Exception ThrowHelperInternal(bool fatal) { return(fatal ? Fx.AssertAndThrowFatal("Fatal InternalException should never be thrown.") : Fx.AssertAndThrow("InternalException should never be thrown.")); }
protected virtual Message OnEndRequest(TChannel channel, MaskingMode maskingMode, IAsyncResult result) { throw Fx.AssertAndThrow("The derived class does not support the OnEndRequest operation."); }
public async Task <int> ReceiveAsync(byte[] buffer, int offset, TimeSpan timeout) { byte[] header = new byte[2]; Fx.AssertAndThrow(State == WebSocketState.Open, ClientWebSocketNotInOpenStateDuringReceive); TcpClient.ReceiveTimeout = TimeoutHelper.ToMilliseconds(timeout); bool succeeded = false; try { byte payloadLength; bool pongFrame; // TODO: rewrite this section to handle all control frames (including ping) int totalBytesRead; int bytesRead; do { // Ignore pong frame and start over totalBytesRead = 0; totalBytesRead = await ReadFromStreamAsync(WebSocketStream, header).ConfigureAwait(false); if (totalBytesRead == 0) { throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes")); } if (!ParseWebSocketFrameHeader(header, out payloadLength, out pongFrame)) { // Encountered a close frame or error in parsing frame from server. Close connection byte[] closeHeader = PrepareWebSocketHeader(0, WebSocketMessageType.Close); await WriteToStreamAsync(WebSocketStream, closeHeader).ConfigureAwait(false); State = WebSocketState.Closed; WebSocketStream.Close(); TcpClient.Close(); return(0); // TODO: throw exception? } if (pongFrame && payloadLength > 0) { totalBytesRead = 0; byte[] tempBuffer = new byte[payloadLength]; while (totalBytesRead < payloadLength) { bytesRead = await ReadFromStreamAsync(WebSocketStream, tempBuffer, totalBytesRead, payloadLength - totalBytesRead).ConfigureAwait(false); if (bytesRead == 0) { throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes")); } totalBytesRead += bytesRead; } } }while (pongFrame); totalBytesRead = 0; if (buffer.Length < payloadLength) { throw Fx.Exception.AsError(new InvalidOperationException(SizeExceedsRemainingBufferSpace)); } if (payloadLength < MediumSizeFrame) { while (totalBytesRead < payloadLength) { bytesRead = await ReadFromStreamAsync(WebSocketStream, buffer, offset + totalBytesRead, payloadLength - totalBytesRead).ConfigureAwait(false); if (bytesRead == 0) { throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes")); } totalBytesRead += bytesRead; } } else { switch (payloadLength) { case MediumSizeFrame: // read payload length (< 64K) do { bytesRead = await ReadFromStreamAsync(WebSocketStream, header, totalBytesRead, header.Length - totalBytesRead).ConfigureAwait(false); if (bytesRead == 0) { throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes")); } totalBytesRead += bytesRead; }while (totalBytesRead < header.Length); totalBytesRead = 0; ushort extendedPayloadLength = (ushort)((header[0] << 8) | header[1]); // read payload if (buffer.Length >= extendedPayloadLength) { while (totalBytesRead < extendedPayloadLength) { bytesRead = await ReadFromStreamAsync(WebSocketStream, buffer, offset + totalBytesRead, extendedPayloadLength - totalBytesRead).ConfigureAwait(false); if (bytesRead == 0) { throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes")); } totalBytesRead += bytesRead; } } else { throw Fx.Exception.AsError(new InvalidOperationException(SizeExceedsRemainingBufferSpace)); } break; case LargeSizeFrame: // read payload length (>= 64K) byte[] payloadLengthBuffer = new byte[8]; do { bytesRead = await ReadFromStreamAsync(WebSocketStream, payloadLengthBuffer, totalBytesRead, payloadLengthBuffer.Length - totalBytesRead).ConfigureAwait(false); if (bytesRead == 0) { throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes")); } totalBytesRead += bytesRead; }while (totalBytesRead < payloadLengthBuffer.Length); totalBytesRead = 0; // ignore bytes 0-3 - length cannot be larger than a 32-bit number uint superExtendedPayloadLength = (uint)((payloadLengthBuffer[4] << 24) | (payloadLengthBuffer[5] << 16) | (payloadLengthBuffer[6] << 8) | payloadLengthBuffer[7]); // read payload if (buffer.Length >= superExtendedPayloadLength) { while (totalBytesRead < superExtendedPayloadLength) { bytesRead = await ReadFromStreamAsync(WebSocketStream, buffer, offset + totalBytesRead, (int)(superExtendedPayloadLength - totalBytesRead)).ConfigureAwait(false); if (bytesRead == 0) { throw new IOException(FramingPrematureEOF, new InvalidDataException("IotHubClientWebSocket was expecting more bytes")); } totalBytesRead += bytesRead; } } else { throw Fx.Exception.AsError(new InvalidOperationException(SizeExceedsRemainingBufferSpace)); } break; } } succeeded = true; return(totalBytesRead); } finally { if (!succeeded) { Fault(); } } }
private void ProcessWsdl() { string wsdlText; string portType; string bindingName; string address; string spnIdentity = null; string upnIdentity = null; string dnsIdentity = null; EndpointIdentity identity = null; string serializer = null; string contractNamespace = null; string bindingNamespace = null; propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Wsdl, out wsdlText); propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Contract, out portType); propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Binding, out bindingName); propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Address, out address); propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.SpnIdentity, out spnIdentity); propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.UpnIdentity, out upnIdentity); propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.DnsIdentity, out dnsIdentity); propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Serializer, out serializer); propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingNamespace, out bindingNamespace); propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.ContractNamespace, out contractNamespace); if (string.IsNullOrEmpty(wsdlText)) { throw Fx.AssertAndThrow("Wsdl should not be null at this point"); } if (string.IsNullOrEmpty(portType) || string.IsNullOrEmpty(bindingName) || string.IsNullOrEmpty(address)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.ContractBindingAddressCannotBeNull))); } if (!string.IsNullOrEmpty(spnIdentity)) { if ((!string.IsNullOrEmpty(upnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity))); } identity = EndpointIdentity.CreateSpnIdentity(spnIdentity); } else if (!string.IsNullOrEmpty(upnIdentity)) { if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity))); } identity = EndpointIdentity.CreateUpnIdentity(upnIdentity); } else if (!string.IsNullOrEmpty(dnsIdentity)) { if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(upnIdentity))) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity))); } identity = EndpointIdentity.CreateDnsIdentity(dnsIdentity); } else { identity = null; } bool removeXmlSerializerImporter = false; if (!String.IsNullOrEmpty(serializer)) { if ("xml" != serializer && "datacontract" != serializer) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorectSerializer))); } if ("xml" == serializer) { useXmlSerializer = true; } else { removeXmlSerializerImporter = true; // specifying datacontract will explicitly remove the Xml importer } // if this parameter is not set we will simply use indigo defaults } TextReader reader = new StringReader(wsdlText); try { try { WsdlNS.ServiceDescription wsdl = WsdlNS.ServiceDescription.Read(reader); if (String.IsNullOrEmpty(contractNamespace)) { contractNamespace = wsdl.TargetNamespace; } if (String.IsNullOrEmpty(bindingNamespace)) { bindingNamespace = wsdl.TargetNamespace; } WsdlNS.ServiceDescriptionCollection wsdlDocs = new WsdlNS.ServiceDescriptionCollection(); wsdlDocs.Add(wsdl); XmlSchemaSet schemas = new XmlSchemaSet(); foreach (XmlSchema schema in wsdl.Types.Schemas) { schemas.Add(schema); } MetadataSet mds = new MetadataSet(WsdlImporter.CreateMetadataDocuments(wsdlDocs, schemas, null)); WsdlImporter importer; if (useXmlSerializer) { importer = CreateXmlSerializerImporter(mds); } else { if (removeXmlSerializerImporter) { importer = CreateDataContractSerializerImporter(mds); } else { importer = new WsdlImporter(mds); } } XmlQualifiedName contractQname = new XmlQualifiedName(portType, contractNamespace); XmlQualifiedName bindingQname = new XmlQualifiedName(bindingName, bindingNamespace); WsdlNS.PortType wsdlPortType = wsdlDocs.GetPortType(contractQname); contractDescription = importer.ImportContract(wsdlPortType); WsdlNS.Binding wsdlBinding = wsdlDocs.GetBinding(bindingQname); Binding binding = importer.ImportBinding(wsdlBinding); EndpointAddress endpointAddress = new EndpointAddress(new Uri(address), identity, (AddressHeaderCollection)null); serviceEndpoint = new ServiceEndpoint(contractDescription, binding, endpointAddress); ComPlusWsdlChannelBuilderTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationWsdlChannelBuilderLoaded, SR.TraceCodeComIntegrationWsdlChannelBuilderLoaded, bindingQname, contractQname, wsdl, contractDescription, binding, wsdl.Types.Schemas); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.FailedImportOfWsdl, e.Message))); } } finally { IDisposable disposee = reader; disposee.Dispose(); } }
// This is called if we found an existing lock. This handle doesn't own the lock, but it could claim it, if it can prove // that no other live handle owns it. If this returns non-null, the outcome will be available later on the // InstanceHandleReference once the AsyncWaitHandle completes. (Null indicates a conflict with another handle.) // // The instanceVersion reported here was read under the transaction, but not changed. Either it was already committed, or it was written under // this transaction in a prior command on a different handle. Due to the latter case, we treat it as dirty - we do not publish it or take // any visible action (such as dooming handles) based on its value. internal AsyncWaitHandle InitiateLockResolution(long instanceVersion, ref InstanceHandleReference reference, ref List <InstanceHandleReference> handlesPendingResolution) { Fx.Assert(reference != null, "Bind wasn't registered - RegisterStartBind must be called."); Fx.Assert(reference.InstanceHandle != null, "Cannot cancel and complete a bind."); Fx.Assert(reference.InstanceHandle.Id != Guid.Empty, "Must be bound to an instance already."); Fx.AssertAndThrow(!(reference is LockResolutionMarker), "InitiateLockResolution already called."); lock (HandlesLock) { InstanceHandleReference cancelReference = reference; LockResolutionMarker markerReference = null; try { InstanceHandle existingHandle; if (BoundHandles.TryGetValue(reference.InstanceHandle.Id, out existingHandle)) { Fx.AssertAndFailFast(!object.ReferenceEquals(existingHandle, reference.InstanceHandle), "InstanceStore lock state is not correct in InitiateLockResolution."); if (existingHandle.Version <= 0 || instanceVersion <= 0) { if (existingHandle.Version != 0 || instanceVersion != 0) { throw Fx.Exception.AsError(new InvalidOperationException(SRCore.InvalidLockToken)); } reference.InstanceHandle.ConflictingHandle = existingHandle; return(null); } if (existingHandle.Version >= instanceVersion) { reference.InstanceHandle.ConflictingHandle = existingHandle; return(null); } } // Put a marker in the InProgressHandles. If it makes it through, and there's still no conflicting handle, // then the lock can be claimed at this version. Only currently in-progress bindings have a chance of // staking a stronger claim to the lock version (if the store actually acquired the lock for the handle). markerReference = new LockResolutionMarker(reference.InstanceHandle, instanceVersion); EnqueueReference(markerReference); reference = markerReference; Fx.Assert(markerReference.MarkerWaitHandle != null, "Null MarkerWaitHandle?"); return(markerReference.MarkerWaitHandle); } finally { if (!object.ReferenceEquals(markerReference, reference)) { CancelReference(ref reference, ref handlesPendingResolution); if (markerReference != null) { cancelReference = markerReference; CancelReference(ref cancelReference, ref handlesPendingResolution); } } else { CancelReference(ref cancelReference, ref handlesPendingResolution); } } } }
ChannelProtectionRequirements GetProtectionRequirements() { // Listing headers that must be signed. ChannelProtectionRequirements result = new ChannelProtectionRequirements(); MessagePartSpecification signedReliabilityMessageParts = WsrmIndex.GetSignedReliabilityMessageParts( this.reliableMessagingVersion); result.IncomingSignatureParts.AddParts(signedReliabilityMessageParts); result.OutgoingSignatureParts.AddParts(signedReliabilityMessageParts); if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { // Adding RM protocol message actions so that each RM protocol message's body will be // signed and encrypted. // From the Client to the Service ScopedMessagePartSpecification signaturePart = result.IncomingSignatureParts; ScopedMessagePartSpecification encryptionPart = result.IncomingEncryptionParts; ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.AckRequestedAction); ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.CreateSequenceAction); ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.SequenceAcknowledgementAction); ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.LastMessageAction); ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.TerminateSequenceAction); // From the Service to the Client signaturePart = result.OutgoingSignatureParts; encryptionPart = result.OutgoingEncryptionParts; ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.CreateSequenceResponseAction); ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.SequenceAcknowledgementAction); ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.LastMessageAction); ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.TerminateSequenceAction); } else if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) { // Adding RM protocol message actions so that each RM protocol message's body will be // signed and encrypted. // From the Client to the Service ScopedMessagePartSpecification signaturePart = result.IncomingSignatureParts; ScopedMessagePartSpecification encryptionPart = result.IncomingEncryptionParts; ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.AckRequestedAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CloseSequenceAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CloseSequenceResponseAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CreateSequenceAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.FaultAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.SequenceAcknowledgementAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.TerminateSequenceAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.TerminateSequenceResponseAction); // From the Service to the Client signaturePart = result.OutgoingSignatureParts; encryptionPart = result.OutgoingEncryptionParts; ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.AckRequestedAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CloseSequenceAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CloseSequenceResponseAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CreateSequenceResponseAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.FaultAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.SequenceAcknowledgementAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.TerminateSequenceAction); ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.TerminateSequenceResponseAction); } else { throw Fx.AssertAndThrow("Reliable messaging version not supported."); } return(result); }
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); } }
internal void Enqueue(MultipleReceiveBinder.ReceiveScopeSignalGate receiveScope) { Fx.AssertAndThrow(this.count < this.size, "Cannot Enqueue into a full queue."); this.items[(this.head + this.count) % this.size] = receiveScope; this.count++; }
public static string ConvertNativeValueToString(object value) { if (value != null) { if (value is bool) { return(XmlConvert.ToString((bool)value)); } if (value is byte) { return(XmlConvert.ToString((byte)value)); } if (value is char) { return(XmlConvert.ToString((char)value)); } if (value is DateTime) { return(XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind)); } if (value is DateTimeOffset) { return(XmlConvert.ToString((DateTimeOffset)value)); } if (value is decimal) { return(XmlConvert.ToString((decimal)value)); } if (value is double) { return(XmlConvert.ToString((double)value)); } if (value is float) { float num = (float)value; return(num.ToString("r", CultureInfo.InvariantCulture)); } if (value is Guid) { return(XmlConvert.ToString((Guid)value)); } if (value is int) { return(XmlConvert.ToString((int)value)); } if (value is long) { return(XmlConvert.ToString((long)value)); } if (value is sbyte) { return(XmlConvert.ToString((sbyte)value)); } if (value is short) { return(XmlConvert.ToString((short)value)); } if (value is string) { return((string)value); } if (value is TimeSpan) { return(XmlConvert.ToString((TimeSpan)value)); } if (value is Type) { return(value.ToString()); } if (value is uint) { return(XmlConvert.ToString((uint)value)); } if (value is ulong) { return(XmlConvert.ToString((ulong)value)); } if (value is Uri) { return(((Uri)value).ToString()); } if (value is ushort) { return(XmlConvert.ToString((ushort)value)); } if (value is XmlQualifiedName) { return(((XmlQualifiedName)value).ToString()); } Fx.AssertAndThrow("Should never reach here"); } return(null); }
public void Close(TimeSpan timeout) { CommunicationState communicationState; ServiceModelActivity serviceModelActivity; if (timeout < TimeSpan.Zero) { throw Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("timeout", Microsoft.ServiceBus.SR.GetString(Resources.SFxTimeoutOutOfRange0, new object[0]))); } if (!Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldUseActivity || !this.TraceOpenAndClose) { serviceModelActivity = null; } else { serviceModelActivity = this.CreateCloseActivity(); } using (serviceModelActivity) { lock (this.ThisLock) { if (this.refCount == 0) { throw new InvalidOperationException(SRClient.InvalidRefcountedCommunicationObject); } RefcountedCommunicationObject refcountedCommunicationObject = this; int num = refcountedCommunicationObject.refCount - 1; int num1 = num; refcountedCommunicationObject.refCount = num; if (num1 <= 0) { communicationState = this.state; if (communicationState != CommunicationState.Closed) { this.state = CommunicationState.Closing; } this.closeCalled = true; } else { return; } } switch (communicationState) { case CommunicationState.Created: case CommunicationState.Opening: case CommunicationState.Faulted: { this.Abort(); if (communicationState != CommunicationState.Faulted) { return; } throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); } case CommunicationState.Opened: { bool flag = true; try { this.OnClosing(); if (!this.onClosingCalled) { throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); } this.OnClose(timeout); this.OnClosed(); if (!this.onClosedCalled) { throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); } flag = false; return; } finally { if (flag) { if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTraceWarning) { DiagnosticTrace diagnosticTrace = Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.DiagnosticTrace; string traceCodeCommunicationObjectCloseFailed = Resources.TraceCodeCommunicationObjectCloseFailed; object[] str = new object[] { this.GetCommunicationObjectType().ToString() }; diagnosticTrace.TraceEvent(TraceEventType.Warning, TraceCode.CommunicationObjectCloseFailed, Microsoft.ServiceBus.SR.GetString(traceCodeCommunicationObjectCloseFailed, str), null, null, this); } this.Abort(); } } break; } case CommunicationState.Closing: case CommunicationState.Closed: { return; } } throw Fx.AssertAndThrow("CommunicationObject.BeginClose: Unknown CommunicationState"); } }
protected async Task ProcessMessageAsync(Message message) { bool closeMessage = true; WsrmMessageInfo messageInfo = WsrmMessageInfo.Get(Settings.MessageVersion, Settings.ReliableMessagingVersion, _binder.Channel, _binder.GetInnerSession(), message); bool wsrm11 = Settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11; try { if (!_session.ProcessInfo(messageInfo, null)) { closeMessage = false; return; } if (!ReliableSession.VerifySimplexProtocolElements(messageInfo, null)) { closeMessage = false; return; } bool final = false; if (messageInfo.AcknowledgementInfo != null) { final = wsrm11 && messageInfo.AcknowledgementInfo.Final; int bufferRemaining = -1; if (Settings.FlowControlEnabled) { bufferRemaining = messageInfo.AcknowledgementInfo.BufferRemaining; } Connection.ProcessTransferred(messageInfo.AcknowledgementInfo.Ranges, bufferRemaining); } if (wsrm11) { WsrmFault fault = null; if (messageInfo.TerminateSequenceResponseInfo != null) { fault = WsrmUtilities.ValidateTerminateSequenceResponse(_session, _terminateRequestor.MessageId, messageInfo, Connection.Last); if (fault == null) { fault = ProcessRequestorResponse(_terminateRequestor, WsrmFeb2005Strings.TerminateSequence, messageInfo); } } else if (messageInfo.CloseSequenceResponseInfo != null) { fault = WsrmUtilities.ValidateCloseSequenceResponse(_session, _closeRequestor.MessageId, messageInfo, Connection.Last); if (fault == null) { fault = ProcessRequestorResponse(_closeRequestor, Wsrm11Strings.CloseSequence, messageInfo); } } else if (messageInfo.TerminateSequenceInfo != null) { if (!WsrmUtilities.ValidateWsrmRequest(_session, messageInfo.TerminateSequenceInfo, _binder, null)) { return; } WsrmAcknowledgmentInfo ackInfo = messageInfo.AcknowledgementInfo; fault = WsrmUtilities.ValidateFinalAckExists(_session, ackInfo); if ((fault == null) && !Connection.IsFinalAckConsistent(ackInfo.Ranges)) { fault = new InvalidAcknowledgementFault(_session.OutputID, ackInfo.Ranges); } if (fault == null) { Message response = WsrmUtilities.CreateTerminateResponseMessage( Settings.MessageVersion, messageInfo.TerminateSequenceInfo.MessageId, _session.OutputID); try { await OnConnectionSendAsync(response, DefaultSendTimeout, false, true); } finally { response.Close(); } _session.OnRemoteFault(new ProtocolException(SR.UnsupportedTerminateSequenceExceptionString)); return; } } else if (final) { if (_closeRequestor == null) { string exceptionString = SR.UnsupportedCloseExceptionString; string faultString = SR.SequenceTerminatedUnsupportedClose; fault = SequenceTerminatedFault.CreateProtocolFault(_session.OutputID, faultString, exceptionString); } else { fault = WsrmUtilities.ValidateFinalAck(_session, messageInfo, Connection.Last); if (fault == null) { _closeRequestor.SetInfo(messageInfo); } } } else if (messageInfo.WsrmHeaderFault != null) { if (!(messageInfo.WsrmHeaderFault is UnknownSequenceFault)) { throw Fx.AssertAndThrow("Fault must be UnknownSequence fault."); } if (_terminateRequestor == null) { throw Fx.AssertAndThrow("In wsrm11, if we start getting UnknownSequence, terminateRequestor cannot be null."); } _terminateRequestor.SetInfo(messageInfo); } if (fault != null) { _session.OnLocalFault(fault.CreateException(), fault, null); return; } } _session.OnRemoteActivity(Connection.Strategy.QuotaRemaining == 0); } finally { if (closeMessage) { messageInfo.Message.Close(); } } }
private void ProcessReply(Message reply, IReliableRequest request, long requestSequenceNumber) { WsrmMessageInfo messageInfo = WsrmMessageInfo.Get(settings.MessageVersion, settings.ReliableMessagingVersion, binder.Channel, binder.GetInnerSession(), reply); if (!session.ProcessInfo(messageInfo, null)) { return; } if (!session.VerifyDuplexProtocolElements(messageInfo, null)) { return; } bool wsrm11 = settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11; if (messageInfo.WsrmHeaderFault != null) { // Close message now, going to stop processing in all cases. messageInfo.Message.Close(); if (!(messageInfo.WsrmHeaderFault is UnknownSequenceFault)) { throw Fx.AssertAndThrow("Fault must be UnknownSequence fault."); } if (terminateRequestor == null) { throw Fx.AssertAndThrow("If we start getting UnknownSequence, terminateRequestor cannot be null."); } terminateRequestor.SetInfo(messageInfo); return; } if (messageInfo.AcknowledgementInfo == null) { WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(session.InputID, SR.SequenceTerminatedReplyMissingAcknowledgement, SR.ReplyMissingAcknowledgement); messageInfo.Message.Close(); session.OnLocalFault(fault.CreateException(), fault, null); return; } if (wsrm11 && (messageInfo.TerminateSequenceInfo != null)) { UniqueId faultId = (messageInfo.TerminateSequenceInfo.Identifier == session.OutputID) ? session.InputID : session.OutputID; WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(faultId, SR.SequenceTerminatedUnsupportedTerminateSequence, SR.UnsupportedTerminateSequenceExceptionString); messageInfo.Message.Close(); session.OnLocalFault(fault.CreateException(), fault, null); return; } else if (wsrm11 && messageInfo.AcknowledgementInfo.Final) { // Close message now, going to stop processing in all cases. messageInfo.Message.Close(); if (closeRequestor == null) { // Remote endpoint signaled Close, this is not allowed so we fault. string exceptionString = SR.UnsupportedCloseExceptionString; string faultString = SR.SequenceTerminatedUnsupportedClose; WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(session.OutputID, faultString, exceptionString); session.OnLocalFault(fault.CreateException(), fault, null); } else { WsrmFault fault = WsrmUtilities.ValidateFinalAck(session, messageInfo, connection.Last); if (fault == null) { // Received valid final ack after sending Close, inform the close thread. closeRequestor.SetInfo(messageInfo); } else { // Received invalid final ack after sending Close, fault. session.OnLocalFault(fault.CreateException(), fault, null); } } return; } int bufferRemaining = -1; if (settings.FlowControlEnabled) { bufferRemaining = messageInfo.AcknowledgementInfo.BufferRemaining; } // We accept no more than MaxSequenceRanges ranges to limit the serialized ack size and // the amount of memory taken up by the ack ranges. Since request reply uses the presence of // a reply as an acknowledgement we cannot call ProcessTransferred (which stops retrying the // request) if we intend to drop the message. This means the limit is not strict since we do // not check for the limit and merge the ranges atomically. The limit + the number of // concurrent threads is a sufficient mitigation. if ((messageInfo.SequencedMessageInfo != null) && !ReliableInputConnection.CanMerge(messageInfo.SequencedMessageInfo.SequenceNumber, ranges)) { messageInfo.Message.Close(); return; } bool exitGuard = replyAckConsistencyGuard != null?replyAckConsistencyGuard.Enter() : false; try { connection.ProcessTransferred(requestSequenceNumber, messageInfo.AcknowledgementInfo.Ranges, bufferRemaining); session.OnRemoteActivity(connection.Strategy.QuotaRemaining == 0); if (messageInfo.SequencedMessageInfo != null) { lock (ThisLock) { ranges = ranges.MergeWith(messageInfo.SequencedMessageInfo.SequenceNumber); } } } finally { if (exitGuard) { replyAckConsistencyGuard.Exit(); } } if (request != null) { if (WsrmUtilities.IsWsrmAction(settings.ReliableMessagingVersion, messageInfo.Action)) { messageInfo.Message.Close(); request.Set(null); } else { request.Set(messageInfo.Message); } } // The termination mechanism in the TerminateSequence fails with RequestReply. // Since the ack ranges are updated after ProcessTransferred is called and // ProcessTransferred potentially signals the Termination process, this channel // winds up sending a message with the ack for last message missing. // Thus we send the termination after we update the ranges. if ((shutdownHandle != null) && connection.CheckForTermination()) { shutdownHandle.Set(); } if (request != null) { request.Complete(); } }
/// <summary> /// Copies the properties from the amqp message to the Message instance. /// </summary> public static void UpdateMessageHeaderAndProperties(AmqpMessage amqpMessage, Message data) { Fx.AssertAndThrow(amqpMessage.DeliveryTag != null, "AmqpMessage should always contain delivery tag."); data.DeliveryTag = amqpMessage.DeliveryTag; SectionFlag sections = amqpMessage.Sections; if ((sections & SectionFlag.Properties) != 0) { // Extract only the Properties that we support data.MessageId = amqpMessage.Properties.MessageId != null?amqpMessage.Properties.MessageId.ToString() : null; data.To = amqpMessage.Properties.To != null?amqpMessage.Properties.To.ToString() : null; if (amqpMessage.Properties.AbsoluteExpiryTime.HasValue) { data.ExpiryTimeUtc = amqpMessage.Properties.AbsoluteExpiryTime.Value; } data.CorrelationId = amqpMessage.Properties.CorrelationId != null?amqpMessage.Properties.CorrelationId.ToString() : null; data.UserId = amqpMessage.Properties.UserId.Array != null?Encoding.UTF8.GetString(amqpMessage.Properties.UserId.Array) : null; } if ((sections & SectionFlag.MessageAnnotations) != 0) { string lockToken; if (amqpMessage.MessageAnnotations.Map.TryGetValue(LockTokenName, out lockToken)) { data.LockToken = lockToken; } ulong sequenceNumber; if (amqpMessage.MessageAnnotations.Map.TryGetValue(SequenceNumberName, out sequenceNumber)) { data.SequenceNumber = sequenceNumber; } DateTime enqueuedTime; if (amqpMessage.MessageAnnotations.Map.TryGetValue(MessageSystemPropertyNames.EnqueuedTime, out enqueuedTime)) { data.EnqueuedTimeUtc = enqueuedTime; } byte deliveryCount; if (amqpMessage.MessageAnnotations.Map.TryGetValue(MessageSystemPropertyNames.DeliveryCount, out deliveryCount)) { data.DeliveryCount = deliveryCount; } } if ((sections & SectionFlag.ApplicationProperties) != 0) { foreach (KeyValuePair <MapKey, object> pair in amqpMessage.ApplicationProperties.Map) { object netObject = null; if (TryGetNetObjectFromAmqpObject(pair.Value, MappingType.ApplicationProperty, out netObject)) { var stringObject = netObject as string; if (stringObject != null) { switch (pair.Key.ToString()) { case MessageSystemPropertyNames.Operation: data.SystemProperties[pair.Key.ToString()] = stringObject; break; default: data.Properties[pair.Key.ToString()] = stringObject; break; } } else { // TODO: RDBug 4093369 Handling of non-string property values in Amqp messages // Drop non-string properties and log an error Fx.Exception.TraceHandled(new InvalidDataException("IotHub does not accept non-string Amqp properties"), "MessageConverter.UpdateMessageHeaderAndProperties"); } } } } }
void ProcessCreateSequenceResponse(Message response, DateTime start) { CreateSequenceResponseInfo createResponse = null; using (response) { if (response.IsFault) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WsrmUtilities.CreateCSFaultException( this.Settings.MessageVersion, this.Settings.ReliableMessagingVersion, response, this.binder.Channel)); } else { WsrmMessageInfo info = WsrmMessageInfo.Get(this.Settings.MessageVersion, this.Settings.ReliableMessagingVersion, this.binder.Channel, this.binder.GetInnerSession(), response, true); if (info.ParsingException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.UnparsableCSResponse), info.ParsingException)); } // this throws and sends a fault if something is wrong with the info this.ProcessInfo(info, null, true); createResponse = info.CreateSequenceResponseInfo; string exceptionReason = null; string faultReason = null; if (createResponse == null) { exceptionReason = SR.GetString(SR.InvalidWsrmResponseChannelNotOpened, WsrmFeb2005Strings.CreateSequence, info.Action, WsrmIndex.GetCreateSequenceResponseActionString(this.Settings.ReliableMessagingVersion)); } else if (!object.Equals(createResponse.RelatesTo, this.requestor.MessageId)) { exceptionReason = SR.GetString(SR.WsrmMessageWithWrongRelatesToExceptionString, WsrmFeb2005Strings.CreateSequence); faultReason = SR.GetString(SR.WsrmMessageWithWrongRelatesToFaultString, WsrmFeb2005Strings.CreateSequence); } else if ((createResponse.AcceptAcksTo == null) && (this.InputID != null)) { if (this.Settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005) { exceptionReason = SR.GetString(SR.CSResponseWithoutOffer); faultReason = SR.GetString(SR.CSResponseWithoutOfferReason); } else if (this.Settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11) { exceptionReason = SR.GetString(SR.CSResponseOfferRejected); faultReason = SR.GetString(SR.CSResponseOfferRejectedReason); } else { throw Fx.AssertAndThrow("Reliable messaging version not supported."); } } else if ((createResponse.AcceptAcksTo != null) && (this.InputID == null)) { exceptionReason = SR.GetString(SR.CSResponseWithOffer); faultReason = SR.GetString(SR.CSResponseWithOfferReason); } else if (createResponse.AcceptAcksTo != null && (createResponse.AcceptAcksTo.Uri != this.binder.RemoteAddress.Uri)) { exceptionReason = SR.GetString(SR.AcksToMustBeSameAsRemoteAddress); faultReason = SR.GetString(SR.AcksToMustBeSameAsRemoteAddressReason); } if ((faultReason != null) && (createResponse != null)) { UniqueId sequenceId = createResponse.Identifier; WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(sequenceId, faultReason, null); this.OnLocalFault(null, fault, null); } if (exceptionReason != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(exceptionReason)); } } } this.InitiationTime = DateTime.UtcNow - start; this.OutputID = createResponse.Identifier; this.pollingTimer.Set(this.GetPollingInterval()); base.StartInactivityTimer(); }
/// <summary> /// Copies the properties from the AMQP message to the Message instance. /// </summary> public static void UpdateMessageHeaderAndProperties(AmqpMessage amqpMessage, Message message) { Fx.AssertAndThrow(amqpMessage.DeliveryTag != null, "AmqpMessage should always contain delivery tag."); message.DeliveryTag = amqpMessage.DeliveryTag; SectionFlag sections = amqpMessage.Sections; if ((sections & SectionFlag.Properties) != 0) { // Extract only the Properties that we support message.MessageId = amqpMessage.Properties.MessageId?.ToString(); message.To = amqpMessage.Properties.To?.ToString(); if (amqpMessage.Properties.AbsoluteExpiryTime.HasValue) { message.ExpiryTimeUtc = amqpMessage.Properties.AbsoluteExpiryTime.Value; } message.CorrelationId = amqpMessage.Properties.CorrelationId?.ToString(); if (!string.IsNullOrWhiteSpace(amqpMessage.Properties.ContentType.Value)) { message.ContentType = amqpMessage.Properties.ContentType.Value; } if (!string.IsNullOrWhiteSpace(amqpMessage.Properties.ContentEncoding.Value)) { message.ContentEncoding = amqpMessage.Properties.ContentEncoding.Value; } message.UserId = amqpMessage.Properties.UserId.Array != null ? Encoding.UTF8.GetString(amqpMessage.Properties.UserId.Array, 0 /*index*/, amqpMessage.Properties.UserId.Array.Length) : null; } if ((sections & SectionFlag.MessageAnnotations) != 0) { if (amqpMessage.MessageAnnotations.Map.TryGetValue(LockTokenName, out string lockToken)) { message.LockToken = lockToken; } if (amqpMessage.MessageAnnotations.Map.TryGetValue(SequenceNumberName, out ulong sequenceNumber)) { message.SequenceNumber = sequenceNumber; } if (amqpMessage.MessageAnnotations.Map.TryGetValue(MessageSystemPropertyNames.EnqueuedTime, out DateTime enqueuedTime)) { message.EnqueuedTimeUtc = enqueuedTime; } if (amqpMessage.MessageAnnotations.Map.TryGetValue(MessageSystemPropertyNames.DeliveryCount, out byte deliveryCount)) { message.DeliveryCount = deliveryCount; } if (amqpMessage.MessageAnnotations.Map.TryGetValue(InputName, out string inputName)) { message.InputName = inputName; } if (amqpMessage.MessageAnnotations.Map.TryGetValue(MessageSystemPropertyNames.ConnectionDeviceId, out string connectionDeviceId)) { message.ConnectionDeviceId = connectionDeviceId; } if (amqpMessage.MessageAnnotations.Map.TryGetValue(MessageSystemPropertyNames.ConnectionModuleId, out string connectionModuleId)) { message.ConnectionModuleId = connectionModuleId; } } if ((sections & SectionFlag.ApplicationProperties) != 0) { foreach (KeyValuePair <MapKey, object> pair in amqpMessage.ApplicationProperties.Map) { if (TryGetNetObjectFromAmqpObject(pair.Value, MappingType.ApplicationProperty, out object netObject)) { string stringObject = netObject as string; if (stringObject != null) { switch (pair.Key.ToString()) { case MessageSystemPropertyNames.Operation: message.SystemProperties[pair.Key.ToString()] = stringObject; break; case MessageSystemPropertyNames.MessageSchema: message.MessageSchema = stringObject; break; case MessageSystemPropertyNames.CreationTimeUtc: message.CreationTimeUtc = DateTime.Parse(stringObject, CultureInfo.InvariantCulture); break; default: message.Properties[pair.Key.ToString()] = stringObject; break; } } else { // TODO: RDBug 4093369 Handling of non-string property values in AMQP messages // Drop non-string properties and log an error Fx.Exception.TraceHandled(new InvalidDataException("IotHub does not accept non-string Amqp properties"), "MessageConverter.UpdateMessageHeaderAndProperties"); } } } } }
/// <summary> /// Flush the content of the given buffer to the remote peer. /// </summary> /// <param name="channelOutboundBuffer">The buffer to write to the remote peer.</param> protected override async void DoWrite(ChannelOutboundBuffer channelOutboundBuffer) { if (Logging.IsEnabled) { Logging.Enter(this, nameof(DoWrite)); } if (channelOutboundBuffer == null) { throw new ArgumentNullException(nameof(channelOutboundBuffer), "The channel outbound buffer cannot be null."); } try { // The ChannelOutboundBuffer might have more than one message per MQTT packet that needs to be written to the websocket as a single frame. // One example of this is a PUBLISH packet, which encodes the payload and topic information as separate messages. // In order to reduce the number of frames sent to the websocket, we will consolidate the individual messages per MQTT packet into a single byte buffer. IByteBufferAllocator allocator = Configuration.Allocator; // The parameter "direct" is used to indicate if operations carried out in the CompositeByteBuffer should be treated as "unsafe". var compositeByteBuffer = new CompositeByteBuffer(allocator, direct: false, maxNumComponents: int.MaxValue); var bytesToBeWritten = new ArraySegment <byte>(); _isWriteInProgress = true; while (true) { object currentMessage = channelOutboundBuffer.Current; // Once there are no more messages pending in ChannelOutboundBuffer, the "Current" property is returned as "null". // This indicates that all pending messages have been dequeued from the ChannelOutboundBuffer and are ready to be written to the websocket. if (currentMessage == null) { // This indicates that the ChannelOutboundBuffer had readable bytes and they have been added to the CompositeByteBuffer. if (compositeByteBuffer.NumComponents > 0) { // All messages have been added to the CompositeByteBuffer and are now ready to be written to the socket. bytesToBeWritten = compositeByteBuffer.GetIoBuffer(); } break; } var byteBuffer = currentMessage as IByteBuffer; Fx.AssertAndThrow(byteBuffer != null, "channelOutBoundBuffer contents must be of type IByteBuffer"); // If the byte buffer has readable bytes then add them to the CompositeByteBuffer. if (byteBuffer.ReadableBytes != 0) { // There are two operations carried out while adding a byte buffer component to a CompositeByteBuffer: // - Increase WriterIndex of the CompositeByteBuffer // - increases the count of readable bytes added to the CompositeByteBuffer. // - Call the method Retain() on the byte buffer being added // - The property ReferenceCount of a byte buffer implementation maintains a counter of the no of messages available for dequeuing. // A ReferenceCount of 0 indicates that all messages have been flushed and the buffer can be deallocated. // By calling the method Retain() on each byte buffer component added to the CompositeByteBuffer, // we increase the ReferenceCount by 1 and mark them as ready for dequeuing. compositeByteBuffer .AddComponent( increaseWriterIndex: true, buffer: (IByteBuffer)byteBuffer.Retain()); } // Once the readable bytes are added to the CompositeByteBuffer they can be removed from the ChannelOutboundBuffer // and the next message, if any, can be processed. channelOutboundBuffer.Remove(); } if (bytesToBeWritten.Count > 0) { if (Logging.IsEnabled) { Logging.Info(this, $"Writing bytes of size {bytesToBeWritten.Count} to the websocket", nameof(DoWrite)); } await _webSocket.SendAsync(bytesToBeWritten, WebSocketMessageType.Binary, true, _writeCancellationTokenSource.Token).ConfigureAwait(false); } _isWriteInProgress = false; } catch (Exception e) when(!e.IsFatal()) { // Since this method returns void, all exceptions must be handled here. _isWriteInProgress = false; Pipeline.FireExceptionCaught(e); await HandleCloseAsync().ConfigureAwait(false); } finally { if (Logging.IsEnabled) { Logging.Exit(this, nameof(DoWrite)); } } }
// This happens only when the transaction under which the handle was bound is committed. internal bool TryCompleteBind(ref InstanceHandleReference reference, ref List <InstanceHandleReference> handlesPendingResolution, out InstanceHandle handleToFree) { Fx.Assert(reference != null, "Bind wasn't registered - RegisterStartBind must be called."); Fx.Assert(reference.InstanceHandle != null, "Cannot cancel and complete a bind."); Fx.Assert(reference.InstanceHandle.Version != -1, "Handle state must be set first."); Fx.Assert(object.ReferenceEquals(this, reference.InstanceHandle.Owner), "TryCompleteBind called on the wrong owner for a handle."); Fx.Assert(!(reference is LockResolutionMarker) || ((LockResolutionMarker)reference).NonConflicting, "How did a Version get set if we're still resolving."); handleToFree = null; lock (HandlesLock) { try { InstanceHandle existingHandle; if (BoundHandles.TryGetValue(reference.InstanceHandle.Id, out existingHandle)) { Fx.AssertAndFailFast(!object.ReferenceEquals(existingHandle, reference.InstanceHandle), "InstanceStore lock state is not correct."); if (existingHandle.Version <= 0 || reference.InstanceHandle.Version <= 0) { if (existingHandle.Version != 0 || reference.InstanceHandle.Version != 0) { throw Fx.Exception.AsError(new InvalidOperationException(SRCore.InvalidLockToken)); } reference.InstanceHandle.ConflictingHandle = existingHandle; return(false); } if (existingHandle.Version > reference.InstanceHandle.Version) { reference.InstanceHandle.ConflictingHandle = existingHandle; return(false); } if (existingHandle.Version < reference.InstanceHandle.Version) { existingHandle.ConflictingHandle = reference.InstanceHandle; handleToFree = existingHandle; BoundHandles[reference.InstanceHandle.Id] = reference.InstanceHandle; return(true); } if (existingHandle.Version == reference.InstanceHandle.Version) { // This could be a case of amnesia (backup / restore). throw Fx.Exception.AsError(new InvalidOperationException(SRCore.InstanceStoreBoundSameVersionTwice)); } throw Fx.AssertAndThrow("All cases covered above."); } else { BoundHandles.Add(reference.InstanceHandle.Id, reference.InstanceHandle); return(true); } } finally { CancelReference(ref reference, ref handlesPendingResolution); } } }
async Task IAsyncCommunicationObject.CloseAsync(TimeSpan timeout) { if (timeout < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("timeout", SR.SFxTimeoutOutOfRange0)); } CommunicationState originalState; lock (ThisLock) { originalState = _state; if (originalState != CommunicationState.Closed) { _state = CommunicationState.Closing; } _closeCalled = true; } switch (originalState) { case CommunicationState.Created: case CommunicationState.Opening: case CommunicationState.Faulted: this.Abort(); if (originalState == CommunicationState.Faulted) { throw TraceUtility.ThrowHelperError(this.CreateFaultedException(), Guid.Empty, this); } break; case CommunicationState.Opened: { bool throwing = true; try { TimeoutHelper actualTimeout = new TimeoutHelper(timeout); OnClosing(); if (!_onClosingCalled) { throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); } await OnCloseAsync(actualTimeout.RemainingTime()); OnClosed(); if (!_onClosedCalled) { throw TraceUtility.ThrowHelperError(this.CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); } throwing = false; } finally { if (throwing) { Abort(); } } break; } case CommunicationState.Closing: case CommunicationState.Closed: break; default: throw Fx.AssertAndThrow("CommunicationObject.BeginClose: Unknown CommunicationState"); } }
protected virtual IAsyncResult OnBeginRequest(TChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode, AsyncCallback callback, object state) { throw Fx.AssertAndThrow("The derived class does not support the OnBeginRequest operation."); }
private Assembly ResolveAssemblyFromTypeLibID(Guid iid, Guid typeLibraryID, string version, bool noAssemblyGeneration) { Assembly assembly; ComPlusTLBImportTrace.Trace(TraceEventType.Verbose, 0x5000d, "TraceCodeComIntegrationTLBImportStarting", iid, typeLibraryID); bool flag = false; ITypeLib2 typeLibrary = null; try { lock (this.assemblyTableLock) { this.assemblyTable.TryGetValue(typeLibraryID, out assembly); if (assembly == null) { typeLibrary = this.GettypeLibrary(typeLibraryID, version); object pVarVal = null; typeLibrary.GetCustData(ref clrAssemblyCustomID, out pVarVal); if (pVarVal == null) { flag = true; } string str = pVarVal as string; if (string.IsNullOrEmpty(str)) { flag = true; } if (noAssemblyGeneration && flag) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("NativeTypeLibraryNotAllowed", new object[] { typeLibraryID }))); } if (!flag) { ComPlusTLBImportTrace.Trace(TraceEventType.Verbose, 0x5000e, "TraceCodeComIntegrationTLBImportFromAssembly", iid, typeLibraryID, str); assembly = Assembly.Load(str); } else { ComPlusTLBImportTrace.Trace(TraceEventType.Verbose, 0x5000f, "TraceCodeComIntegrationTLBImportFromTypelib", iid, typeLibraryID); assembly = TypeLibraryHelper.GenerateAssemblyFromNativeTypeLibrary(iid, typeLibraryID, typeLibrary); } this.assemblyTable[typeLibraryID] = assembly; } } } catch (Exception exception) { DiagnosticUtility.EventLog.LogEvent(TraceEventType.Error, EventLogCategory.ComPlus, (EventLogEventId)(-1073610728), new string[] { iid.ToString(), typeLibraryID.ToString(), exception.ToString() }); throw; } finally { if (typeLibrary != null) { Marshal.ReleaseComObject(typeLibrary); } } if (null == assembly) { throw Fx.AssertAndThrow("Assembly should not be null"); } ComPlusTLBImportTrace.Trace(TraceEventType.Verbose, 0x50011, "TraceCodeComIntegrationTLBImportFinished", iid, typeLibraryID); return(assembly); }
protected virtual Message OnRequest(TChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode) { throw Fx.AssertAndThrow("The derived class does not support the OnRequest operation."); }
protected void ProcessMessage(Message message) { bool flag = true; WsrmMessageInfo info = WsrmMessageInfo.Get(this.settings.MessageVersion, this.settings.ReliableMessagingVersion, this.binder.Channel, this.binder.GetInnerSession(), message); bool flag2 = this.settings.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11; try { if (!this.session.ProcessInfo(info, null)) { flag = false; return; } if (!this.ReliableSession.VerifySimplexProtocolElements(info, null)) { flag = false; return; } bool flag3 = false; if (info.AcknowledgementInfo != null) { flag3 = flag2 && info.AcknowledgementInfo.Final; int quotaRemaining = -1; if (this.settings.FlowControlEnabled) { quotaRemaining = info.AcknowledgementInfo.BufferRemaining; } this.connection.ProcessTransferred(info.AcknowledgementInfo.Ranges, quotaRemaining); } if (!flag2) { goto Label_0300; } WsrmFault fault = null; if (info.TerminateSequenceResponseInfo != null) { fault = WsrmUtilities.ValidateTerminateSequenceResponse(this.session, this.terminateRequestor.MessageId, info, this.connection.Last); if (fault == null) { fault = this.ProcessRequestorResponse(this.terminateRequestor, "TerminateSequence", info); } } else if (info.CloseSequenceResponseInfo != null) { fault = WsrmUtilities.ValidateCloseSequenceResponse(this.session, this.closeRequestor.MessageId, info, this.connection.Last); if (fault == null) { fault = this.ProcessRequestorResponse(this.closeRequestor, "CloseSequence", info); } } else { if (info.TerminateSequenceInfo != null) { if (WsrmUtilities.ValidateWsrmRequest(this.session, info.TerminateSequenceInfo, this.binder, null)) { WsrmAcknowledgmentInfo acknowledgementInfo = info.AcknowledgementInfo; fault = WsrmUtilities.ValidateFinalAckExists(this.session, acknowledgementInfo); if ((fault == null) && !this.connection.IsFinalAckConsistent(acknowledgementInfo.Ranges)) { fault = new InvalidAcknowledgementFault(this.session.OutputID, acknowledgementInfo.Ranges); } if (fault != null) { goto Label_02E5; } Message message2 = WsrmUtilities.CreateTerminateResponseMessage(this.settings.MessageVersion, info.TerminateSequenceInfo.MessageId, this.session.OutputID); try { this.OnConnectionSend(message2, base.DefaultSendTimeout, false, true); } finally { message2.Close(); } this.session.OnRemoteFault(new ProtocolException(System.ServiceModel.SR.GetString("UnsupportedTerminateSequenceExceptionString"))); } return; } if (flag3) { if (this.closeRequestor == null) { string exceptionMessage = System.ServiceModel.SR.GetString("UnsupportedCloseExceptionString"); string faultReason = System.ServiceModel.SR.GetString("SequenceTerminatedUnsupportedClose"); fault = SequenceTerminatedFault.CreateProtocolFault(this.session.OutputID, faultReason, exceptionMessage); } else { fault = WsrmUtilities.ValidateFinalAck(this.session, info, this.connection.Last); if (fault == null) { this.closeRequestor.SetInfo(info); } } } else if (info.WsrmHeaderFault != null) { if (!(info.WsrmHeaderFault is UnknownSequenceFault)) { throw Fx.AssertAndThrow("Fault must be UnknownSequence fault."); } if (this.terminateRequestor == null) { throw Fx.AssertAndThrow("In wsrm11, if we start getting UnknownSequence, terminateRequestor cannot be null."); } this.terminateRequestor.SetInfo(info); } } Label_02E5: if (fault != null) { this.session.OnLocalFault(fault.CreateException(), fault, null); return; } Label_0300: this.session.OnRemoteActivity(this.connection.Strategy.QuotaRemaining == 0); } finally { if (flag) { info.Message.Close(); } } }
public async Task CloseAsync(CancellationToken token) { token.ThrowIfCancellationRequested(); //using (DiagnosticUtility.ShouldUseActivity && this.TraceOpenAndClose ? this.CreateCloseActivity() : null) //{ CommunicationState originalState; lock (ThisLock) { originalState = State; if (originalState != CommunicationState.Closed) { State = CommunicationState.Closing; } _closeCalled = true; } switch (originalState) { case CommunicationState.Created: case CommunicationState.Opening: case CommunicationState.Faulted: Abort(); if (originalState == CommunicationState.Faulted) { throw TraceUtility.ThrowHelperError(CreateFaultedException(), Guid.Empty, this); } break; case CommunicationState.Opened: { bool throwing = true; try { //TimeoutHelper actualTimeout = new TimeoutHelper(timeout); OnClosing(); if (!_onClosingCalled) { throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnClosing"), Guid.Empty, this); } await OnCloseAsync(token); OnClosed(); if (!_onClosedCalled) { throw TraceUtility.ThrowHelperError(CreateBaseClassMethodNotCalledException("OnClosed"), Guid.Empty, this); } throwing = false; } finally { if (throwing) { //if (DiagnosticUtility.ShouldTraceWarning) //{ // TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.CommunicationObjectCloseFailed, SR.Format(SR.TraceCodeCommunicationObjectCloseFailed, this.GetCommunicationObjectType().ToString()), this); //} Abort(); } } break; } case CommunicationState.Closing: case CommunicationState.Closed: break; default: throw Fx.AssertAndThrow("CommunicationObject.BeginClose: Unknown CommunicationState"); } //} }
public override void SetInfo(WsrmMessageInfo info) { throw Fx.AssertAndThrow("Not Supported."); }
private void ProcessCreateSequenceResponse(Message response, DateTime start) { CreateSequenceResponseInfo createSequenceResponseInfo = null; using (response) { if (response.IsFault) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(WsrmUtilities.CreateCSFaultException(base.Settings.MessageVersion, base.Settings.ReliableMessagingVersion, response, this.binder.Channel)); } WsrmMessageInfo info2 = WsrmMessageInfo.Get(base.Settings.MessageVersion, base.Settings.ReliableMessagingVersion, this.binder.Channel, this.binder.GetInnerSession(), response, true); if (info2.ParsingException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("UnparsableCSResponse"), info2.ParsingException)); } base.ProcessInfo(info2, null, true); createSequenceResponseInfo = info2.CreateSequenceResponseInfo; string message = null; string faultReason = null; if (createSequenceResponseInfo == null) { message = System.ServiceModel.SR.GetString("InvalidWsrmResponseChannelNotOpened", new object[] { "CreateSequence", info2.Action, WsrmIndex.GetCreateSequenceResponseActionString(base.Settings.ReliableMessagingVersion) }); } else if (!object.Equals(createSequenceResponseInfo.RelatesTo, this.requestor.MessageId)) { message = System.ServiceModel.SR.GetString("WsrmMessageWithWrongRelatesToExceptionString", new object[] { "CreateSequence" }); faultReason = System.ServiceModel.SR.GetString("WsrmMessageWithWrongRelatesToFaultString", new object[] { "CreateSequence" }); } else if ((createSequenceResponseInfo.AcceptAcksTo == null) && (base.InputID != null)) { if (base.Settings.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessagingFebruary2005) { if (base.Settings.ReliableMessagingVersion != ReliableMessagingVersion.WSReliableMessaging11) { throw Fx.AssertAndThrow("Reliable messaging version not supported."); } message = System.ServiceModel.SR.GetString("CSResponseOfferRejected"); faultReason = System.ServiceModel.SR.GetString("CSResponseOfferRejectedReason"); } else { message = System.ServiceModel.SR.GetString("CSResponseWithoutOffer"); faultReason = System.ServiceModel.SR.GetString("CSResponseWithoutOfferReason"); } } else if ((createSequenceResponseInfo.AcceptAcksTo != null) && (base.InputID == null)) { message = System.ServiceModel.SR.GetString("CSResponseWithOffer"); faultReason = System.ServiceModel.SR.GetString("CSResponseWithOfferReason"); } else if ((createSequenceResponseInfo.AcceptAcksTo != null) && (createSequenceResponseInfo.AcceptAcksTo.Uri != this.binder.RemoteAddress.Uri)) { message = System.ServiceModel.SR.GetString("AcksToMustBeSameAsRemoteAddress"); faultReason = System.ServiceModel.SR.GetString("AcksToMustBeSameAsRemoteAddressReason"); } if ((faultReason != null) && (createSequenceResponseInfo != null)) { WsrmFault fault = SequenceTerminatedFault.CreateProtocolFault(createSequenceResponseInfo.Identifier, faultReason, null); base.OnLocalFault(null, fault, null); } if (message != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(message)); } } base.InitiationTime = (TimeSpan)(DateTime.UtcNow - start); base.OutputID = createSequenceResponseInfo.Identifier; this.pollingTimer.Set(this.GetPollingInterval()); base.StartInactivityTimer(); }
public override WsrmMessageInfo GetInfo() { throw Fx.AssertAndThrow("Not Supported."); }
internal virtual IAsyncResult InternalBeginOnSave(IDictionary <XName, object> readWriteValues, IDictionary <XName, object> writeOnlyValues, TimeSpan timeout, AsyncCallback callback, object state) { throw Fx.AssertAndThrow("BeginOnSave should not be called on PersistenceParticipant."); }
public static void UpdateEventDataHeaderAndProperties(AmqpMessage amqpMessage, EventData data) { string str; string str1; DateTime dateTime; long num; string str2; ArraySegment <byte> deliveryTag = amqpMessage.DeliveryTag; Fx.AssertAndThrow(true, "AmqpMessage should always contain delivery tag."); data.DeliveryTag = amqpMessage.DeliveryTag; SectionFlag sections = amqpMessage.Sections; if ((int)(sections & SectionFlag.MessageAnnotations) != 0) { if (amqpMessage.MessageAnnotations.Map.TryGetValue <string>("x-opt-publisher", out str)) { data.Publisher = str; } if (amqpMessage.MessageAnnotations.Map.TryGetValue <string>("x-opt-partition-key", out str1)) { data.PartitionKey = str1; } if (amqpMessage.MessageAnnotations.Map.TryGetValue <DateTime>("x-opt-enqueued-time", out dateTime)) { data.EnqueuedTimeUtc = dateTime; } if (amqpMessage.MessageAnnotations.Map.TryGetValue <long>("x-opt-sequence-number", out num)) { data.SequenceNumber = num; } if (amqpMessage.MessageAnnotations.Map.TryGetValue <string>("x-opt-offset", out str2)) { data.Offset = str2; } } if ((int)(sections & SectionFlag.ApplicationProperties) != 0) { foreach (KeyValuePair <MapKey, object> map in (IEnumerable <KeyValuePair <MapKey, object> >)amqpMessage.ApplicationProperties.Map) { object obj = null; if (!MessageConverter.TryGetNetObjectFromAmqpObject(map.Value, MappingType.ApplicationProperty, out obj)) { continue; } data.Properties[map.Key.ToString()] = obj; } } if ((int)(sections & SectionFlag.Properties) != 0) { foreach (KeyValuePair <string, object> dictionary in amqpMessage.Properties.ToDictionary()) { if (dictionary.Value is MessageId || dictionary.Value is Address || dictionary.Value is AmqpSymbol) { data.SystemProperties.Add(dictionary.Key, dictionary.Value.ToString()); } else { data.SystemProperties.Add(dictionary); } } } }