// TryReceive public bool TryReceive(TimeSpan timeout, out Message message) { message = null; if (DoneReceivingInCurrentState()) { return(true); } using (MsmqDiagnostics.BoundReceiveOperation(this.receiver)) { MsmqInputMessage msmqMessage = this.receiver.TakeMessage(); try { MsmqMessageProperty property; bool retval = this.receiver.TryReceive( msmqMessage, timeout, this.ReceiveParameters.ExactlyOnce ? MsmqTransactionMode.CurrentOrNone : MsmqTransactionMode.None, out property); if (retval) { if (null != property) { message = DecodeMsmqMessage(msmqMessage, property); message.Properties[MsmqMessageProperty.Name] = property; if (this.receiveParameters.ReceiveContextSettings.Enabled) { message.Properties[MsmqReceiveContext.Name] = this.receiveContextManager.CreateMsmqReceiveContext(msmqMessage.LookupId.Value); } MsmqDiagnostics.DatagramReceived(msmqMessage.MessageId, message); this.listener.RaiseMessageReceived(); } else if (CommunicationState.Opened == this.State) { this.listener.FaultListener(); this.Fault(); } } return(retval); } catch (MsmqException ex) { if (ex.FaultReceiver) { this.listener.FaultListener(); this.Fault(); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex.Normalized); } finally { this.receiver.ReturnMessage(msmqMessage); } } }
internal static Message DecodeIntegrationDatagram(MsmqIntegrationChannelListener listener, MsmqReceiveHelper receiver, MsmqIntegrationInputMessage msmqMessage, MsmqMessageProperty messageProperty) { Message message2; using (MsmqDiagnostics.BoundReceiveBytesOperation()) { Message message = Message.CreateMessage(MessageVersion.None, (string)null); bool flag = true; try { SecurityMessageProperty property = listener.ValidateSecurity(msmqMessage); if (property != null) { message.Properties.Security = property; } MsmqIntegrationMessageProperty property2 = new MsmqIntegrationMessageProperty(); msmqMessage.SetMessageProperties(property2); int length = msmqMessage.BodyLength.Value; if (length > listener.MaxReceivedMessageSize) { receiver.FinalDisposition(messageProperty); throw listener.NormalizePoisonException(messageProperty.LookupId, MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(listener.MaxReceivedMessageSize)); } byte[] bufferCopy = msmqMessage.Body.GetBufferCopy(length); MemoryStream bodyStream = new MemoryStream(bufferCopy, 0, bufferCopy.Length, false); object obj2 = null; using (MsmqDiagnostics.BoundDecodeOperation()) { try { obj2 = DeserializeForIntegration(listener, bodyStream, property2, messageProperty.LookupId); } catch (SerializationException exception) { receiver.FinalDisposition(messageProperty); throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(System.ServiceModel.SR.GetString("MsmqDeserializationError"), exception)); } property2.Body = obj2; message.Properties["MsmqIntegrationMessageProperty"] = property2; bodyStream.Seek(0L, SeekOrigin.Begin); message.Headers.To = listener.Uri; flag = false; MsmqDiagnostics.TransferFromTransport(message); } message2 = message; } finally { if (flag) { message.Close(); } } } return(message2); }
static Msmq() { MsmqQueue.GetMsmqInformation(ref Msmq.version, ref activeDirectoryEnabled); MsmqDiagnostics.MsmqDetected(Msmq.version); System.Version version = Environment.OSVersion.Version; if ((version.Major == 5) && (version.Minor == 1)) { xpSendLock = new object(); } }
static Msmq() { MsmqQueue.GetMsmqInformation(ref version, ref activeDirectoryEnabled); MsmqDiagnostics.MsmqDetected(version); Version osVersion = System.Environment.OSVersion.Version; if (osVersion.Major == 5 && osVersion.Minor == 1) { xpSendLock = new object(); } }
public virtual void CloseQueue() { if (this.handle != null) { this.CloseQueue(this.handle); this.handle = null; this.isBoundToCompletionPort = false; this.isAsyncEnabled = false; MsmqDiagnostics.QueueClosed(this.formatName); } }
private void OnCloseCore(bool isAborting, TimeSpan timeout) { if (!isAborting && (this.buffers.Count > 1)) { lock (base.ThisLock) { this.VerifyTransaction(); this.buffers.Add(this.EncodeEndMarker()); } int bodySize = this.CalcSessionGramSize(); using (MsmqOutputMessage <IOutputSessionChannel> message = new MsmqOutputMessage <IOutputSessionChannel>(this.Factory, bodySize, this.RemoteAddress)) { message.ApplyCertificateIfNeeded(this.certificateTokenProvider, this.factory.MsmqTransportSecurity.MsmqAuthenticationMode, timeout); message.Body.EnsureBufferLength(bodySize); message.Body.BufferLength = bodySize; this.CopySessionGramToBuffer(message.Body.Buffer); bool lockHeld = false; try { Msmq.EnterXPSendLock(out lockHeld, this.factory.MsmqTransportSecurity.MsmqProtectionLevel); this.msmqQueue.Send(message, MsmqTransactionMode.CurrentOrSingle); MsmqDiagnostics.SessiongramSent(this.Session.Id, message.MessageId, this.buffers.Count); } catch (MsmqException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception.Normalized); } finally { if (lockHeld) { Msmq.LeaveXPSendLock(); } this.ReturnSessionGramBuffers(); } } } if (this.msmqQueue != null) { this.msmqQueue.Dispose(); } this.msmqQueue = null; if (this.certificateTokenProvider != null) { if (isAborting) { this.certificateTokenProvider.Abort(); } else { this.certificateTokenProvider.Close(timeout); } } }
private void OnReceiveContextFaulted(object sender, EventArgs e) { try { MsmqReceiveContext receiveContext = (MsmqReceiveContext)sender; this.UnlockMessage(receiveContext, TimeSpan.Zero); } catch (MsmqException exception) { MsmqDiagnostics.ExpectedException(exception); } }
private bool CheckServiceExists(string serviceFile) { try { return(ServiceHostingEnvironment.IsConfigurationBasedService(serviceFile) || HostingEnvironmentWrapper.ServiceFileExists(serviceFile)); } catch (ArgumentException exception) { MsmqDiagnostics.ExpectedException(exception); return(false); } }
protected override void OnSend(Message message, TimeSpan timeout) { ArraySegment <byte> segment = this.factory.MessageEncoderFactory.Encoder.WriteMessage(message, 0x7fffffff, this.factory.BufferManager, this.preamble.Length); Buffer.BlockCopy(this.preamble, 0, segment.Array, segment.Offset - this.preamble.Length, this.preamble.Length); byte[] array = segment.Array; int srcOffset = segment.Offset - this.preamble.Length; int bodySize = segment.Count + this.preamble.Length; MsmqOutputMessage <IOutputChannel> message2 = this.outputMessages.Take(); if (message2 == null) { message2 = new MsmqOutputMessage <IOutputChannel>(this.factory, bodySize, this.RemoteAddress); MsmqDiagnostics.PoolFull(this.factory.MaxPoolSize); } try { message2.ApplyCertificateIfNeeded(this.certificateTokenProvider, this.factory.MsmqTransportSecurity.MsmqAuthenticationMode, timeout); message2.Body.EnsureBufferLength(bodySize); message2.Body.BufferLength = bodySize; Buffer.BlockCopy(array, srcOffset, message2.Body.Buffer, 0, bodySize); this.factory.BufferManager.ReturnBuffer(array); bool lockHeld = false; try { Msmq.EnterXPSendLock(out lockHeld, this.factory.MsmqTransportSecurity.MsmqProtectionLevel); this.msmqQueue.Send(message2, this.transactionMode); MsmqDiagnostics.DatagramSent(message2.MessageId, message); } catch (MsmqException exception) { if (exception.FaultSender) { base.Fault(); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception.Normalized); } finally { if (lockHeld) { Msmq.LeaveXPSendLock(); } } } finally { if (!this.outputMessages.Return(message2)) { message2.Dispose(); } } }
internal virtual MsmqQueueHandle OpenQueue() { MsmqQueueHandle handle; int error = UnsafeNativeMethods.MQOpenQueue(this.formatName, this.accessMode, this.shareMode, out handle); if (error != 0) { Utility.CloseInvalidOutSafeHandle(handle); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(System.ServiceModel.SR.GetString("MsmqOpenError", new object[] { MsmqError.GetErrorString(error) }), error)); } MsmqDiagnostics.QueueOpened(this.formatName); return(handle); }
void OnReceiveContextFaulted(object sender, EventArgs e) { try { MsmqReceiveContext receiveContext = (MsmqReceiveContext)sender; UnlockMessage(receiveContext, TimeSpan.Zero); } catch (MsmqException ex) { // ReceiveContext is already faulted and best effort was made to cleanup the lock queue. MsmqDiagnostics.ExpectedException(ex); } }
public bool AnotherTryNeeded() { if (--this.attemptsLeft > 0) { if (this.attemptsLeft == 0x31) { MsmqDiagnostics.MessageLockedUnderTheTransaction(this.lookupId); } Thread.Sleep(TimeSpan.FromMilliseconds(100.0)); return(true); } MsmqDiagnostics.MoveOrDeleteAttemptFailed(this.lookupId); return(false); }
bool CheckServiceExists(string serviceFile) { try { return((ServiceHostingEnvironment.IsConfigurationBasedService(serviceFile) || HostingEnvironmentWrapper.ServiceFileExists(serviceFile)) && AspNetEnvironment.Current.IsWithinApp(VirtualPathUtility.ToAbsolute(serviceFile))); } catch (ArgumentException ex) { MsmqDiagnostics.ExpectedException(ex); return(false); } }
public override MsmqQueue.ReceiveResult TryReceive(NativeMsmqMessage message, TimeSpan timeout, MsmqTransactionMode transactionMode) { MsmqQueue.MoveReceiveResult result3; TimeoutHelper helper = new TimeoutHelper(timeout); bool flag = false; long lookupId = 0L; while (!flag) { using (MsmqMessageLookupId id = new MsmqMessageLookupId()) { MsmqQueue.ReceiveResult result = base.TryPeek(id, helper.RemainingTime()); if (result != MsmqQueue.ReceiveResult.MessageReceived) { return(result); } lookupId = id.lookupId.Value; } try { if (base.TryMoveMessage(lookupId, this.lockQueueForMove, MsmqTransactionMode.None) == MsmqQueue.MoveReceiveResult.Succeeded) { flag = true; } continue; } catch (MsmqException exception) { MsmqDiagnostics.ExpectedException(exception); continue; } } try { result3 = this.lockQueueForReceive.TryReceiveByLookupId(lookupId, message, MsmqTransactionMode.None, 0x40000010); } catch (MsmqException exception2) { this.UnlockMessage(lookupId, TimeSpan.Zero); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception2); } if (result3 == MsmqQueue.MoveReceiveResult.Succeeded) { return(MsmqQueue.ReceiveResult.MessageReceived); } this.UnlockMessage(lookupId, TimeSpan.Zero); return(MsmqQueue.ReceiveResult.OperationCancelled); }
private void StartService(object state) { try { string virtualPath = (string)state; ServiceHostingEnvironment.EnsureServiceAvailable(virtualPath); } catch (ServiceActivationException exception) { MsmqDiagnostics.ExpectedException(exception); } catch (EndpointNotFoundException exception2) { MsmqDiagnostics.ExpectedException(exception2); } }
private static System.ServiceModel.Channels.DeliveryFailure?TryGetDeliveryFailure(string messageId, int acknowledgment) { if ((0x8000 & acknowledgment) == 0) { return(null); } int num2 = 0x4000 & acknowledgment; int num3 = -49153 & acknowledgment; if ((((num2 == 0) && (num3 >= 0)) && (num3 <= 10)) || (((num2 != 0) && (num3 >= 0)) && (num3 <= 2))) { return(new System.ServiceModel.Channels.DeliveryFailure?((System.ServiceModel.Channels.DeliveryFailure)acknowledgment)); } MsmqDiagnostics.UnexpectedAcknowledgment(messageId, acknowledgment); return(0); }
public MoveReceiveResult TryMoveMessage(long lookupId, MsmqQueue destinationQueue, MsmqTransactionMode transactionMode) { MsmqQueueHandle sourceQueueHandle = GetHandle(); MsmqQueueHandle destinationQueueHandle = destinationQueue.GetHandle(); int error; try { if (RequiresDtcTransaction(transactionMode)) { error = TryMoveMessageDtcTransacted(lookupId, sourceQueueHandle, destinationQueueHandle, transactionMode); } else { error = UnsafeNativeMethods.MQMoveMessage(sourceQueueHandle, destinationQueueHandle, lookupId, (IntPtr)GetTransactionConstant(transactionMode)); } } catch (ObjectDisposedException ex) { MsmqDiagnostics.ExpectedException(ex); return(MoveReceiveResult.Succeeded); } if (error != 0) { if (error == UnsafeNativeMethods.MQ_ERROR_MESSAGE_NOT_FOUND) { return(MoveReceiveResult.MessageNotFound); } else if (error == UnsafeNativeMethods.MQ_ERROR_MESSAGE_LOCKED_UNDER_TRANSACTION) { return(MoveReceiveResult.MessageLockedUnderTransaction); } else if (IsErrorDueToStaleHandle(error)) { HandleIsStale(sourceQueueHandle); destinationQueue.HandleIsStale(destinationQueueHandle); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqSendError, MsmqError.GetErrorString(error)), error)); } return(MoveReceiveResult.Succeeded); }
private unsafe void StartReceive(bool synchronously) { bool flag; int num; try { this.handle = this.msmqQueue.GetHandleForAsync(out flag); } catch (MsmqException exception) { this.OnCompletion(exception.ErrorCode, synchronously); return; } NativeOverlapped *nativeOverlapped = this.nativeOverlapped; IntPtr nativePropertiesPointer = this.message.Pin(); this.nativeOverlapped = new Overlapped(0, 0, IntPtr.Zero, this).UnsafePack(onPortedCompletion, this.message.GetBuffersForAsync()); try { if (flag) { num = this.msmqQueue.ReceiveCoreAsync(this.handle, nativePropertiesPointer, this.timeoutHelper.RemainingTime(), this.action, this.nativeOverlapped, null); } else { if (onNonPortedCompletion == null) { onNonPortedCompletion = new UnsafeNativeMethods.MQReceiveCallback(MsmqQueue.TryReceiveAsyncResult.OnNonPortedCompletion); } num = this.msmqQueue.ReceiveCoreAsync(this.handle, nativePropertiesPointer, this.timeoutHelper.RemainingTime(), this.action, this.nativeOverlapped, onNonPortedCompletion); } } catch (ObjectDisposedException exception2) { MsmqDiagnostics.ExpectedException(exception2); num = -1072824312; } if ((num != 0) && (num != 0x400e0006)) { Overlapped.Free(this.nativeOverlapped); this.nativeOverlapped = null; GC.SuppressFinalize(this); this.OnCompletion(num, synchronously); } }
private void RollbackTransaction(Exception exception) { try { if (this.associatedTx.TransactionInformation.Status == TransactionStatus.Active) { this.associatedTx.Rollback(exception); } } catch (TransactionAbortedException exception2) { MsmqDiagnostics.ExpectedException(exception2); } catch (ObjectDisposedException exception3) { MsmqDiagnostics.ExpectedException(exception3); } }
internal static void TryAbortTransactionCurrent() { if (null != Transaction.Current) { try { Transaction.Current.Rollback(); } catch (TransactionAbortedException ex) { MsmqDiagnostics.ExpectedException(ex); } catch (ObjectDisposedException ex) { MsmqDiagnostics.ExpectedException(ex); } } }
void OnTimer(object state) { lock (this) { if (!this.disposed) { try { this.retryQueueForPeek.TryMoveMessage(this.retryQueueMessage.LookupId.Value, this.mainQueueForMove, MsmqTransactionMode.Single); } catch (MsmqException ex) { MsmqDiagnostics.ExpectedException(ex); } this.retryQueueForPeek.BeginPeek(this.retryQueueMessage, TimeSpan.MaxValue, onPeekCompleted, this); } } }
public MoveReceiveResult TryReceiveByLookupId(long lookupId, NativeMsmqMessage message, MsmqTransactionMode transactionMode, int action) { MsmqQueueHandle handle = GetHandle(); int error = 0; while (true) { try { error = ReceiveByLookupIdCore(handle, lookupId, message, transactionMode, action); } catch (ObjectDisposedException ex) { // ---- with Close MsmqDiagnostics.ExpectedException(ex); return(MoveReceiveResult.Succeeded); } if (0 == error) { return(MoveReceiveResult.Succeeded); } if (IsReceiveErrorDueToInsufficientBuffer(error)) { message.GrowBuffers(); continue; } else if (UnsafeNativeMethods.MQ_ERROR_MESSAGE_NOT_FOUND == error) { return(MoveReceiveResult.MessageNotFound); } else if (UnsafeNativeMethods.MQ_ERROR_MESSAGE_LOCKED_UNDER_TRANSACTION == error) { return(MoveReceiveResult.MessageLockedUnderTransaction); } else if (IsErrorDueToStaleHandle(error)) { HandleIsStale(handle); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(SR.GetString(SR.MsmqReceiveError, MsmqError.GetErrorString(error)), error)); } }
void CleanupExpiredLocks(object state) { lock (this.internalStateLock) { if (this.disposed) { return; } if ((this.messageExpiryMap.Count < 1)) { this.messageExpiryTimer.Set(this.messageTimeoutInterval); return; } List <MsmqReceiveContext> expiredLockList = new List <MsmqReceiveContext>(); try { foreach (KeyValuePair <long, MsmqReceiveContext> msgEntry in this.messageExpiryMap) { if (DateTime.UtcNow > msgEntry.Value.ExpiryTime) { expiredLockList.Add(msgEntry.Value); } } try { foreach (MsmqReceiveContext entry in expiredLockList) { entry.MarkContextExpired(); } } catch (MsmqException ex) { MsmqDiagnostics.ExpectedException(ex); } } finally { this.messageExpiryTimer.Set(this.messageTimeoutInterval); } } }
static Message DecodeSessiongramMessage( MsmqInputSessionChannelListener listener, MsmqInputSessionChannel channel, MessageEncoder encoder, MsmqMessageProperty messageProperty, byte[] buffer, int offset, int size) { if (size > listener.MaxReceivedMessageSize) { channel.FaultChannel(); listener.MsmqReceiveHelper.FinalDisposition(messageProperty); throw listener.NormalizePoisonException(messageProperty.LookupId, MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(listener.MaxReceivedMessageSize)); } // Fix for CSDMain if ((size + offset) > buffer.Length) { listener.MsmqReceiveHelper.FinalDisposition(messageProperty); throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqBadFrame))); } byte[] envelopeBuffer = listener.BufferManager.TakeBuffer(size); Buffer.BlockCopy(buffer, offset, envelopeBuffer, 0, size); try { Message message = null; using (MsmqDiagnostics.BoundDecodeOperation()) { message = encoder.ReadMessage(new ArraySegment <byte>(envelopeBuffer, 0, size), listener.BufferManager); MsmqDiagnostics.TransferFromTransport(message); } return(message); } catch (XmlException e) { channel.FaultChannel(); listener.MsmqReceiveHelper.FinalDisposition(messageProperty); throw listener.NormalizePoisonException(messageProperty.LookupId, new ProtocolException(SR.GetString(SR.MsmqBadXml), e)); } }
protected override Uri PostVerify(Uri uri) { if (0 == String.Compare(uri.Host, "localhost", StringComparison.OrdinalIgnoreCase)) { return(uri); } try { if (0 == String.Compare(DnsCache.MachineName, DnsCache.Resolve(uri).HostName, StringComparison.OrdinalIgnoreCase)) { return(new UriBuilder(Scheme, "localhost", -1, uri.PathAndQuery).Uri); } } catch (EndpointNotFoundException ex) { MsmqDiagnostics.ExpectedException(ex); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MsmqDLQNotLocal), "uri")); }
public Uri[] GetBaseAddresses(string virtualPath) { foreach (MsmqBindingMonitor monitor in this.bindingMonitors) { monitor.WaitForFirstRoundComplete(); } string str = VirtualPathUtility.ToAbsolute(virtualPath, HostingEnvironment.ApplicationVirtualPath); List <Uri> list = new List <Uri>(this.hosts.Length); string processedVirtualPath = str.Substring(1); foreach (string str3 in this.hosts) { bool isPrivate = this.filter.IsPrivateMatch(processedVirtualPath); Uri item = this.addressing.CreateUri(str3, processedVirtualPath, isPrivate); list.Add(item); MsmqDiagnostics.FoundBaseAddress(item, str); } return(list.ToArray()); }
private void CleanupExpiredLocks(object state) { lock (this.internalStateLock) { if (!this.disposed) { if (this.messageExpiryMap.Count < 1) { this.messageExpiryTimer.Set(this.messageTimeoutInterval); } else { List <MsmqReceiveContext> list = new List <MsmqReceiveContext>(); try { foreach (KeyValuePair <long, MsmqReceiveContext> pair in this.messageExpiryMap) { if (DateTime.UtcNow > pair.Value.ExpiryTime) { list.Add(pair.Value); } } try { foreach (MsmqReceiveContext context in list) { context.MarkContextExpired(); } } catch (MsmqException exception) { MsmqDiagnostics.ExpectedException(exception); } } finally { this.messageExpiryTimer.Set(this.messageTimeoutInterval); } } } } }
public override object MatchFound(string host, string name, bool isPrivate) { string virtualPath = this.CreateRelativeVirtualPath(host, name, isPrivate); string serviceFile = ServiceHostingEnvironment.NormalizeVirtualPath(virtualPath); lock (this) { if (isPrivate) { string str3 = this.CreateBaseQueue(serviceFile); this.privateMatches[str3] = str3; } } if (this.CheckServiceExists(serviceFile)) { MsmqDiagnostics.StartingService(host, name, isPrivate, virtualPath); ActionItem.Schedule(new Action <object>(this.StartService), virtualPath); } return(null); }
void StartService(object state) { try { string processedVirtualPath = (string)state; ServiceHostingEnvironment.EnsureServiceAvailable(processedVirtualPath); } catch (ServiceActivationException e) { // Non-fatal exceptions from the user code are wrapped in ServiceActivationException // The best we can do is to trace them MsmqDiagnostics.ExpectedException(e); } catch (EndpointNotFoundException e) { // This means that the server disappeared between the time we // saw the service, and the time we tried to start it. // That's okay. MsmqDiagnostics.ExpectedException(e); } }
public MoveReceiveResult TryMoveMessage(long lookupId, MsmqQueue destinationQueue, MsmqTransactionMode transactionMode) { int num; MsmqQueueHandle sourceQueueHandle = this.GetHandle(); MsmqQueueHandle handle = destinationQueue.GetHandle(); try { if (this.RequiresDtcTransaction(transactionMode)) { num = this.TryMoveMessageDtcTransacted(lookupId, sourceQueueHandle, handle, transactionMode); } else { num = UnsafeNativeMethods.MQMoveMessage(sourceQueueHandle, handle, lookupId, (IntPtr)this.GetTransactionConstant(transactionMode)); } } catch (ObjectDisposedException exception) { MsmqDiagnostics.ExpectedException(exception); return(MoveReceiveResult.Succeeded); } switch (num) { case 0: return(MoveReceiveResult.Succeeded); case -1072824184: return(MoveReceiveResult.MessageNotFound); case -1072824164: return(MoveReceiveResult.MessageLockedUnderTransaction); } if (IsErrorDueToStaleHandle(num)) { this.HandleIsStale(sourceQueueHandle); destinationQueue.HandleIsStale(handle); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MsmqException(System.ServiceModel.SR.GetString("MsmqSendError", new object[] { MsmqError.GetErrorString(num) }), num)); }