public void Send(string Msg) { string QueuePath = ".\\private$\\SLS_Allcai_Task_Alipay_" + MessageType; if (!MessageQueue.Exists(QueuePath)) { return; } MessageQueue mq = null; try { mq = new MessageQueue(QueuePath); } catch { return; } if (mq == null) { return; } System.Messaging.Message m = new System.Messaging.Message(); m.Body = Msg; m.Formatter = new System.Messaging.BinaryMessageFormatter(); mq.Send(m); }
//#TODO Improve code public void mq_ReceiveCompletedNotifyQ(object sender, ReceiveCompletedEventArgs e) { //queue that have received a message MessageQueue cmq = (MessageQueue)sender; try { //a message we have received (it is already removed from queue) System.Messaging.Message msg = cmq.EndReceive(e.AsyncResult); var messageLabel = msg.Label; foreach (var client in clients) { if (client.ComputerName.Equals(messageLabel)) { DataGridColumn column = null; column = dgrClients.Columns[2]; //Create a temp LabClient list to send the result List <LabClient> tLabClients = new List <LabClient>(); tLabClients.Add(client); SetFeatureActivity(Feature.NOTIFY, tLabClients, true); } } } catch { } //refresh queue just in case any changes occurred (optional) cmq.Refresh(); //tell MessageQueue to receive next message when it arrives cmq.BeginReceive(); }
public void MoveFromSubQueue(Type messageType, Message message) { using (var pendingQueue = GetQueue(messageType)) { pendingQueue.MoveFromSubQueue(message); } }
private void QReceiveCompleted(object sender, ReceiveCompletedEventArgs e) { if (sender != null) { lock (SyncRoot) { MessageQueue _msgQ = sender as MessageQueue; try { using (System.Messaging.Message _message = _msgQ.EndReceive(e.AsyncResult)) { // do skip messages } if (QSubscriberEvents != null) { QSubscriberEvents(this, e); } } catch (MessageQueueException) { //throw new Exception(ex.MessageQueueErrorCode.ToString(), ex); } catch (Exception) { } finally { _msgQ.BeginReceive(); } } } }
private void OnReceiveCompleted(object sender, ReceiveCompletedEventArgs e) { System.Messaging.Message msg = _queue.EndReceive(e.AsyncResult); StartListening(); Contact myContact = new Contact(); Object o = new Object(); System.Type[] arrTypes = new System.Type[2]; arrTypes[0] = myContact.GetType(); arrTypes[1] = o.GetType(); msg.Formatter = new XmlMessageFormatter(arrTypes); myContact = ((Contact)msg.Body); StringBuilder sb = new StringBuilder(); sb.Append(myContact.FirstName + ";"); sb.Append(myContact.LastName + ";"); sb.Append(myContact.Id.ToString() + ";"); sb.Append(myContact.Guid.ToString() + ";"); Console.WriteLine(sb); FireRecieveEvent(msg.Body); }
/// <summary> /// Convert the given object to a Message. /// </summary> /// <param name="obj">The object to send.</param> /// <returns>Message to send</returns> public Message ToMessage(object obj) { Message m = new Message(); m.Body = obj; m.Formatter = messageFormatter; return m; }
/// <summary> /// 3.连接消息队列并从队列中接收消息 /// </summary> public void ReceiveMessage() { MessageQueue myQueue = new MessageQueue(Path); myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); try { //从队列中接收消息 System.Messaging.Message myMessage = myQueue.Receive();// myQueue.Peek();--接收后不消息从队列中移除 string context = myMessage.Body.ToString(); Console.WriteLine("消息内容:" + context); Console.ReadLine(); } catch (MessageQueueException e) { Console.WriteLine(e.Message); } catch (InvalidCastException e) { Console.WriteLine(e.Message); } }
/// <summary> /// When implemented in a class, reads the contents from the given message and creates an object that contains data from the message. /// </summary> /// <returns> /// The deserialized message. /// </returns> /// <param name="message">The <see cref="T:System.Messaging.Message"/> to deserialize. </param> public object Read(Message message) { using (var streamReader = new StreamReader(message.BodyStream, _encoding)) { return streamReader.ReadToEnd(); } }
public void QueueMessagingTest() { //Задаем путь тестовой очереди string testQueuePath = @".\QueueAccessTest"; //Пытаемся создать новую очередь if (!MessageQueue.Exists(testQueuePath)) MessageQueue.Create(testQueuePath); System.Threading.Thread.Sleep(20000); // Время, необходимое для создания очереди //Тест пройден, если очередь успешно создалась Assert.IsTrue(MessageQueue.Exists(testQueuePath)); //Создаем представителя нашего сервиса по обработке ошибок Service.ExeptionService ExсeptionService serviceTest = new ExсeptionService(); //Создаем новое сообщение с наивысшим приоритетом Message mes = new Message { Label = "QueueMessagingTest_Message_Label", Body = "QueueMessagingTest_Message_Body", Priority = MessagePriority.Highest }; //Посылаем сообщение в очередь testQueuePath serviceTest.SendToQueue(mes, testQueuePath); //Забираем сообщение из очереди и если оно совпадает с тем, которое мы отправляли, то тест пройден Assert.AreEqual(new MessageQueue(testQueuePath).Receive().Label, mes.Label); //Пытаемся удалить ранее созданную очередь MessageQueue.Delete(testQueuePath); System.Threading.Thread.Sleep(5000); // Время, необходимое для удаления очереди //Если очереди больше нет, то тест пройден Assert.IsTrue(!MessageQueue.Exists(testQueuePath)); }
public void Send(Object message) { // Open the queue. using (var queue = new MessageQueue(_queueName.GetQueueFormatName())) { // Set the formatter to JSON. queue.Formatter = new MsmqMessageFormatter(); // Since we're using a transactional queue, make a transaction. using (MessageQueueTransaction mqt = new MessageQueueTransaction()) { mqt.Begin(); // Create a simple text message. Message myMessage = new Message(message, new MsmqMessageFormatter()); myMessage.Label = message.GetType().FullName; myMessage.ResponseQueue = new MessageQueue(_queueName.GetQueueFormatName()); // Send the message. queue.Send(myMessage, mqt); mqt.Commit(); } } }
/// <summary> /// Moves the <paramref name="message"/> to discarded queue. /// </summary> /// <param name="queue">The queue.</param> /// <param name="message">The message.</param> public void MoveToDiscardedQueue(MessageQueue queue, Message message) { using (var destinationQueue = new MessageQueue(GetDiscardedQueuePath(),QueueAccessMode.Send)) { destinationQueue.Send(queue.ReceiveByLookupId(message.LookupId), destinationQueue.GetTransactionType()); } }
/// <summary> /// 生成带有级别的Message /// </summary> /// <param name="p_strPriority"></param> /// <returns></returns> public Message GetPriority(string p_strPriority) { Message queueMessage = new System.Messaging.Message(); switch (p_strPriority) { case "AboveNormal": queueMessage.Priority = MessagePriority.AboveNormal; break; case "High": queueMessage.Priority = MessagePriority.High; break; case "Highest": queueMessage.Priority = MessagePriority.Highest; break; case "Low": queueMessage.Priority = MessagePriority.Low; break; case "Lowest": queueMessage.Priority = MessagePriority.Lowest; break; case "Normal": queueMessage.Priority = MessagePriority.Normal; break; case "VeryHigh": queueMessage.Priority = MessagePriority.VeryHigh; break; case "VeryLow": queueMessage.Priority = MessagePriority.VeryLow; break; default: queueMessage.Priority = MessagePriority.Normal; break; } return queueMessage; }
internal static Message GetMSMQMessage(this PipeMessageEnvelope pipeMessage) { Message MSMQMessage = new Message(); if (pipeMessage.CorrelationId != null) { MSMQMessage.CorrelationId = pipeMessage.CorrelationId; } if (pipeMessage.Label != null) { MSMQMessage.Label = pipeMessage.Label; } MSMQMessage.Body = pipeMessage.Body; MessageFlags appSpecific = MessageFlags.None; if (pipeMessage.IsPostback) { appSpecific |= MessageFlags.Postback; } MSMQMessage.AppSpecific = (int)appSpecific; // Debugging //long messageSize = Utils.BinSizeOf(pipeMessage.Body); //if (messageSize > 100000) //{ // Tracer.Trace( // "Message label = {0}, Message size = {1}", pipeMessage.Label, Utils.BinSizeOf(pipeMessage.Body)); //} return MSMQMessage; }
public void SendWithPathNotSet () { MessageQueue q = new MessageQueue (); Message m = new Message ("foobar", new BinaryMessageFormatter ()); q.Send (m); }
private void QueueWorker() { string queuePath = ConfigurationManager.AppSettings["qPath"]; MessageQueue queue = null; if (!MessageQueue.Exists(queuePath)) { queue = MessageQueue.Create(queuePath); } else { queue = new MessageQueue(queuePath); } queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) }); while (true) { System.Messaging.Message message = queue.Receive(); if (message.Label == "Key") { RecievingHandler.SendEncryptedSymmetricalKey(message.Body.ToString()); } else if (message.Label == "Data") { string input = Encryptor.DecryptSymmetrical(message.Body.ToString(), ConfigurationManager.AppSettings["tdesKey"]); int result = RecievingHandler.RecieveData(input); tbInput.Invoke((MethodInvoker) delegate { tbInput.AppendText("\r\n" + result.ToString() + " новых записей добавлено."); }); } } }
public void Adding_then_removing_will_result_in_no_subscriptions() { var serializer = new XmlMessageSerializer(new DefaultReflection(), new DefaultKernel()); var msg = new Message(); serializer.Serialize(new object[]{new AddSubscription { Endpoint = TransactionalTestQueueUri.ToString(), Type = typeof(TestMessage).FullName, }}, msg.BodyStream); queue.Send(msg, MessageQueueTransactionType.None); msg = queue.Peek(); queue.MoveToSubQueue("subscriptions",msg); var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(), serializer, TestQueueUri, new SubQueueStrategy()); subscriptionStorage.Initialize(); subscriptionStorage.RemoveSubscription(typeof(TestMessage).FullName, TransactionalTestQueueUri.ToString()); var uris = subscriptionStorage .GetSubscriptionsFor(typeof (TestMessage)); Assert.Equal(0, uris.Count()); }
override protected void Append(LoggingEvent loggingEvent) { if (m_queue == null) { if (MessageQueue.Exists(m_queueName)) { m_queue = new MessageQueue(m_queueName); } else { ErrorHandler.Error("Queue ["+m_queueName+"] not found"); } } if (m_queue != null) { Message message = new Message(); message.Label = RenderLabel(loggingEvent); using(System.IO.MemoryStream stream = new System.IO.MemoryStream()) { System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, new System.Text.UTF8Encoding(false, true)); base.RenderLoggingEvent(writer, loggingEvent); writer.Flush(); stream.Position = 0; message.BodyStream = stream; m_queue.Send(message); } } }
public void Can_read_subscription_from_queue() { var serializer = new XmlMessageSerializer(new DefaultReflection(), new DefaultKernel()); var msg = new Message(); serializer.Serialize(new object[]{new AddSubscription { Endpoint = TransactionalTestQueueUri.ToString(), Type = typeof(TestMessage).FullName, }}, msg.BodyStream); queue.Send(msg, MessageQueueTransactionType.None); msg = queue.Peek(); queue.MoveToSubQueue("subscriptions", msg); var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(), serializer, TestQueueUri, new SubQueueStrategy()); subscriptionStorage.Initialize(); var uri = subscriptionStorage .GetSubscriptionsFor(typeof(TestMessage)) .Single(); Assert.Equal(TransactionalTestQueueUri, uri); }
/// <summary> /// Writes to the MSMQ message, assuming that the given object is a <see cref="TransportMessageToSend"/> - /// otherwise, an <see cref="ArgumentException"/> will be thrown /// </summary> public void Write(Message message, object obj) { var transportMessage = obj as TransportMessageToSend; if (transportMessage == null) { throw new ArgumentException( string.Format("Object to serialize is not a TransportMessageToSend - it's a {0}", obj.GetType())); } message.BodyStream = new MemoryStream(transportMessage.Body); message.Extension = HeaderEcoding.GetBytes(DictionarySerializer.Serialize(transportMessage.Headers)); message.Label = transportMessage.Label ?? "???"; var expressDelivery = transportMessage.Headers.ContainsKey(Headers.Express); var hasTimeout = transportMessage.Headers.ContainsKey(Headers.TimeToBeReceived); // make undelivered messages go to the dead letter queue if they could disappear from the queue anyway message.UseDeadLetterQueue = !(expressDelivery || hasTimeout); message.Recoverable = !expressDelivery; if (hasTimeout) { var timeToBeReceivedStr = (string)transportMessage.Headers[Headers.TimeToBeReceived]; message.TimeToBeReceived = TimeSpan.Parse(timeToBeReceivedStr); } }
private bool SendToAllQueues(Message message) { var success = true; for (var i = 0; i < _sendQueues.Count; i++) { // if a sender queue is not available at the moment due to a previous error, don't send the message if (!_sendQueuesAvailable[i]) continue; try { _sendQueues[i].Send(message); } catch (MessageQueueException mex) { Logger.WriteException(mex); _sendQueuesAvailable[i] = false; // indicate that the queue is out of order success = false; } catch (Exception ex) { Logger.WriteException(ex); _sendQueuesAvailable[i] = false; // indicate that the queue is out of order success = false; } } return success; }
public void SendMessageToQueue(string queueName, CallDisposition data) { var msMq = new MessageQueue(queueName); var myMessage = new System.Messaging.Message(); myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(CallDisposition) }); myMessage.Body = data; myMessage.Label = "MessageQueue"; myMessage.UseJournalQueue = true; myMessage.Recoverable = true; //message send acknowledgement. myMessage.AdministrationQueue = new MessageQueue(@".\Private$\MessageAcknowledgeQueue"); myMessage.AcknowledgeType = AcknowledgeTypes.PositiveReceive | AcknowledgeTypes.PositiveArrival; try { msMq.Send(myMessage); Console.WriteLine("Message sent successfully!"); } catch (MessageQueueException e) { Console.Write(e.ToString()); } catch (Exception e) { Console.Write(e.ToString()); } finally { msMq.Close(); } }
static public bool Receive_msmq_message <T>(int timeoutInMs, out T convertedObject, out string MessageLabel, MessageQueue queue, out string error) { convertedObject = default(T); error = ""; MessageLabel = string.Empty; bool retValue = false; if (queue != null) { TimeSpan ts = TimeSpan.FromMilliseconds(timeoutInMs); MessageQueueTransaction tr = new MessageQueueTransaction(); tr.Begin(); try { System.Messaging.Message message = queue.Receive(ts, tr); message.Formatter = new XmlMessageFormatter(new Type[] { typeof(T) }); MessageLabel = message.Label; convertedObject = (T)message.Body; tr.Commit(); retValue = true; } catch (Exception e) { error = e.Message; tr.Abort(); } } return(retValue); }
private void OnMessageRecived(Object source, ReceiveCompletedEventArgs e) { MessageQueue mq = null; System.Messaging.Message m = null; try { //incercam sa luam mesajul primit mq = (MessageQueue)source; m = mq.EndReceive(e.AsyncResult); } catch { MessageBox.Show("Error"); } m.Formatter = new BinaryMessageFormatter(); EditorMessages msg = (EditorMessages)m.Body; switch (msg.Type) { case MSG_TYPE.NEW_TEXT: SetText(msg.Text); break; } try { mq.BeginReceive(); } catch { MessageBox.Show("Error"); } }
void solve() { string QueueName = ".\\Private$\\sum"; MessageQueue Q1 = new MessageQueue(QueueName); try { System.Messaging.Message ms = Q1.Receive(); ms.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); int a = Convert.ToInt32(ms.Body.ToString()); int sum = 0; for (int i = 1; i <= a; i++) { sum += i; } string Queue2 = ".\\Private$\\sum_ans"; if (!MessageQueue.Exists(Queue2)) { MessageQueue.Create(Queue2); } MessageQueue Q2 = new MessageQueue(Queue2); Q2.Send(sum); solve(); } catch (Exception ex) { } }
// reads message off the queue; calls ProcessMessage internal void PeekMessage(string mqPath) { try { // grab a handle to the queue MessageQueue mq = new MessageQueue(mqPath); ((XmlMessageFormatter)mq.Formatter).TargetTypeNames = new string[] { "System.String" }; // receive the next message with a timeout of 30 seconds System.Messaging.Message msg = mq.Peek(new TimeSpan(0, 0, 0, Constants.QUEUE_TIMEOUT, 0)); // save message ID; will remove from queue later if all is successful string msgId = msg.Id; // log SharedSupport.LogMessage(SharedSupport.GetLocalizedString("ServerAction_PeekMessage") + msg.Label + " " + msg.Body); // set boolean to remove from queue bool removeFromQueue = ProcessMessage(msg.Body.ToString(), msg.Label.ToString()); // if ProcessMessage true, remove the message from the queue if (removeFromQueue == true) { mq.ReceiveById(msgId, new TimeSpan(0, 0, 0, Constants.QUEUE_TIMEOUT, 0)); // log SharedSupport.LogMessage(SharedSupport.GetLocalizedString("ServerAction_RemoveMessage") + msg.Label + " " + msg.Body); } } catch (System.Exception ex) { SharedSupport.HandleError(ex); } }
public void Raven_dtc_bug() { new MessageQueue(QueueAddress, QueueAccessMode.ReceiveAndAdmin) .Purge(); using (var tx = new TransactionScope()) { using (var session = store.OpenSession()) { session.Store(new GatewayMessage()); session.SaveChanges(); } using (var q = new MessageQueue(QueueAddress, QueueAccessMode.Send)) { var toSend = new Message { BodyStream = new MemoryStream(new byte[8]) }; //sending a message to a msmq queue causes raven to promote the tx q.Send(toSend, MessageQueueTransactionType.Automatic); } //when we complete raven commits it tx but the DTC tx is never commited and eventually times out tx.Complete(); } Thread.Sleep(1000); Assert.AreEqual(1,new MessageQueue(QueueAddress, QueueAccessMode.ReceiveAndAdmin) .GetAllMessages().Length); }
private void btnSend2_Click(object sender, System.EventArgs e) { System.Messaging.Message m = new System.Messaging.Message(); //m.Formatter = new System.Messaging.BinaryMessageFormatter(); m.Body = "Content"; MyMQ.Send(m); }
public void InsertMessageinQueue() { try { MessageQueue msmq = null; if (MessageQueue.Exists(connection)) { msmq = new MessageQueue(connection); } else { msmq = MessageQueue.Create(connection); } var msg = new Message(); msg.Body = "SampleMessage "; msg.Label = "Msg" + i.ToString(); ++i; msmq.Send(msg); msmq.Refresh(); //msmq.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
private void btnSendImage_Click(object sender, System.EventArgs e) { Stream imageStream; System.Messaging.Message mImage = new System.Messaging.Message(); openFileDialog1.Filter = "image files (.bmp,.jpg,.gif)|*.bmp;*.jpg;*.gif;*.exe"; openFileDialog1.FilterIndex = 1; if (openFileDialog1.ShowDialog() == DialogResult.OK) { if ((imageStream = openFileDialog1.OpenFile()) != null) { mImage.BodyStream = imageStream; try { MyMQ.Send(mImage); } catch (Exception ex) { MessageBox.Show(ex.Message + " " + ex.InnerException.Message); } finally { imageStream.Close(); } } } }
private void SendStartupNotification() { MessageQueue startupQueue = null; string startupQueueName = @".\Private$\StromoLight_Startup"; if (MessageQueue.Exists(startupQueueName)) { startupQueue = new System.Messaging.MessageQueue(@".\Private$\StromoLight_Startup"); System.Messaging.Message message = new System.Messaging.Message(); message.Body = "DSOK"; message.Label = "Message from Diagnostics"; startupQueue.Send(message); } else { startupQueue = MessageQueue.Create(@".\Private$\StromoLight_Startup"); startupQueue = new System.Messaging.MessageQueue(@".\Private$\StromoLight_Startup"); System.Messaging.Message message = new System.Messaging.Message(); message.Body = "DSOK Started OK"; message.Label = "Message from Diagnostics"; startupQueue.Send(message); } }
private void btnReceiveImage_Click(object sender, System.EventArgs e) { Bitmap bmp; Stream imageStream; System.Messaging.Message mImage = new System.Messaging.Message(); try { mImage = MyMQ.Receive(new TimeSpan(0, 0, 3)); } catch { MessageBox.Show("No messages were receieved"); } try { imageStream = mImage.BodyStream; bmp = new Bitmap(imageStream); picBox1.Image = bmp; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void recuperarFacturasToolStripMenuItem_Click(object sender, EventArgs e) { try { string rutaCola = @".\private$\facturas"; if (!MessageQueue.Exists(rutaCola)) { MessageQueue.Create(rutaCola); } MessageQueue cola = new MessageQueue(rutaCola); cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Factura) }); int total = cola.GetAllMessages().Count(); while (cola.GetAllMessages().Count() != 0) { System.Messaging.Message mensaje = cola.Receive(); Factura facturaItem = (Factura)mensaje.Body; string postdata = "{\"Numero\":\"" + facturaItem.Numero + "\",\"Fecha\":\"" + facturaItem.Fecha + "\",\"Cliente\":\"" + facturaItem.Cliente + "\",\"ImporteBruto\":\"" + facturaItem.ImporteBruto + "\",\"ImporteVenta\":\"" + facturaItem.ImporteVenta + "\",\"ImporteIGV\":\"" + facturaItem.ImporteIGV + "\",\"ImporteTotalVenta\":\"" + facturaItem.ImporteTotalVenta + "\"}"; byte[] data = Encoding.UTF8.GetBytes(postdata); HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:23440/Facturas.svc/Facturas"); req.Method = "POST"; req.ContentLength = data.Length; req.ContentType = "application/json"; var reqStream = req.GetRequestStream(); reqStream.Write(data, 0, data.Length); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(res.GetResponseStream()); string compraJson = reader.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); } MessageBox.Show(total + " facturas recuperadas", "Facturas Recuperadas"); } catch { MessageBox.Show("Error de comunicación", "Error"); } }
public void SendToMSMQ(List <string> entries) { if (entries == null || entries.Count <= 0) { return; } try { object obj = entries; if (JsonSerialization) { string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(entries); obj = json; } var m = new System.Messaging.Message(obj); MyQueue.Send(m, Source); } catch (Exception ex) { Trace.WriteLine(ex); } }
public void Send(string Msg) { string QueuePath = ".\\private$\\SZJS_Allcai_Task_" + MessageType; if (!MessageQueue.Exists(QueuePath)) { return; } MessageQueue mq = null; try { mq = new MessageQueue(QueuePath); } catch { return; } if (mq == null) { return; } System.Messaging.Message m = new System.Messaging.Message(); m.Body = Msg; m.Formatter = new System.Messaging.BinaryMessageFormatter(); mq.Send(m); }
private void onUpdateReceived(IAsyncResult asyncResult) { Client client = (Client)asyncResult.AsyncState; try { Message msg = client.rxQueue.EndReceive(asyncResult); documentTextBox.TextChanged -= documentTextBox_TextChanged; documentTextBox.Text = (string)msg.Body; documentTextBox.TextChanged += documentTextBox_TextChanged; /* * this.Invoke((MethodInvoker)delegate () * { * });*/ } catch { } finally { client.rxQueue.BeginReceive(Client.maxLockTime, client, new AsyncCallback(onUpdateReceived) ); } }
public MsmqSubscriptionMessage(Message m) { Body = m.Body; Label = m.Label; Id = m.Id; ArrivedTime = m.ArrivedTime; }
/// <summary> /// 发送消息 /// </summary> /// <typeparam name="T">用户数据类型</typeparam> /// <param name="target">用户数据</param> /// <param name="queuePath">队列名称</param> /// <param name="tran"></param> /// <returns></returns> public static bool SendMessage <T>(T target, string queuePath, MessageQueueTransaction tran = null) { try { //连接到本地的队列 MessageQueue myQueue = new MessageQueue(queuePath); System.Messaging.Message myMessage = new System.Messaging.Message(); myMessage.Body = target; myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(T) }); //发送消息到队列中 if (tran == null) { myQueue.Send(myMessage); } else { myQueue.Send(myMessage, tran); } Console.WriteLine("消息已成功发送到" + queuePath + "队列!"); return(true); } catch (ArgumentException e) { Console.WriteLine(e.Message); return(false); } }
static void Main() { Console.WriteLine("Using straight xml serialization and msmq to test interop."); Console.WriteLine("To exit, enter 'q'. Press 'Enter' to send a message."); string queueName = string.Format("FormatName:DIRECT=OS:{0}\\private$\\OrderServiceInputQueue", Environment.MachineName); var label = "<CorrId></CorrId><WinIdName>UDI_MOBILE_2\\Administrator</WinIdName>"; var q = new MessageQueue(queueName); var serializer = new XmlSerializer(typeof(OrderMessage), new[] { typeof(OrderLine) }); while ((Console.ReadLine().ToLower()) != "q") { var m1 = new OrderMessage { PurchaseOrderNumber = Guid.NewGuid().ToString(), ProvideBy = DateTime.Now, PartnerId = Guid.NewGuid(), OrderLines = new[] {new OrderLine {ProductId = Guid.NewGuid(), Quantity = 10F}}, Done = true }; var toSend = new Message(); serializer.Serialize(toSend.BodyStream, m1); toSend.ResponseQueue = new MessageQueue(string.Format("FormatName:DIRECT=OS:{0}\\private$\\PartnerInputQueue", Environment.MachineName)); toSend.Label = label; q.Send(toSend, MessageQueueTransactionType.Single); Console.WriteLine("Sent order {0}", m1.PurchaseOrderNumber); } }
static void SendMessages() { MessageQueue messageQueue = null; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Directory.GetCurrentDirectory() + @"\XMLFiles\TestFile.xml"); if (MessageQueue.Exists(quePath)) { messageQueue = new MessageQueue(quePath); messageQueue.Label = "Testing Queue"; } else { // Create the Queue MessageQueue.Create(quePath); messageQueue = new MessageQueue(quePath); messageQueue.Label = "Newly Created Queue"; } System.Messaging.Message msg = new System.Messaging.Message { Body = xmlDoc, Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" }) }; messageQueue.Send(msg); }
/// <summary> /// 2.连接消息队列并发送消息到队列 /// 远程模式:MessageQueue rmQ = new MessageQueue("FormatName:Direct=OS:machinename//private$//queue"); /// rmQ.Send("sent to regular queue - Atul");对于外网的MSMQ只能发不能收 /// </summary> public void SendMessage() { try { //连接到本地队列 MessageQueue myQueue = new MessageQueue(Path); //MessageQueue myQueue = new MessageQueue("FormatName:Direct=TCP:192.168.12.79//Private$//myQueue1"); //MessageQueue rmQ = new MessageQueue("FormatName:Direct=TCP:121.0.0.1//private$//queue");--远程格式 System.Messaging.Message myMessage = new System.Messaging.Message(); myMessage.Body = "消息内容34kuangbo去死"; myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); //发生消息到队列中 myQueue.Send(myMessage); Console.WriteLine("消息发送成功!"); Console.ReadLine(); } catch (ArgumentException e) { Console.WriteLine(e.Message); } }
private bool DoesUserExist(string emailAddress) { var responseAddress = Guid.NewGuid().ToString().Substring(0, 6); responseAddress = ".\\private$\\" + responseAddress; try { using (var responseQueue = msmq.MessageQueue.Create(responseAddress)) { var doesUserExistRequest = new DoesUserExistRequest { EmailAddress = emailAddress }; using (var requestQueue = new msmq.MessageQueue( ".\\private$\\sixeyed.messagequeue.doesuserexist")) { var message = new msmq.Message(); message.BodyStream = doesUserExistRequest.ToJsonStream(); message.Label = doesUserExistRequest.GetMessageType(); message.ResponseQueue = responseQueue; requestQueue.Send(message); } var response = responseQueue.Receive(); var responseBody = response.BodyStream.ReadFromJson <DoesUserExistResponse>(); return(responseBody.Exists); } } finally { if (msmq.MessageQueue.Exists(responseAddress)) { msmq.MessageQueue.Delete(responseAddress); } } }
public ActionResult Publish(string message) { //var factory = new ConnectionFactory() { HostName = "localhost" }; //using (var connection = factory.CreateConnection()) //using (var channel = connection.CreateModel()) //{ // channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); // var body = Encoding.UTF8.GetBytes(message); // channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body); // Console.WriteLine(" [x] Sent {0}", message); //} var queue = new MessageQueue(@".\Private$\HelloWorld"); var msg = new Message { Body = message, Label = $"Presentation at {DateTime.Now}" }; queue.Send(msg); return View("Index"); }
protected void PeekCompleted(object sender, PeekCompletedEventArgs e) { System.Messaging.Message msg = null; MessageQueue mq = null; try { mq = (MessageQueue)sender; mq.Formatter = new BinaryMessageFormatter(); System.Messaging.Message m = mq.EndPeek(e.AsyncResult); mq.ReceiveById(m.Id); if (OnMessageArrivedHandle != null) { OnMessageArrivedHandle(m.Label, m.Body.ToString()); } } catch (Exception ex) { string err = ex.Message; } finally { if (msg != null) { try { msg.Dispose(); } catch { } finally { msg = null; } } //接收下一次事件 if (mq != null) { mq.BeginPeek(); } } }
private static int GetMessageCountWithPeek(MessageQueue q) { // remember to release resource as soon as possible, // if not there may be a "An invalid handle was passed to the function." exception int count = 0; using (Cursor cursor = q.CreateCursor()) { System.Messaging.Message m = PeekWithoutTimeout(q, cursor, PeekAction.Current); if (m != null) { m.Dispose(); count = 1; while ((m = PeekWithoutTimeout(q, cursor, PeekAction.Next)) != null) { m.Dispose(); count++; } } } return(count); }
public void Send2WithLabelWithTransaction () { String label1 = "label1"; String label2 = "label2"; Message sent1 = new Message ("Message 1", new BinaryMessageFormatter ()); Message sent2 = new Message ("Message 2", new BinaryMessageFormatter ()); MessageQueue mq = MQUtil.GetQueue (MQUtil.CreateQueueName (), true); mq.MessageReadPropertyFilter.SetAll (); Assert.IsTrue(mq.Transactional, "Message Queue should be transactional"); using (MessageQueueTransaction tx = new MessageQueueTransaction ()) { tx.Begin (); mq.Send (sent1, label1, tx); mq.Send (sent2, label2, tx); tx.Commit (); Message received1 = mq.Receive (); Assert.IsNotNull (received1.TransactionId, "TransactionId not set"); Message received2 = mq.Receive (); Assert.IsNotNull (received2.TransactionId, "TransactionId not set"); Assert.AreEqual (received1.TransactionId, received2.TransactionId, "Messages have differing TransactionIds"); Assert.IsTrue (received1.TransactionId.Length > 1); Assert.AreEqual (sent1.Body, received1.Body, "Message 1 not delivered correctly"); Assert.AreEqual (sent2.Body, received2.Body, "Message 2 not delivered correctly"); Assert.AreEqual (label1, received1.Label, "Label 1 not passed correctly"); Assert.AreEqual (label2, received2.Label, "Label 2 not passed correctly"); } }
/// <summary> /// Start the listen to the queue for incoming messages and /// notifiy the handlers as new messges arrive /// </summary> private void StartQueueListener() { //create a separate connection to the message queue System.Messaging.MessageQueue listenermq = new System.Messaging.MessageQueue(formatName); ((XmlMessageFormatter)listenermq.Formatter).TargetTypeNames = (string[])(supportedTypes.ToArray(typeof(System.String))); System.Messaging.Message message = null; queueListenerStarted = true; try { //listen to the queue continusly through loop while (queueListenerStarted == true) { System.Threading.Thread.Sleep(sleepTime); if (handler.GetInvocationList().Length > 0) { //this is a call that will block the thread if no //message is in the queue. message = listenermq.Receive(); SAF.MessageQueue.Message safMessage = new SAF.MessageQueue.Message(); safMessage.Label = message.Label; safMessage.Content = message.Body; //fire the event handler(safMessage, queueName); } } } finally { //close the connetion listenermq.Close(); } }
public bool CanRead (Message message) { if (message == null) throw new ArgumentNullException (); return message.BodyStream.CanRead; }
public void SendReceiveBinaryMessage () { MessageQueue mq = MQUtil.GetQueue (); String s = "Test: " + DateTime.Now; Message m = new Message (s, new BinaryMessageFormatter ()); m.CorrelationId = Guid.NewGuid () + "\\0"; mq.MessageReadPropertyFilter.SetAll (); mq.Send (m); Message m2 = mq.Receive (); m2.Formatter = new BinaryMessageFormatter (); Assert.AreEqual (s, m2.Body); //Assert.IsTrue (DateTime.MinValue == m.ArrivedTime); Assert.IsNotNull(m2.Id, "Id is null"); Assert.IsTrue (Guid.Empty.ToString () != m2.Id, "Id is Empty"); Assert.IsTrue (DateTime.MinValue != m2.ArrivedTime, "Arrived Time is not set"); Assert.AreEqual (Acknowledgment.None, m2.Acknowledgment, "Acknowledgment"); Assert.AreEqual (m.CorrelationId, m2.CorrelationId, "CorrelationId not set properly"); Assert.IsTrue (0 != m2.SenderVersion); // TODO: This is not supported on a workgroup installation. //Assert.IsNotNull (m2.SourceMachine, "SourceMachine is null"); Assert.AreEqual (mq.QueueName, m2.DestinationQueue.QueueName, "Destination Queue not set"); mq.Close (); }
/// <summary> /// Converts a TransportMessage to an Msmq message. /// Doesn't set the ResponseQueue of the result. /// </summary> public static Message Convert(TransportMessage message) { var result = new Message(); if (message.Body != null) { result.BodyStream = new MemoryStream(message.Body); } AssignMsmqNativeCorrelationId(message, result); result.Recoverable = message.Recoverable; if (message.TimeToBeReceived < MessageQueue.InfiniteTimeout) { result.TimeToBeReceived = message.TimeToBeReceived; } using (var stream = new MemoryStream()) { headerSerializer.Serialize(stream, message.Headers.Select(pair => new HeaderInfo { Key = pair.Key, Value = pair.Value }).ToList()); result.Extension = stream.ToArray(); } result.AppSpecific = (int) message.MessageIntent; return result; }
public bool HandlePeekedMessage(IMsmqTransport transport, OpenedQueue queue, Message message) { bool doesNotHaveMessageId = message.Extension.Length < 16; if(doesNotHaveMessageId) { const string errorMessage = "Message does not have Extension set to at least 16 bytes, which will be used as the message id. Probably not a bus message."; transport.RaiseMessageSerializationException(queue,message,errorMessage); MoveToErrorQueue(queue, message, errorMessage); return true; } var id = message.GetMessageId(); ErrorCounter errorCounter = null; failureCounts.Read(reader => reader.TryGetValue(id, out errorCounter)); if (errorCounter == null) return false; if (errorCounter.FailureCount < numberOfRetries) return false; failureCounts.Write(writer => { writer.Remove(id); MoveToErrorQueue(queue, message, errorCounter.ExceptionText); }); return true; }
Message CreateMsmqMessage(TransportMessage message) { var headers = message.Headers; var expressDelivery = headers.ContainsKey(Headers.Express); var hasTimeout = headers.TryGetValue(Headers.TimeToBeReceived, out var timeToBeReceivedStr); var msmqMessage = new Message { BodyStream = new MemoryStream(message.Body), UseJournalQueue = false, Recoverable = !expressDelivery, UseDeadLetterQueue = !(expressDelivery || hasTimeout), Label = GetMessageLabel(message), }; _msmqHeaderSerializer.SerializeToMessage(headers, msmqMessage); if (hasTimeout) { msmqMessage.TimeToBeReceived = TimeSpan.Parse(timeToBeReceivedStr); } return(msmqMessage); }
public void Adding_then_removing_will_result_in_no_subscriptions() { var serializer = new XmlMessageSerializer(new DefaultReflection(), new CastleServiceLocator(new WindsorContainer())); var msg = new Message(); serializer.Serialize(new object[]{new AddSubscription { Endpoint = transactionalTestQueueEndpoint, Type = typeof(TestMessage).FullName, }}, msg.BodyStream); msg.Extension = Guid.NewGuid().ToByteArray(); queue.OpenSiblngQueue(SubQueue.Subscriptions, QueueAccessMode.Send).Send(msg); var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(), serializer, testQueueEndPoint.Uri, new EndpointRouter(), new FlatQueueStrategy(new EndpointRouter(),testQueueEndPoint.Uri)); subscriptionStorage.Initialize(); subscriptionStorage.RemoveSubscription(typeof(TestMessage).FullName, transactionalTestQueueEndpoint.Uri.ToString()); var uris = subscriptionStorage .GetSubscriptionsFor(typeof(TestMessage)); Assert.Equal(0, uris.Count()); }
private void button2_Click(object sender, EventArgs e) { textBoxTituloReceber.Text = string.Empty; textBoxConteudoReceber.Text = string.Empty; int timeout = 1000; //tempo de espera por uma nova mensagem, caso não exista nenhuma na fila try { var retorno = messageQueue.ReceiveById(textBoxTituloReceber.Text); System.Messaging.Message message = messageQueue.Receive(new TimeSpan(timeout)); message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(String) }); textBoxTituloReceber.Text = message.Label; textBoxConteudoReceber.Text = (string)message.Body; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static void ReceiveFromMsmq() { // Open transactional MSMQ queue. Define filter to retrieve all message properties. MessageQueue msmqQueue = Helper.OpenMsmqQueue(Constants.MsmqReceiveQueue, true); for (int i = 1; i <= 3; i++) { try { using (MessageQueueTransaction msmqTransaction = new MessageQueueTransaction()) { // Receive message from MSMQ. msmqTransaction.Begin(); System.Messaging.Message msmqMessage = msmqQueue.Receive(msmqTransaction); Console.WriteLine( string.Format("Received message from {0}: {1}", Constants.MsmqReceiveQueue, msmqMessage.Label)); msmqTransaction.Commit(); } } catch (MessageQueueException) { // In this scenario (infinite receive), we can receive a MessageQueueException when // the MSMQ queues are deleted during cleanup return; } catch (Exception exception) { Console.WriteLine("Exception received: " + exception.ToString()); throw; } } }
void MsmqOnPeekComplete(IAsyncResult result) { // Complete the MSMQ peek operation. If a timeout occured, peek again. System.Messaging.Message msmqMessage = null; try { msmqMessage = this.msmqQueue.EndPeek(result); } catch (MessageQueueException ex) { if (ex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout) { this.MsmqPeekBegin(); return; } } if (msmqMessage != null) { var Message = MsmqHelper.UnpackServiceBusMessageFromMsmqMessage(msmqMessage); // Clone Service Bus message in case we need to deadletter it. var serviceBusDeadletterMessage = Message.Clone(); Trace.TraceInformation("DurableSender: Enqueue message {0} into Service Bus.", msmqMessage.Label); switch (this.SendMessageToServiceBus(Message)) { case SendResult.Success: // Message was successfully sent to Service Bus. Remove MSMQ message from MSMQ queue. Trace.TraceInformation("DurableSender: Service Bus send operation completed."); this.msmqQueue.BeginReceive(TimeSpan.FromSeconds(60), null, this.MsmqOnReceiveComplete); break; case SendResult.WaitAndRetry: // Service Bus is temporarily unavailable. Wait. Trace.TraceWarning("DurableSender: Service Bus is temporarily unavailable."); this.waitAfterErrorTimer = new Timer( this.ResumeSendingMessagesToServiceBus, null, WaitTimeAfterServiceBusReturnsAnIntermittentErrorInSeconds * 1000, Timeout.Infinite); break; case SendResult.PermanentFailure: // Permanent error. Deadletter MSMQ message. Trace.TraceError("DurableSender: Permanent error when sending message to Service Bus. Deadletter message."); var msmqDeadletterMessage = MsmqHelper.PackServiceBusMessageIntoMsmqMessage(serviceBusDeadletterMessage); try { this.SendtoMsmq(this.msmqDeadletterQueue, msmqDeadletterMessage); } catch (Exception ex) { Trace.TraceError( "DurableSender: Failure when sending message {0} to deadletter queue {1}: {2} {3}", msmqDeadletterMessage.Label, this.msmqDeadletterQueue.FormatName, ex.GetType(), ex.Message); } this.msmqQueue.BeginReceive(TimeSpan.FromSeconds(60), null, this.MsmqOnReceiveComplete); break; } } }
private void Loop() { //q2.Purge(); var start = Stopwatch.StartNew(); while (true) { batchCountdownEvent.Reset(); var sp = Stopwatch.StartNew(); Parallel.For(0, batchSize, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, i => { var current = Interlocked.Increment(ref total); var msg = new Message { Recoverable = true, Label = current.ToString(), Body = body, Extension = head, }; writeQueue.Send(msg, MessageQueueTransactionType.Single); }); batchCountdownEvent.Wait(); var elapsed = sp.Elapsed.TotalSeconds; Console.WriteLine("{0:N0}msg/s ~{1:N0} +{2:N0} {3}s", batchSize / elapsed, total / start.Elapsed.TotalSeconds, total, start.Elapsed.TotalSeconds); } }
private void button1_Click(object sender, EventArgs e) { System.Messaging.Message inMessage = readerThingy.Receive(); inMessage.Formatter = new XmlMessageFormatter(new String[] { "System.String,mscorlib" }); textOut = (String)inMessage.Body; textBox1.Text = textOut; }
public void Adding_then_removing_will_result_in_no_subscriptions() { var serializer = new XmlMessageSerializer(new DefaultReflection(), new CastleServiceLocator(new WindsorContainer())); var msg = new Message(); serializer.Serialize(new object[]{new AddSubscription { Endpoint = TransactionalTestQueueUri, Type = typeof(TestMessage).FullName, }}, msg.BodyStream); msg.Extension = Guid.NewGuid().ToByteArray(); queue.Send(msg, MessageQueueTransactionType.None); msg = queue.Peek(TimeSpan.FromSeconds(30)); queue.MoveToSubQueue("subscriptions",msg); var subscriptionStorage = new MsmqSubscriptionStorage(new DefaultReflection(), serializer, TestQueueUri.Uri, new EndpointRouter(), new SubQueueStrategy()); subscriptionStorage.Initialize(); subscriptionStorage.RemoveSubscription(typeof(TestMessage).FullName, TransactionalTestQueueUri.Uri.ToString()); var uris = subscriptionStorage .GetSubscriptionsFor(typeof (TestMessage)); Assert.Equal(0, uris.Count()); }