static void Main(string[] args) { SolicitudServicioData oSolicitudServicioData = new SolicitudServicioData(); string rutaCola = @".\private$\SolicitudServicioRecibida"; if (MessageQueue.Exists(rutaCola) == true) { MessageQueue cola = new MessageQueue(rutaCola); Message[] msgs = cola.GetAllMessages(); SolicitudServicioDTO oSolicitudServicioDTO = new SolicitudServicioDTO(); if (cola.GetAllMessages().Count() > 0) { foreach (Message msg in cola.GetAllMessages()) { msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(SolicitudServicioDTO) }); oSolicitudServicioDTO = (SolicitudServicioDTO)msg.Body; if (oSolicitudServicioData.Get(oSolicitudServicioDTO.SolicitudServicioId) == null) { oSolicitudServicioData.Add(oSolicitudServicioDTO); } else { oSolicitudServicioData.Update(oSolicitudServicioDTO); } cola.Receive(); } } } }
static void Main(string[] args) { CitaDAO dao = new CitaDAO(); string rutaCola = @".\private$\CitaRecibida"; if (MessageQueue.Exists(rutaCola) == true) { MessageQueue cola = new MessageQueue(rutaCola); Message[] msgs = cola.GetAllMessages(); Cita _cita = new Cita(); if (cola.GetAllMessages().Count() > 0) { foreach (Message msg in cola.GetAllMessages()) { msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(Cita) }); _cita = (Cita)msg.Body; if (dao.Obtener(_cita.IdCita) == null) { dao.Crear(_cita); } else { dao.Modificar(_cita); } cola.Receive(); } } } }
public void ReceiveLastMessage() { Trace.WriteLine("Start Receiving and sending last message from Queue", "ReceiveLastMessage"); List <Message> messages = mq.GetAllMessages().ToList(); if (messages.Count > 0) { Message lastMessage = messages.Last(); QueueMessage queueMessage = (QueueMessage)mq.ReceiveById(lastMessage.Id).Body; String errorMessage = String.Empty; // Get byte array from file VanLeeuwen.Framework.IO.File.WaitForRelease(queueMessage.FilePath, 10); byte[] fileContents = File.ReadAllBytes(queueMessage.FilePath); if (FileSender.SendFile(queueMessage.DatabaseName, fileContents, queueMessage.FileName, out errorMessage)) { // Succesfully Send!!! // remove file from Queue folder File.Delete(queueMessage.FilePath); } else { AddMessage(queueMessage); } Trace.WriteLine("Receiving and sending last message from Queue completed", "ReceiveLastMessage"); } }
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 MensajeEncola() { //guardamos los mensajes en cola si ocurre error string rutaCola = @".\private$\queja"; if (!MessageQueue.Exists(rutaCola)) { MessageQueue.Create(rutaCola); } MessageQueue cola = new MessageQueue(rutaCola); Message mensaje = new Message(); mensaje.Label = "Queja registrada con fecha " + DateTime.Now.ToShortDateString(); mensaje.Body = new Queja() { N_IdResidente = 2, B_Estado = false, C_Detalle = "detalle", C_Motivo = "motivo", C_Tipo = "Grave", D_FecQueja = "2014-06-12", D_FecRegistro = new DateTime(10,10,10,10,10,10) }; cola.Send(mensaje); //recuperamos el mensaje MessageQueue cola2 = new MessageQueue(rutaCola); int cantidadmensajes = 0; if (MessageQueue.Exists(rutaCola)) { cantidadmensajes = cola2.GetAllMessages().Count(); //recorrer y grabar foreach (Message mensajeTodo in cola2.GetAllMessages()) { mensajeTodo.Formatter = new XmlMessageFormatter(new Type[] { typeof(Queja) }); Queja ObjQueja = (Queja)mensajeTodo.Body; //buscamos el que se envio if (ObjQueja.N_IdResidente == 2 & ObjQueja.D_FecQueja == "2014-06-12") { Assert.AreEqual(false, ObjQueja.B_Estado); Assert.AreEqual("detalle", ObjQueja.C_Detalle); Assert.AreEqual("motivo", ObjQueja.C_Motivo); Assert.AreEqual("Grave", ObjQueja.C_Tipo); Assert.AreEqual(new DateTime(10, 10, 10, 10, 10, 10), ObjQueja.D_FecRegistro); cola2.Receive(); break; } } //se elimina los mensajes MessageQueue.Delete(rutaCola); } Assert.AreNotEqual(0, cantidadmensajes); }
public ICollection<Favorito> ListarFavoritos(int idTorneo, int idParticipante) { string rutaCola = @".\private$\DSWarrior2"; if (!MessageQueue.Exists(rutaCola)) { MessageQueue.Create(rutaCola); } var cola = new MessageQueue(rutaCola); cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Favorito) }); var lista = new List<Favorito>(); var messages = cola.GetAllMessages(); var totalMessages = messages.Count(); for (int i = 0; i < totalMessages; i++) { var mensaje = messages[i]; var favorito = (Favorito)mensaje.Body; if (favorito.IDTorneo == idTorneo && favorito.IDParticipante == idParticipante) { lista.Add(favorito); } } return lista; //return favoritoDA.ListarFavoritos(idTorneo, idParticipante); }
private void SequanceProcess(Guid agentId, CancellationToken cancelToken) { try { var agentQueueName = GetAgentQueueName(agentId); HostLogger.Get <ProcessingService>().Info("Pdf generation started..."); using (var agentQueue = new System.Messaging.MessageQueue(agentQueueName, QueueAccessMode.Receive)) { agentQueue.Formatter = new XmlMessageFormatter(new[] { typeof(string) }); var imageNamesMessages = agentQueue.GetAllMessages(); if (!imageNamesMessages.Any()) { return; } var imageNames = imageNamesMessages.Select(x => x.Body as string).ToList(); GeneratePdfFile(agentId, imageNames, cancelToken); RemoveProcessedItems(imageNames, agentQueue); } } catch (Exception e) { HostLogger.Get <ProcessingService>().Error(e.Message); } _status = ProcessingStatus.Idle; }
public object receiveByID(string MessageID, string InputQueue) { // Open existing queue using (MessageQueue queue = new MessageQueue(InputQueue)) { //Peek to find message with the MessageID in the label while (true) { Message[] peekedmessage = queue.GetAllMessages(); foreach (Message m in peekedmessage) { if (m.Label.StartsWith(MessageID)) { using (Message message = queue.ReceiveById(m.Id)) { RequestGuid = MessageID; // Gets object type from the message label Type objType = Type.GetType(message.Label.Split('|')[1], true, true); // Derializes object from the stream DataContractSerializer serializer = new DataContractSerializer(objType); return serializer.ReadObject(message.BodyStream); } } } System.Threading.Thread.Sleep(10); } } }
public string enviarPromociones() { string resultado = string.Empty; try { string rutaCola = @".\private$\CitasClinica"; if (!MessageQueue.Exists(rutaCola)) MessageQueue.Create(rutaCola); MessageQueue cola = new MessageQueue(rutaCola); cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Cita) }); foreach (var msj in cola.GetAllMessages()) { Message mensaje = cola.Receive(); Cita citaBE = (Cita)mensaje.Body; enviarCorreo(citaBE); } resultado = "Se envio las promociones OK"; } catch (Exception) { resultado = "No se enviaron las promociones"; } return resultado; }
public string GetElementFromDestination(string pQueuePach) { System.Messaging.Message sourceMessage; string str=""; try { destinationQueue = new System.Messaging.MessageQueue(pQueuePach); ((XmlMessageFormatter)destinationQueue.Formatter).TargetTypeNames = new string[]{"System.String"}; if(destinationQueue.GetAllMessages ().Length >0) { sourceMessage = destinationQueue.Receive(System.Messaging.MessageQueueTransactionType.Automatic); // destinationQueue.Formatter = new XmlMessageFormatter(new Type[] {typeof(String)}); ((XmlMessageFormatter)destinationQueue.Formatter).TargetTypeNames = new string[]{"Empleado"}; str = (string)sourceMessage.Body; } return str; } catch(MessageQueueException e) { throw e; } }
/// <summary> /// 作者:Vincen /// 时间:2013.11.14 PM /// 描述:处理登录日志(消息队列) /// </summary> public static void DoLoginLog() { InitQueue(MsmqType.LoginLog); using (var mq = new MessageQueue(MsmpPath + MsmqType.LoginLog)) { var msgs = mq.GetAllMessages(); foreach (var msg in msgs) { try { msg.Formatter = new XmlMessageFormatter(new[] { typeof(LoginLogs) }); var item = msg.Body as LoginLogs; if (null == item) { continue; } LoginLogsBLL.CreateLoginLogs(item); } //记录下(异常)日志信息 catch (Exception e) { Common.MSMQ.QueueManager.AddExceptionLog(new ExceptionLogs() { ExceptionType = Utility.CommonHelper.To<int>(ExceptionType.Msmq), Message = string.Format("MSMQ-DoLoginLog:{0};{1};{2}", e.Message, e.InnerException.Message, e.HelpLink), IsTreat = false, CreateBy = 0, CreateTime = DateTime.Now }); } } mq.Purge(); } }
public Ubicacion listaUbicacion(string idenvio) { string rutaCola = @".\private$\proyecto"; if (!MessageQueue.Exists(rutaCola)) MessageQueue.Create(rutaCola); MessageQueue cola = new MessageQueue(rutaCola); ///regularizar peidos int x = cola.GetAllMessages().Count(); for (int i = 1; i <= x; i++) { cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Ubicacion) }); Message mensaje = cola.Receive(); Ubicacion nota = (Ubicacion)mensaje.Body; string pedido = ubicacion(nota); } //Ubicacion ubi = tdao.ObtenerUbicacion(idenvio); // //if(ubi==null){ // throw new FaultException("No tiene pedidos en ruta", FaultCode.CreateSenderFaultCode("Fallo", "No tiene pedidos en ruta"),"G"); //} return tdao.ObtenerUbicacion(idenvio); }
public async Task ShouldRemoveSubscriptionsInNonTransactionalMode() { var address = MsmqAddress.Parse("MsmqSubscriptionStorageQueueTests.PersistNonTransactional"); var queuePath = address.PathWithoutPrefix; if (MessageQueue.Exists(queuePath)) { MessageQueue.Delete(queuePath); } MessageQueue.Create(queuePath, false); using (var queue = new MessageQueue(queuePath)) { queue.Send(new Message { Label = "subscriber", Body = typeof(MyMessage).AssemblyQualifiedName }, MessageQueueTransactionType.None); } var storage = new MsmqSubscriptionStorage(new MsmqSubscriptionStorageQueue(address, false)); storage.Init(); await storage.Unsubscribe(new Subscriber("subscriber", "subscriber"), new MessageType(typeof(MyMessage)), new ContextBag()); using (var queue = new MessageQueue(queuePath)) { CollectionAssert.IsEmpty(queue.GetAllMessages()); } }
protected override void OnStart(string[] args) { try { string queueName = ConfigurationManager.AppSettings["ProvisionQueueName"]; //if (!MessageQueue.Exists(queueName))MessageQueue.Create(queueName, true); var queue = new MessageQueue(queueName); Trace.WriteLine("Queue Created in MSMQService at:" + DateTime.Now); //Console.ReadLine(); queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(String) }); //Below code reads from queue once Message[] messages = queue.GetAllMessages(); Trace.WriteLine("Reading from queue in MSMQService : " + queueName); Trace.WriteLine("Number of messages in MSMQService: " + messages.Length); /**foreach (Message msg in messages) { // var decoded = JsonConvert.DeserializeObject(msg.Body.ToString()); Console.WriteLine("message:" + msg.Body); Console.ReadLine(); } Console.WriteLine("End of messages"); Console.ReadLine(); **/ //Below code keeps reading from queue queue.ReceiveCompleted += QueueMessageReceived; queue.BeginReceive(); signal.WaitOne(); //Console.ReadLine(); } catch (Exception e) { Trace.WriteLine("Error in receiving in MSMQService: " + e.Message); } }
private void button1_Click(object sender, EventArgs e) { try { config = new Utils.ReadConfigure().GetConfig(); lblConfig.Text = lblConfig.Text + " OK"; GetCertificado(); lblCertificado.Text = lblCertificado.Text + " OK"; MessageQueue mq = new MessageQueue(@".\Private$\nfce_contingencia", false); lblFila.Text += mq.GetAllMessages().Count(); enviaSeFaz = new EnviaSeFaz.ManagerSeFaz(config, cert); enviaSeFaz.verificaStatusSefaz(); lblStatusSefaz.Text = lblStatusSefaz.Text + " OK"; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
void ISubscriptionStorage.Init() { var path = MsmqUtilities.GetFullPath(Queue); q = new MessageQueue(path); bool transactional; try { transactional = q.Transactional; } catch (Exception ex) { throw new ArgumentException(string.Format("There is a problem with the subscription storage queue {0}. See enclosed exception for details.", Queue), ex); } if (!transactional && TransactionsEnabled) throw new ArgumentException("Queue must be transactional (" + Queue + ")."); var messageReadPropertyFilter = new MessagePropertyFilter { Id = true, Body = true, Label = true }; q.Formatter = new XmlMessageFormatter(new[] { typeof(string) }); q.MessageReadPropertyFilter = messageReadPropertyFilter; foreach (var m in q.GetAllMessages()) { var subscriber = Address.Parse(m.Label); var messageTypeString = m.Body as string; var messageType = new MessageType(messageTypeString); //this will parse both 2.6 and 3.0 type strings entries.Add(new Entry { MessageType = messageType, Subscriber = subscriber }); AddToLookup(subscriber, messageType, m.Id); } }
public ProcessingServiceData GetProcessingServiceData() { if (!System.Messaging.MessageQueue.Exists(_remoteControlQueueName)) { System.Messaging.MessageQueue.Create(_remoteControlQueueName); } using (var remoteControlQueue = new System.Messaging.MessageQueue(_remoteControlQueueName, QueueAccessMode.SendAndReceive)) { remoteControlQueue.Formatter = new XmlMessageFormatter(new[] { typeof(ProcessingServiceData), typeof(RemoteControlCommand) }); var processingServiceDataRequest = new RemoteControlCommand { Code = RemoteControlCommandCode.GetProcessingServiceData }; remoteControlQueue.Send(new Message(processingServiceDataRequest)); do { var processingServiceMessage = remoteControlQueue.GetAllMessages().FirstOrDefault(); var processingServiceData = processingServiceMessage?.Body as ProcessingServiceData; if (processingServiceData == null) { Thread.Sleep(_callDelay); continue; } remoteControlQueue.Receive(); return(processingServiceData); } while (true); } }
public string GetElementFromSource(string pQueuePach) { System.Messaging.Message sourceMessage; string str = ""; try { sourceQueue = new System.Messaging.MessageQueue(pQueuePach); ((XmlMessageFormatter)sourceQueue.Formatter).TargetTypeNames = new string[] { "System.String" }; if (sourceQueue.GetAllMessages().Length > 0) { sourceMessage = sourceQueue.Receive(System.Messaging.MessageQueueTransactionType.Automatic); // Set the formatter. // sourceQueue.Formatter = new XmlMessageFormatter(new Type[] {typeof(String)}); ((XmlMessageFormatter)sourceQueue.Formatter).TargetTypeNames = new string[] { "Empleado" }; str = (string)sourceMessage.Body; } return(str); } catch (MessageQueueException e) { throw e; } catch (Exception e) { throw e; } }
static void Main(string[] args) { cmdLine = args; var timeOfMigration = DateTime.UtcNow; var storage = GetSetting("-storageQueue"); var inputStorageQueue = Address.Parse(storage); var destination = GetSetting("-destination"); newTimeoutManagerAddress = Address.Parse(destination); var minAge = GetSetting("-migrateOlderThan"); var minAgeOfTimeouts = TimeSpan.MinValue; if (!string.IsNullOrEmpty(minAge)) minAgeOfTimeouts = TimeSpan.Parse(minAge); bus = Configure.With() .DefaultBuilder() .XmlSerializer() .MsmqTransport() .UnicastBus() .SendOnly(); var path = MsmqUtilities.GetFullPath(inputStorageQueue); storageQueue = new MessageQueue(path) { MessageReadPropertyFilter = { LookupId = true } }; if (!storageQueue.Transactional) throw new Exception(inputStorageQueue + " must be transactional."); storageQueue.Formatter = new XmlMessageFormatter(new[] { typeof(TimeoutData) }); Console.WriteLine(string.Format("Parsing {0} to find timeouts to migrate", inputStorageQueue)); storageQueue.GetAllMessages().ToList().ForEach( m => { var timeoutData = m.Body as TimeoutData; if (timeoutData == null) //get rid of message throw new InvalidOperationException("Failed to parse timeout data with id " + m.Id); if (minAgeOfTimeouts != TimeSpan.MinValue && timeoutData.Time < (timeOfMigration + minAgeOfTimeouts)) { Console.WriteLine(string.Format("Timeout {0} has a expiry ({1}) less than the configured min age of {2} and will be ignored", m.Id, timeoutData.Time, minAgeOfTimeouts)); return; } timeoutsToBeMigrated.Add(new Tuple<TimeoutData, string>(timeoutData, m.Id)); }); Console.WriteLine(string.Format("{0} parsed, {1} timeouts found that will be migrated", inputStorageQueue, timeoutsToBeMigrated.Count())); timeoutsToBeMigrated.ForEach(t => MigrateMessage(t.Item1, t.Item2)); Console.WriteLine(string.Format("Migration completed successfully")); }
public List<Cliente> ListarTodos() { //***************Antes de listar Inserta a todos los clientes ENCOLADOS string rutaCola = @".\private$\RegistroClientes"; if (!MessageQueue.Exists(rutaCola)) MessageQueue.Create(rutaCola); MessageQueue cola = new MessageQueue(rutaCola); int cantidad = cola.GetAllMessages().Length; cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Cliente) }); Message mensaje = null; for (int i = 0; i < cantidad; i++) { mensaje = cola.Receive(); Cliente p = (Cliente)mensaje.Body; //insertar a la DB clientes encolados string sql2 = "insert into Cliente (NombreCliente, ApellidoCliente, DNI, CorreoCliente ) " + "values (@nomCli, @apeCli, @dniCli, @correoCli)"; using (SqlConnection con = new SqlConnection(ConexionUtil.Cadena)) { con.Open(); using (SqlCommand com = new SqlCommand(sql2, con)) { com.Parameters.Add(new SqlParameter("@nomCli", p.NombreCliente)); com.Parameters.Add(new SqlParameter("@apeCli", p.ApellidoCliente)); com.Parameters.Add(new SqlParameter("@dniCli", p.DNI)); com.Parameters.Add(new SqlParameter("@correoCli", p.CorreoCliente)); com.ExecuteNonQuery(); } } } //*************** List<Cliente> clientesEncontrado = null; clientesEncontrado = new List<Cliente>(); string sql = "select NombreCliente, ApellidoCliente, DNI, CorreoCliente from cliente"; using (SqlConnection con = new SqlConnection(ConexionUtil.Cadena)) { con.Open(); using (SqlCommand com = new SqlCommand(sql, con)) { using (SqlDataReader resultado = com.ExecuteReader()) { while (resultado.Read()) { Cliente clienteEncontrado = new Cliente() { NombreCliente = (string)resultado["NombreCliente"], ApellidoCliente = (string)resultado["ApellidoCliente"], DNI = (string)resultado["DNI"], CorreoCliente = (string)resultado["CorreoCliente"], }; clientesEncontrado.Add(clienteEncontrado); } } } } return clientesEncontrado; }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void TimerElapsed(object sender, ElapsedEventArgs args) { var messages = _underlyingQueue.GetAllMessages(); if (messages.Any()) { OnNewMessagesFound(messages.Select(GetMessagePayload)); } }
public void TestSendMessage() { Service service = new Service(); using (ServicePublisher publisher = new ServicePublisher()) { publisher.Send(service); } MessageQueue mq = new MessageQueue(@".\Private$\IQ1"); Message[] messages = mq.GetAllMessages(); mq.Purge(); Assert.AreEqual(1, messages.Length); }
public void setData(MessageQueue mq) { this.tblQueues.Items.Clear(); System.Messaging.Message[] messages = mq.GetAllMessages(); for (int i = 0; i < messages.Length; i++) { String[] queueItem = new String[] { i + "", messages[i].Label }; this.tblQueues.Items.Add(new ListViewItem(queueItem)); } }
//Actualizacion de los expedientes public String Actualizar() { String mensajeFinal = ""; /* 1. Regulizar expedientes*/ string rutaCola = @".\private$\evaluacionXhora"; if (!MessageQueue.Exists(rutaCola)) MessageQueue.Create(rutaCola); MessageQueue cola = new MessageQueue(rutaCola); cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Expediente) }); while (cola.GetAllMessages().Count() != 0) { Message mensaje = cola.Receive(); Expediente expedienteItem = (Expediente)mensaje.Body; string postdata = "{" + "\"codigo\":" + expedienteItem.codigo + "," + "\"codigoSolicitante\":" + expedienteItem.codigoSolicitante + "," + "\"codigoTramite\":" + expedienteItem.codigoTramite + "," + "\"Estado\":" + expedienteItem.Estado + "}"; byte[] data = Encoding.UTF8.GetBytes(postdata); HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:7966/Evaluacion.svc/Evaluacion"); req.Method = "PUT"; req.ContentLength = data.Length; req.ContentType = "application/json"; var reqStream = req.GetRequestStream(); reqStream.Write(data, 0, data.Length); HttpWebResponse res = null; try { res = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(res.GetResponseStream()); string pedidoJson = reader.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); Expediente pedidoCreado = js.Deserialize<Expediente>(pedidoJson); mensajeFinal = ""; } catch (WebException e) { HttpStatusCode code = ((HttpWebResponse)e.Response).StatusCode; string message = ((HttpWebResponse)e.Response).StatusDescription; StreamReader reader = new StreamReader(e.Response.GetResponseStream()); string error = reader.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); string msjError = js.Deserialize<string>(error); mensajeFinal = msjError; break; } } return mensajeFinal; }
private static void ClearSubscriptionStorage(string subscriptionStorageQueue, string pluginInputQueue) { var fullName = MsmqUtilities.GetFullPathWithoutPrefix(subscriptionStorageQueue); if (!MessageQueue.Exists(fullName)) return; var queue = new MessageQueue(fullName); foreach (var message in queue.GetAllMessages()) { if (message.Label.ToLower().Contains(pluginInputQueue.ToLower())) { queue.ReceiveById(message.Id); } } Console.WriteLine("SubscriptionStorage queue {0} successfully cleared", subscriptionStorageQueue); }
static void Main(string[] args) { string queueName = ConfigurationManager.AppSettings["MSMQLocation"]; if (args.Count() != 4) { Console.WriteLine("needs 4 params: sourcedir sourcefiletypes dstdir dstfileformat"); return; } try { MessageQueue rmTxnQ = new MessageQueue(queueName); rmTxnQ.Formatter = new XmlMessageFormatter(new Type[] { typeof(ProcessMessage) }); string[] files = Directory.GetFiles(args[0], args[1], SearchOption.AllDirectories); int count = 0; foreach (string s in files) { MessageQueueTransaction msgTx = new MessageQueueTransaction(); msgTx.Begin(); try { string argument = "-i \"{0}\" -o \"{1}\" --preset \"" + ConfigurationManager.AppSettings["HandbrakePreset"] + "\""; string destination = args[2] + "\\" + Path.GetFileNameWithoutExtension(s) + args[3]; ProcessMessage p = new ProcessMessage() { CommandLine = argument, DestinationUrl = destination, OrignalFileUrl = s }; rmTxnQ.Send(p, msgTx); Console.WriteLine("Adding message for {0} to queue", s); count++; msgTx.Commit(); } catch (Exception ex) { Console.WriteLine(ex.Message); msgTx.Abort(); } } Console.WriteLine("added {0} items to queue. Queue count now {1}", count, rmTxnQ.GetAllMessages().Count()); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public MessageInfo GetAllMessage(StructuredQueue oQueueTemp, int myID, int MaxQuery) { MessageInfo MyInfo = new MessageInfo(); try { Message[] messages = null; MessageQueue MessageInQueue = new System.Messaging.MessageQueue(oQueueTemp.sPath, QueueAccessMode.SendAndReceive); // MessageInQueue.MessageReadPropertyFilter.SetAll(); MessageInQueue.MessageReadPropertyFilter.Id = true; MessageInQueue.MessageReadPropertyFilter.Priority = true; MessageInQueue.MessageReadPropertyFilter.SentTime = true; MessageInQueue.MessageReadPropertyFilter.MessageType = true; MessageInQueue.MessageReadPropertyFilter.Label = true; MessageInQueue.MessageReadPropertyFilter.Body = true; Application.DoEvents(); messages = MessageInQueue.GetAllMessages(); Application.DoEvents(); ArrayList MyMessage = new ArrayList(); // MyInfo.ID = MessageInQueue.GetAllMessages().Length; MyInfo.ID = messages.Length; for (int index = 0; index < messages.Length; index++) { Application.DoEvents(); if (index >= MaxQuery) { break; } QueueInfos QueueInfo = new QueueInfos(); QueueInfo.ID = messages[index].Id; QueueInfo.SentTime = messages[index].SentTime.ToString(); QueueInfo.Body = ReadMessageStream(messages[index].BodyStream); QueueInfo.Label = messages[index].Label; QueueInfo.Priority = messages[index].Priority.ToString(); QueueInfo.MessageID = index.ToString(); QueueInfo.Transact = oQueueTemp.bTransactional; QueueInfo.Queue = oQueueTemp.sQueueName; MyMessage.Add(QueueInfo); } MyInfo.Message = MyMessage; } catch { } return(MyInfo); }
/// <summary> /// Timer Event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void timer_Elapsed(object sender, ElapsedEventArgs e) { try { if (queue.GetAllMessages().Length > 0) { timer.Enabled = false; QueueMail(); timer.Enabled = true;//to start the time after completion of process } } catch (Exception ex) { log.SaveError(VAdvantage.Utility.Msg.GetMsg(Env.GetContext(), "QueueError", true), ex); timer.Enabled = false; } }
protected override void ProcessRecord() { var queueAddress = string.Format("FormatName:DIRECT=OS:{0}\\private$\\{1}", Environment.MachineName,QueueName); var queue = new MessageQueue(queueAddress); var messageReadPropertyFilter = new MessagePropertyFilter {Id = true, Extension = true, ArrivedTime = true}; queue.MessageReadPropertyFilter = messageReadPropertyFilter; var output = queue.GetAllMessages().Select(m => new { m.Id, Headers = ParseHeaders(m), m.ArrivedTime }); WriteObject(output, true); }
public static void Main(string[] args) { string strRutaCola = @".\private$\Sucamec"; if (!MessageQueue.Exists(strRutaCola)) MessageQueue.Create(strRutaCola); MessageQueue cola = new MessageQueue(strRutaCola); cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(EntidadLicencia) }); Message[] mensajes = cola.GetAllMessages(); for (int i = 0; i < mensajes.Length; i++) { EntidadLicencia licencia = (EntidadLicencia)mensajes[i].Body; //Envia datos a la Tienda a traves del Servicio Web ServicioTienda.TiendaClient objServicio = new ServicioTienda.TiendaClient(); objServicio.RecibeSucamec(licencia.intCodSolicitud, licencia.intEstadoLicencia, licencia.strFechaRespuesta, licencia.intCodSucamec, licencia.strNumeroLicencia, licencia.strEstadoAntecedentePolicial, licencia.strEstadoAntecedenteJudicial, licencia.strEstadoAntecedentePenal); Console.WriteLine("Asunto: " + mensajes[i].Label); Console.WriteLine("Estado: " + licencia.intEstadoLicencia + ", Fecha de respuesta: " + licencia.strFechaRespuesta + ", Codigo Sucamec: " + licencia.intCodSucamec + ", Código Solicitud: " + licencia.intCodSolicitud + ", Número Licencia: " + licencia.strNumeroLicencia); Console.ReadLine(); } cola.Purge(); //Message mensaje = cola.Receive(); //EntidadLicencia licencia = (EntidadLicencia)mensaje.Body; //Envia datos a la Tienda a traves del Servicio Web //ServicioTienda.TiendaClient objServicio = new ServicioTienda.TiendaClient(); //objServicio.RecibeSucamec(licencia.intCodSolicitud, licencia.intEstadoLicencia, licencia.strFechaRespuesta, // licencia.intCodSucamec, licencia.strNumeroLicencia); //Console.WriteLine("Asunto: " + mensaje.Label); //Console.WriteLine("Estado: " + licencia.intEstadoLicencia + ", Fecha de respuesta: " + // licencia.strFechaRespuesta + ", Codigo Sucamec: " + licencia.intCodSucamec + // ", Código Solicitud: " + licencia.intCodSolicitud + ", Número Licencia: " + // licencia.strNumeroLicencia); //Console.ReadLine(); }
private void ProcessingServiceCommandsMonitor(CancellationToken cancToken) { using (var remoteControlQueue = new System.Messaging.MessageQueue(_remoteControlQueueName, QueueAccessMode.SendAndReceive)) { remoteControlQueue.Formatter = new XmlMessageFormatter(new[] { typeof(ProcessingServiceSettings), typeof(RemoteControlCommand), typeof(ProcessingServiceSettingsCommand), typeof(ProcessingServiceData), typeof(RemoteControlResult) }); do { var processingServiceMessage = remoteControlQueue.GetAllMessages().FirstOrDefault(); var settingsCommand = processingServiceMessage?.Body as ProcessingServiceSettingsCommand; if (settingsCommand != null) { remoteControlQueue.Receive(); var settings = settingsCommand.Settings; var result = new RemoteControlResult(); try { OnProcessingServiceSettingsChanged?.Invoke(settings); result.Code = RemoteControlResultCode.Success; } catch (Exception e) { result.Code = RemoteControlResultCode.Error; result.Message = e.Message; } remoteControlQueue.Send(new Message(result)); continue; } var command = processingServiceMessage?.Body as RemoteControlCommand; if (command != null) { remoteControlQueue.Receive(); var data = _processingServiceDataProvider(); remoteControlQueue.Send(new Message(data)); continue; } Thread.Sleep(_callDelay); } while (!cancToken.IsCancellationRequested); } }
public static void StartProcessing() { string queuePath = @".\private$\BroccoliEmails"; QueueService.InsureQueueExists(queuePath); msgQ = new MessageQueue(queuePath); msgQ.Formatter = new BinaryMessageFormatter(); msgQ.MessageReadPropertyFilter.SetAll(); var messages = msgQ.GetAllMessages(); foreach (var message in messages) { var msg = (EmailMessage) message.Body; msgQ_Send(msg); } msgQ.Close(); }
// // GET: /Payment/ public ActionResult Index() { IDictionary<PaymentModel, string> model = new Dictionary<PaymentModel, string>(); if (MessageQueue.Exists(".\\Private$\\easyTravelPaymentQueue")) { using (MessageQueue mq = new MessageQueue(".\\Private$\\easyTravelPaymentQueue")) { //mq.Formatter = new XmlMessageFormatter(); ((XmlMessageFormatter)mq.Formatter).TargetTypes = new Type[] { typeof(PaymentModel) }; Cursor c = mq.CreateCursor(); Message[] msgs = mq.GetAllMessages(); if (msgs != null) { foreach (Message m in msgs) { model.Add((PaymentModel)m.Body, m.Label); } } } } else { log.Warn("Queue \".\\Private$\\easyTravelPaymentQueue\" does not exist"); } return View(model); }
public static int GetMessageQueueCount(string queue) { string mqName = CreateMessageQueueName(queue); if (!MessageQueue.Exists(mqName)) { MessageQueue.Create(mqName, true); return 0; } else { int ret = 0; using (MessageQueue mq = new MessageQueue(mqName, false, false, QueueAccessMode.SendAndReceive)) { ret = mq.GetAllMessages().Length; mq.Close(); } return ret; } }
public List<Prestamo> Recibir(string ruta) { List<Prestamo> lista = new List<Prestamo>(); Prestamo prestamo = null; if (!MessageQueue.Exists(ruta)) { MessageQueue.Create(ruta); } MessageQueue cola = new MessageQueue(ruta); cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Prestamo) }); Message[] mensajes = cola.GetAllMessages(); foreach (var item in mensajes) { prestamo = (Prestamo)item.Body; lista.Add(prestamo); } return lista; }
public static Message[] GetAllMessages(string queue) { string mqName = CreateMessageQueueName(queue); if (!MessageQueue.Exists(mqName)) { MessageQueue.Create(mqName, true); return null; } else { Message[] ret = null; using (MessageQueue mq = new MessageQueue(mqName, false, false, QueueAccessMode.SendAndReceive)) { ret = mq.GetAllMessages(); mq.Close(); } return ret; } }
public Prestamo CrearPrestamo(Prestamo prestamoACrear) { string rutaCola = @".\private$\prestamospendientes"; if (!MessageQueue.Exists(rutaCola)) MessageQueue.Create(rutaCola); MessageQueue cola = new MessageQueue(rutaCola); cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(Prestamo) }); int cuenta = cola.GetAllMessages().Count(); if (cuenta != 0) { for (int i = 1; i <= cuenta; i++) { Message mensaje = cola.Receive(); Prestamo nota = (Prestamo)mensaje.Body; } } return PrestamoDAO.Crear(prestamoACrear); }
public List<EComentario> ListarNotificaciones(int CodigoUsuario) { List<EComentario> listaNotificaciones = new List<EComentario>(); string rutaCola = @".\private$\" + CodigoUsuario.ToString(); if (!MessageQueue.Exists(rutaCola)) MessageQueue.Create(rutaCola); MessageQueue cola = new MessageQueue(rutaCola); cola.Formatter = new XmlMessageFormatter(new Type[] { typeof(EComentario) }); while (cola.GetAllMessages().Count() != 0) { Message mensaje = cola.Receive(); EComentario comentarioItem = (EComentario)mensaje.Body; listaNotificaciones.Add(comentarioItem); } return listaNotificaciones; }
private void RestorePreviousSession() { if (!System.Messaging.MessageQueue.Exists(_queuesQueueName)) { System.Messaging.MessageQueue.Create(_queuesQueueName); } using (var queuesQueue = new System.Messaging.MessageQueue(_queuesQueueName, QueueAccessMode.Receive)) { queuesQueue.Formatter = new XmlMessageFormatter(new[] { typeof(AgentQueue) }); var agentQueues = queuesQueue.GetAllMessages().Select(x => x.Body as AgentQueue); foreach (var agentQqueue in agentQueues) { if (agentQqueue == null) { continue; } lock (_sequances) { if (!_sequances.ContainsKey(agentQqueue.AgentId)) { var newSequance = new Sequance(agentQqueue.AgentId, _sequanceTime, _cancelationSource.Token); newSequance.OnSequanceCompleted += SequanceProcess; _sequances.Add(agentQqueue.AgentId, newSequance); if (!System.Messaging.MessageQueue.Exists(agentQqueue.QueueName)) { System.Messaging.MessageQueue.Create(agentQqueue.QueueName); } } _sequances[agentQqueue.AgentId].UpdateSequanceState(); } } } }
public void SetProcessingServiceSettings(ProcessingServiceSettings processingServiceSettings) { using (var remoteControlQueue = new System.Messaging.MessageQueue(_remoteControlQueueName, QueueAccessMode.SendAndReceive)) { remoteControlQueue.Formatter = new XmlMessageFormatter(new[] { typeof(RemoteControlResult), typeof(ProcessingServiceSettingsCommand) }); var processingServiceDataRequest = new ProcessingServiceSettingsCommand { Settings = processingServiceSettings }; remoteControlQueue.Send(new Message(processingServiceDataRequest)); do { var processingServiceMessage = remoteControlQueue.GetAllMessages().FirstOrDefault(); var result = processingServiceMessage?.Body as RemoteControlResult; if (result == null) { Thread.Sleep(_callDelay); continue; } if (result.Code == RemoteControlResultCode.Error) { MessageBox.Show($"Settings weren't applied...\n\"{result.Message}\"", "MSMQ communication", MessageBoxButton.OK, MessageBoxImage.Error); } if (result.Code == RemoteControlResultCode.Success) { MessageBox.Show("Settings were successfully applied!"); } remoteControlQueue.Receive(); return; } while (true); } }