private int CountInternal() { try { ConnectInternal(); if (MessageQueue != null) { var count = 0; using (var messageEnumerator = MessageQueue.GetMessageEnumerator2()) { while (messageEnumerator.MoveNext()) { ++count; } } return(count); } Logger.Warning("Unable to count messages {%Queue}", ToJson()); return(-1); } catch (Exception exception) { Logger.Warning(exception, "Unable to count messages {%Queue}", ToJson()); return(-1); } }
public IEnumerable<int> GetEnqueuedJobIds(string queue, int @from, int perPage) { var result = new List<int>(); using (var messageQueue = new MessageQueue(String.Format(_pathPattern, queue))) { var current = 0; var end = @from + perPage; var enumerator = messageQueue.GetMessageEnumerator2(); var formatter = new BinaryMessageFormatter(); while (enumerator.MoveNext()) { if (current >= @from && current < end) { var message = enumerator.Current; message.Formatter = formatter; result.Add(int.Parse((string)message.Body)); } if (current >= end) break; current++; } } return result; }
private long MessageCount() { long count = 0; var cursor = m_Queue.GetMessageEnumerator2(); while (cursor.MoveNext()) { count++; } return(count); }
public int Count(MessageQueue queue) { int count = 0; var enumarator = queue.GetMessageEnumerator2(); while (enumarator.MoveNext()) count++; Console.WriteLine("There is {0} ", count + " Message in the queue right now"); return count; }
public IEnumerable<LogEntry> GetLogEntries() { var queueAddress = ConfigurationManager.AppSettings["queueName"]; var messages = new List<Message>(); using (var queue = new MessageQueue(queueAddress)) { var enumerator = queue.GetMessageEnumerator2(); while (enumerator.MoveNext(new TimeSpan(0, 0, 1))) { messages.Add(enumerator.Current); } } return ParseMessages(messages); }
static void Main(string[] args) { MessageQueue myQueue = new MessageQueue(".\\myQueue"); //var mes = myQueue.Receive(new TimeSpan(0, 0, 3)); var timeout = TimeSpan.FromSeconds(1); MessageEnumerator msgs = myQueue.GetMessageEnumerator2(); while (msgs.MoveNext(timeout)) { using (var message = myQueue.ReceiveById(msgs.Current.Id, timeout)) { message.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" }); string m = message.Body.ToString(); Console.WriteLine(m); } } }
public object[] PickMessage(string fromQueue) { using (var queue = new MessageQueue(fromQueue)) { using (MessageEnumerator messageEnumerator2 = queue.GetMessageEnumerator2()) { if (!messageEnumerator2.MoveNext()) return null; Message current = messageEnumerator2.Current; messageEnumerator2.RemoveCurrent(); return DeserializeMessage(current); } } }
public long Count(long limit) { long count = 0; using (var queue = new MessageQueue(_address.InboundFormatName, QueueAccessMode.Receive)) { using (MessageEnumerator enumerator = queue.GetMessageEnumerator2()) { while (enumerator.MoveNext(TimeSpan.Zero)) { if (++count >= limit) break; } } } return count; }
public EnqueuedAndFetchedCountDto GetEnqueuedAndFetchedCount(string queue) { using (var messageQueue = new MessageQueue(String.Format(_pathPattern, queue))) { var count = 0; var enumerator = messageQueue.GetMessageEnumerator2(); while (enumerator.MoveNext()) { count++; } return new EnqueuedAndFetchedCountDto { EnqueuedCount = count }; } }
/// <summary> /// Gets a listing of all timeout messages. /// </summary> /// <returns></returns> public IEnumerable<TimeoutInfo> GetTimeoutMessages(MessageQueue queue) { var fullSubQueueName = queue.Path + ";timeout"; using (var timeoutQueue = new MessageQueue(fullSubQueueName, QueueAccessMode.Receive)) { timeoutQueue.MessageReadPropertyFilter.Extension = true; var enumerator2 = timeoutQueue.GetMessageEnumerator2(); while(enumerator2.MoveNext()) { var message = enumerator2.Current; if(message==null) continue; yield return new TimeoutInfo { Id = message.Id, Time = DateTime.FromBinary(BitConverter.ToInt64(message.Extension, 0)) }; } } }
public int Transfer(string subject, string destination, string expression, bool caseInsensitive, bool removeAfter) { MessageQueueTransaction transaction = null; int ret = 0; Regex matcher = null; if (expression != null) matcher = new Regex("(" + expression + ")", RegexOptions.Compiled | (caseInsensitive ? RegexOptions.IgnoreCase : RegexOptions.None)); var messagePropertyFilter = new MessagePropertyFilter { ArrivedTime = true, Body = true, Id = true, Label = true }; var messageQueue = new MessageQueue(subject); if (!Exists(destination)) { throw new Exception("Can't write to non-existing queue " + destination + ". You can create it with qtouch."); } var destinationQueue = new MessageQueue(destination); if (!destinationQueue.CanWrite) { throw new Exception("Can't write to non-writable queue " + destination); } if (destinationQueue.Transactional) { transaction = new MessageQueueTransaction(); transaction.Begin(); } destinationQueue.Formatter = messageQueue.Formatter; messageQueue.MessageReadPropertyFilter = messagePropertyFilter; var messageEnumerator2 = messageQueue.GetMessageEnumerator2(); while (messageEnumerator2.MoveNext()) { if (messageEnumerator2.Current == null) continue; var message = messageEnumerator2.Current; if (matcher != null) { using (var streamReader = new StreamReader(message.BodyStream)) { string body = streamReader.ReadToEnd(); if (!matcher.IsMatch(body)) continue; Send(message, destinationQueue, transaction); } } else { Send(message, destinationQueue, transaction); } ret++; if (removeAfter) messageEnumerator2.RemoveCurrent(); } if (transaction!=null) transaction.Commit(); return ret; }
public Dictionary<string, int> MessageTypes() { var dict = new Dictionary<string, int>(); using (var queue = new MessageQueue(_address.InboundFormatName, QueueAccessMode.Receive)) { using (MessageEnumerator enumerator = queue.GetMessageEnumerator2()) { while (enumerator.MoveNext(TimeSpan.Zero)) { Message q = enumerator.Current; if (!dict.ContainsKey(q.Label)) dict.Add(q.Label, 0); dict[q.Label]++; } } } return dict; }
public IEnumerable<GrepResult> Grep(string subject, string expression, bool caseInsensitive) { Regex matcher = new Regex("(" + expression + ")", RegexOptions.Compiled | (caseInsensitive ? RegexOptions.IgnoreCase : RegexOptions.None)); var messagePropertyFilter = new MessagePropertyFilter { ArrivedTime = true, Body = true, Id = true, Label = true }; var messageQueue = new MessageQueue(subject); messageQueue.MessageReadPropertyFilter = messagePropertyFilter; var messageEnumerator2 = messageQueue.GetMessageEnumerator2(); while (messageEnumerator2.MoveNext()) { if (messageEnumerator2.Current == null) continue; var message = messageEnumerator2.Current; using (var streamReader = new StreamReader(message.BodyStream)) { string body = streamReader.ReadToEnd(); if (!matcher.IsMatch(body)) continue; yield return new GrepResult {Message = CreateMessageDescriptor(message), Text = matcher.HighlightMatch(body, "<{0}>")}; } } }
public IEnumerable<MessageDescriptor> Tail(string queue) { var messagePropertyFilter = new MessagePropertyFilter { ArrivedTime = true, Body = true, Id = true, Label = true }; var messageQueue = new MessageQueue(queue); messageQueue.MessageReadPropertyFilter = messagePropertyFilter; var messageEnumerator2 = messageQueue.GetMessageEnumerator2(); while(true) { //arbitrary, 1 day. while(messageEnumerator2.MoveNext(TimeSpan.FromDays(1))) { if(messageEnumerator2.Current == null) continue; yield return CreateMessageDescriptor(messageEnumerator2.Current); } } }
public Message[] PeekMessages(MessageQueue activeQueue, bool blnDynamicConnection, eMessageFormat messageFormat, System.Type customType) { Message objMessage; Message[] arrCurrentMessages = new Message[0]; Message[] arrCopyOfMessages = null; MessagePropertyFilter objMessagePropertyFilter = new MessagePropertyFilter(); int intArrayIndex; // Message Formatter SetQueueFormatterAndProperties(activeQueue, messageFormat, customType); // Dynamic Connection whilst gathering messages if (blnDynamicConnection == true) { IEnumerator objMessageEnumerator = activeQueue.GetMessageEnumerator2(); intArrayIndex = 0; while (objMessageEnumerator.MoveNext()) { objMessage = (Message)objMessageEnumerator.Current; if (intArrayIndex > 0) { arrCopyOfMessages = new Message[intArrayIndex]; arrCurrentMessages.CopyTo(arrCopyOfMessages, 0); arrCurrentMessages = arrCopyOfMessages; } arrCurrentMessages[intArrayIndex] = objMessage; intArrayIndex += 1; } } else // Snapshot of messages currently in Queue { arrCurrentMessages = null; try { arrCurrentMessages = activeQueue.GetAllMessages(); } catch (System.Messaging.MessageQueueException excM) { throw excM; } } return arrCurrentMessages; }
public IEnumerable<CatResult> Cat(string subject, bool withExtension) { var messagePropertyFilter = new MessagePropertyFilter { ArrivedTime = true, Body = true, Id = true, Label = true, Extension = withExtension }; var messageQueue = new MessageQueue(subject); messageQueue.MessageReadPropertyFilter = messagePropertyFilter; var messageEnumerator2 = messageQueue.GetMessageEnumerator2(); while (messageEnumerator2.MoveNext()) { if (messageEnumerator2.Current == null) continue; var message = messageEnumerator2.Current; using (var streamReader = new StreamReader(message.BodyStream)) { string body = streamReader.ReadToEnd(); yield return new CatResult { Message = CreateMessageDescriptor(message), Text = body, Extension = withExtension ? message.Extension : null }; } } }
private IEnumerable<LabelIdMapping> PeekMessages(MessageQueue queue) { var counter = 0; using (var msgEnumerator = queue.GetMessageEnumerator2()) { while (msgEnumerator.MoveNext(TimeSpan.FromMilliseconds(10)) && msgEnumerator.Current != null) { counter++; var labelId = new LabelIdMapping { Id = msgEnumerator.Current.Id, Label = msgEnumerator.Current.Label }; Dispatcher.Invoke(new Action<LabelIdMapping>(AddSeatToRoom), labelId); } } return (counter > 0) ? _seats : new List<LabelIdMapping>(); }
/// <summary> /// AsyncReceive /// </summary> private void AsyncReceive() { // lblBeginTime.Text = DateTime.Now.ToString(); var messageQueue = new MessageQueue(_queuePath) { Formatter = new XmlMessageFormatter(new Type[] { typeof(MessageObj) }) }; messageQueue.ReceiveCompleted += ReceiveCompleted; using (var messageEnumerator = messageQueue.GetMessageEnumerator2()) { while (messageEnumerator.MoveNext()) { try { messageQueue.BeginReceive(); } catch (Exception ex) { Debug.WriteLine("Exception:ReceiveMessage Exception:" + ex); } } } // lblEndTime.Text = DateTime.Now.ToString(); MessageBox.Show("Receive Done!"); }
static void Main(string[] args) { Console.WriteLine("Queues on This Machine:"); var queues = MessageQueue.GetPrivateQueuesByMachine(Environment.MachineName); foreach (var queue in queues) { Console.WriteLine(".\\" + queue.QueueName); } // TODO: make below only run when on a domain joined machine //queues = MessageQueue.GetPublicQueuesByMachine(Environment.MachineName); //foreach (var queue in queues) //{ // Console.WriteLine(".\\" + queue.QueueName); //} Console.WriteLine("FormatName:DIRECT=OS:.\\System$;Deadletter"); Console.WriteLine("FormatName:DIRECT=OS:.\\System$;Deadxact"); string queueName = string.Empty; while (string.IsNullOrEmpty(queueName)) { Console.WriteLine("Enter queue name: "); queueName = Console.ReadLine(); if (string.IsNullOrEmpty(queueName) == false) { try { if (!string.Equals(queueName, "FormatName:DIRECT=OS:.\\System$;Deadletter", StringComparison.InvariantCultureIgnoreCase) && !string.Equals(queueName, "FormatName:DIRECT=OS:.\\System$;Deadxact", StringComparison.InvariantCultureIgnoreCase) && MessageQueue.Exists(queueName) == false) { // Valid queue path, but doesn't exist Console.WriteLine("Queue {0} not found.", queueName); queueName = string.Empty; } } catch (Exception) { // Invalid queue path formatting Console.WriteLine("Queue {0} not found.", queueName); queueName = string.Empty; } } } Console.WriteLine("Queue Found!"); var outputFolderDialog = new System.Windows.Forms.FolderBrowserDialog() { Description = "Queue Output Folder", ShowNewFolderButton = true }; var dialogResult = outputFolderDialog.ShowDialog(); while (dialogResult != DialogResult.OK) { dialogResult = outputFolderDialog.ShowDialog(); } var outputFolderPath = outputFolderDialog.SelectedPath; //Setup MSMQ using path from user... MessageQueue q = new MessageQueue(queueName); // Loop over all messages and write them to a file... q.MessageReadPropertyFilter.SetAll(); MessageEnumerator msgEnum = q.GetMessageEnumerator2(); int k = 0; Console.Write("Processing..."); while (msgEnum.MoveNext()) { if (k % 100 == 0) Console.Write("."); Message msg = msgEnum.Current; byte[] data = new byte[msg.BodyStream.Length]; msg.BodyStream.Read(data, 0, (int)msg.BodyStream.Length); string messageContent = ASCIIEncoding.ASCII.GetString(data); string fileName = outputFolderPath + "\\" + msg.ArrivedTime.ToString("yyyy-MM-dd hh.mm.ss tt") + "-" + msg.Id.Replace("\\", "-") + ".xml"; string messageWithHeaders = $"<?xml version=\"1.0\"?><MsmqMessage><Id>{msg.Id}</Id><ArrivedTime>{msg.ArrivedTime}</ArrivedTime><Label>{msg.Label}</Label><Class>{msg.Acknowledgment}</Class><Headers>"; var headers = DeserializeMessageHeaders(msg); foreach (var header in headers) { messageWithHeaders += $"<Header><Name>{header.Key}</Name><Value><![CDATA[{header.Value}]]></Value></Header>"; } messageWithHeaders += $"</Headers><Content><![CDATA[{messageContent}]]></Content></MsmqMessage>"; XDocument formattedXml = XDocument.Parse(messageWithHeaders); System.IO.File.WriteAllText(fileName, formattedXml.ToString()); k++; } Console.Write(Environment.NewLine); Console.WriteLine("All done! Hit any key to exit."); Console.ReadKey(); }
/// <summary> /// 异步接收事务消息队列消息 /// 异步接收BeginReceive()方法无MessageQueueTransaction重载(微软类库的Bug?) /// 这里变通一下:先异步BeginPeek(),然后带事务异步接收Receive(MessageQueueTransaction) /// </summary> private void AsyncReceiveWithTransactional() { var messageQueue = new MessageQueue(_transactionalQueuePath) { Formatter = new XmlMessageFormatter(new Type[] { typeof(MessageObj) }) }; messageQueue.PeekCompleted += new PeekCompletedEventHandler(OnPeekCompleted); //lblBeginTime.Text = DateTime.Now.ToString(); using (var messageEnumerator = messageQueue.GetMessageEnumerator2()) { while (messageEnumerator.MoveNext()) { try { messageQueue.BeginPeek(); } catch (Exception ex) { Debug.WriteLine("Exception:ReceiveMessage Exception:" + ex); } } } //lblEndTime.Text = DateTime.Now.ToString(); MessageBox.Show("Receive Done!"); }
void LoadMessages(Queue queue) { Task.Factory .StartNew(() => { var messageQueue = new MessageQueue(queue.QueuePath); messageQueue.MessageReadPropertyFilter = DefaultFilter(); var list = new List<Message>(); using (var enumerator = messageQueue.GetMessageEnumerator2()) { while (enumerator.MoveNext()) { var message = enumerator.Current; var messageViewModel = GenerateMessage(message, queue.QueuePath); messageViewModel.ResetDirtyFlags(); list.Add(messageViewModel); } } return new { Messages = list }; }) .ContinueWith(t => { if (t.Exception == null) { var result = t.Result; queue.SetMessages(result.Messages); return NotificationEvent.Success("{0} messages loaded from {1}", result.Messages.Count, queue.QueueName); } var details = t.Exception.ToString(); return NotificationEvent.Fail(details, "Could not load messages from {0}: {1}", queue.QueueName, t.Exception); }, Context.UiThread) .ContinueWith(t => Messenger.Default.Send(t.Result), Context.UiThread); }
public int GetMessageCount(MessageQueue messageQueue) { messageQueue.MessageReadPropertyFilter.ClearAll(); var enumerator = messageQueue.GetMessageEnumerator2(); var messageCount = 0; if (!HasAccess(messageQueue)) { return messageCount; } while (enumerator.MoveNext()) { messageCount++; } return messageCount; }
/// <summary> /// Receive /// </summary> private void Receive() { var queue = new MessageQueue(@".\private$\MSMQDemo") { Formatter = new XmlMessageFormatter(new Type[] { typeof(MessageObj) }) }; using (var messageEnumerator = queue.GetMessageEnumerator2()) { var index = 1; while (messageEnumerator.MoveNext()) { Message message = null; try { message = queue.Receive(); } catch (Exception ex) { Debug.WriteLine("Exception:ReceiveMessage Exception:" + ex); } if (message != null) { var messageObj = (MessageObj)message.Body; Debug.WriteLine("Receive Message" + index + " Done!(" + messageObj.MediaTaskId + ")"); } index++; } } MessageBox.Show("Receive Done!"); }
public void ClearMessages(string queuePath, string labelFilter = null) { Guard.QueueExists(queuePath); var queue = new MessageQueue(queuePath) { MessageReadPropertyFilter = { Label = true } }; var messageEnumerator = queue.GetMessageEnumerator2(); try { while (messageEnumerator.MoveNext()) { Message currentMessage = null; try { currentMessage = messageEnumerator.Current; } catch (MessageQueueException e) { //TODO: Use ILog Console.WriteLine(e); } if (currentMessage == null) continue; if (labelFilter != null && currentMessage.Label != labelFilter) continue; queue.ReceiveById(currentMessage.Id); } } finally { messageEnumerator.Close(); } queue.Close(); }
public int ReadQueueSize(string refNum) { try { if (MessageQueue.Exists(@".\Private$\ScrapeSessionsQueue")) { MessageQueue mQ = new MessageQueue(@".\Private$\ScrapeSessionsQueue", false, true); int messageCount = 0; using (MessageEnumerator messageEnumerator = mQ.GetMessageEnumerator2()) { while (messageEnumerator.MoveNext()) { messageCount++; } } return messageCount; } return 0; } catch (Exception ex) { log.LogMessage(Enumeration.LoggingPriority.High, refNum, ex); return 0; } }
public IEnumerable<Message> GetMessages(MessageQueue queue, string labelFilter = null, bool includeBody = false, bool includeExtension = false) { queue.MessageReadPropertyFilter.ClearAll(); queue.MessageReadPropertyFilter.Id = true; queue.MessageReadPropertyFilter.Label = true; queue.MessageReadPropertyFilter.SentTime = true; queue.MessageReadPropertyFilter.Body = includeBody; queue.MessageReadPropertyFilter.Extension = includeExtension; var result = new List<Message>(); if (!HasAccess(queue)) { return result; } var messageEnumerator = queue.GetMessageEnumerator2(); try { while (messageEnumerator.MoveNext()) { Message currentMessage = null; try { currentMessage = messageEnumerator.Current; } catch (MessageQueueException e) { //TODO: Use ILog Console.WriteLine(e); } if (currentMessage == null) continue; if (labelFilter == null || currentMessage.Label == labelFilter) result.Add(currentMessage); } } finally { messageEnumerator.Close(); } queue.Close(); return result; }
private void TestIfQueueIsValid() { try { using (var q = new MessageQueue(Path, QueueAccessMode.Peek)) { q.GetMessageEnumerator2().Dispose(); _useJournal = !Path.EndsWith(";journal") && q.UseJournalQueue; } Invalid = false; } catch (Exception ex) { Invalid = true; InvalidMessage = ex.Message; } }