Ejemplo n.º 1
0
        private static T ReadMessage <T>(string queueAddress, ConsoleColor color = ConsoleColor.Gray) where T : UnSubscriberInfo
        {
            T result = default(T);

            using (var mq = new System.Messaging.MessageQueue(queueAddress))
            {
                ConsoleHelper.WriteLine(color, $"Waiting for new {(typeof(T) == typeof(SubscriberInfo) ? "Subscriber" : "Unsubscriber")}...");

                var message = mq.Receive();
                if (message != null)
                {
                    var msgBodyStream = new StreamReader(message.BodyStream);
                    var msgBody       = JsonConvertor.ReadObject <T>(msgBodyStream);

                    if (typeof(T) == typeof(SubscriberInfo))
                    {
                        var subscriber = (SubscriberInfo)(object)msgBody;// dirty casting
                        ConsoleHelper.WriteLine(color, "New Subscriber with below info:");
                        ConsoleHelper.WriteLine(color, $"\t\tFirstName: {subscriber.FirstName}");
                        ConsoleHelper.WriteLine(color, $"\t\tLastName: {subscriber.LastName}");
                        ConsoleHelper.WriteLine(color, $"\t\tEmailAddress: {subscriber.EmailAddress}");
                    }
                    else
                    {
                        var unsubscriber = (UnSubscriberInfo)msgBody;
                        ConsoleHelper.WriteLine(color, "New UnSubscriber with below info:");
                        ConsoleHelper.WriteLine(color, $"\t\tEmailAddress: {unsubscriber.EmailAddress}");
                    }

                    result = msgBody;
                }
            }
            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <remarks>In real life this is going to be a windows service or other type of background operating instance that monitors incomming
        /// messages.
        /// Once message is received the handler resumes corresponding flow execution</remarks>
        /// <param name="args">The arguments.</param>
        private static void Main(string[] args)
        {
            var consoleTracer = new ConsoleTraceListener(true);
            Trace.Listeners.Add(consoleTracer);

            using (var queue = new System.Messaging.MessageQueue(@".\private$\tbms.callbackqueue"))
            {
                while (true)
                {
                    Console.WriteLine("Listening...");
                    var message = queue.Receive();

                    var bodyReader = new StreamReader(message.BodyStream);
                    var body = bodyReader.ReadToEnd();

                    var messageBody = (JObject)JsonConvert.DeserializeObject(body);

                    var flowId = messageBody["flowId"].Value<int>();

                    var flow = DeserializeFlow(flowId);

                    flow?.Resume();
                }
            }
        }
Ejemplo n.º 3
0
        public void MsmqLogWriter_Write_WritesEnumerableBatchToQueue()
        {
            if (System.Messaging.MessageQueue.Exists(_TestQueuePath))
            {
                System.Messaging.MessageQueue.Delete(_TestQueuePath);
            }

            if (!System.Messaging.MessageQueue.Exists(_TestQueuePath))
            {
                System.Messaging.MessageQueue.Create(_TestQueuePath, false);
            }

            using (var writeQueue = new System.Messaging.MessageQueue(_TestQueuePath, false, true, System.Messaging.QueueAccessMode.Send))
            {
                writeQueue.Formatter = new MsmqJsonLogEventMessageFormatter();

                var writer = new MsmqLogWriter(writeQueue);

                using (var readQueue = new System.Messaging.MessageQueue(_TestQueuePath, false, true, System.Messaging.QueueAccessMode.SendAndReceive))
                {
                    readQueue.Formatter = new MsmqJsonLogEventMessageFormatter();

                    var logEvents = new List <LogEvent>(2);
                    logEvents.Add(new LogEvent()
                    {
                        EventName = "Test Event",
                        Source    = "Test Source"
                    });
                    logEvents.Add(new LogEvent()
                    {
                        EventName = "Test Event 2",
                        Source    = "Test Source"
                    });
                    writer.WriteBatch(logEvents);

                    var result = readQueue.Receive(TimeSpan.FromSeconds(5));
                    Assert.IsNotNull(result);

                    var results = Newtonsoft.Json.JsonConvert.DeserializeObject <LogEvent[]>(result.Body.ToString());
                    Assert.AreEqual(2, results.Length);
                    Assert.AreEqual("Test Event", results[0].EventName);
                    Assert.AreEqual("Test Event 2", results[1].EventName);
                }
            }
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            using (var queue = new System.Messaging.MessageQueue(@".\private$\email-unsubscribe"))
            {
                while (true)
                {
                    //System.Environment.Exit(-1);
                    Console.WriteLine("Listening:");

                    var message = queue.Receive();

                    var bodyReader = new StreamReader(message.BodyStream);
                    var jsonBody   = bodyReader.ReadToEnd();

                    var unsubscribeMessage = JsonConvert.DeserializeObject <UnsubscribeMessage>(jsonBody);

                    Console.WriteLine($"Message received & processed {unsubscribeMessage.Email}");
                }
            }
        }
Ejemplo n.º 5
0
        public void MsmqLogWriter_Write_WritesToQueue()
        {
            if (System.Messaging.MessageQueue.Exists(_TestQueuePath))
            {
                System.Messaging.MessageQueue.Delete(_TestQueuePath);
            }

            if (!System.Messaging.MessageQueue.Exists(_TestQueuePath))
            {
                System.Messaging.MessageQueue.Create(_TestQueuePath, false);
            }

            using (var writeQueue = new System.Messaging.MessageQueue(_TestQueuePath, false, true, System.Messaging.QueueAccessMode.Send))
            {
                writeQueue.Formatter = new MsmqXmlLogEventMessageFormatter();

                var writer = new MsmqLogWriter(writeQueue);

                using (var readQueue = new System.Messaging.MessageQueue(_TestQueuePath, false, true, System.Messaging.QueueAccessMode.SendAndReceive))
                {
                    readQueue.Formatter = new MsmqXmlLogEventMessageFormatter();

                    var logEvent = new LogEvent()
                    {
                        EventName = "Test Event",
                        Source    = "Test Source"
                    };
                    writer.Write(logEvent);

                    var result = readQueue.Receive(TimeSpan.FromSeconds(5));
                    Assert.IsNotNull(result);
                    var xdoc = System.Xml.Linq.XDocument.Parse(result.Body.ToString());
                    Assert.IsNotNull((from n in xdoc.Descendants("LogEvent") select n).FirstOrDefault());
                }
            }
        }
Ejemplo n.º 6
0
        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lock (msgQueue)
            {
                try
                {
                    msg           = msgQueue.Receive(new TimeSpan(0, 0, 3));
                    msg.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(objMensaje), typeof(Eventos) });
                    objM          = (objMensaje)msg.Body;

                    DOMDocument Xml     = new DOMDocument();
                    bool        exitoso = Xml.loadXML(objM._Input);

                    if (exitoso)
                    {
                        IXMLDOMElement root = Xml.documentElement;
                        // primer parámetro : cod_workflow - segundo parámetro : str_referencia
                        DataSet ds            = SqlHelper.ExecuteDataset(WinflowAC.ConnectionString.FormarStringConexion(), Queries.WF_ConsultarSolicitud, int.Parse(root.childNodes[0].text), root.childNodes[1].text);
                        int     nRows         = ds.Tables[0].Rows.Count;
                        int     intCodCreador = 0;

                        //+ Nuevo
                        int    intNumPosAct   = 0;
                        int    intCodWF       = 0;
                        string strNumRef      = string.Empty;
                        string strDescRuta    = string.Empty;
                        int    intEstatusWF   = 0;
                        int    intEstatusDoc  = 0;
                        string strPrevXml     = string.Empty;
                        string strXml         = string.Empty;
                        int    intCodEmpDesde = 0;
                        int    intCodEmpHasta = 0;
                        bool   blnActual      = false;
                        int    intIndexActual = 0;
                        //+

                        string strPrev = string.Empty;
                        if (objM._Evento == Eventos.CREAR_SOLICITUD && nRows == 0)
                        {
                            CreateStateMachine(int.Parse(root.childNodes[0].text), root.childNodes[1].text, int.Parse(root.childNodes[2].text), root.childNodes[4].text);
                        }
                        else
                        {
                            SolicitudActual = Convert.ToInt32(ds.Tables[0].Rows[0]["swf_cod_solicitud"]);
                            try
                            {
                                intCodCreador = Convert.ToInt32(ds.Tables[0].Rows[0]["hwf_cod_empleado_origen"]);
                                strPrev       = Convert.ToString(ds.Tables[0].Rows[0]["hwf_str_prevxmldata"]);
                            }
                            catch (Exception ee)
                            {
                                intCodCreador = 0;
                                strPrev       = string.Empty;
                                System.Console.Write(ee.Message);
                            }
                        }

                        IEnumerator arrayList = array.GetEnumerator();
                        if (objM._Evento == Eventos.CAMBIO_DE_DESTINATARIO)
                        {
                            //* Antes

                            /*
                             * bool blnActualCD=false;
                             * int intIndexActualCD=0;
                             * while ( arrayList.MoveNext() )
                             * {
                             *      blnActualCD=((StateMachine)arrayList.Current).Check(SolicitudActual);
                             *      intIndexActualCD++;
                             *      if(blnActualCD)
                             *              break;
                             *
                             * }
                             */
                            //*
                            ((StateProcSmpl)arrayList.Current).ActualizarAprobador(int.Parse(root.childNodes[2].text), SolicitudActual);
                            ((StateMachine)arrayList.Current).Check(SolicitudActual, objM._Evento, objM._Input);

//							array.RemoveAt(intIndexActual-1);
//							StateMachine sMach = new StateProcSmpl(SolicitudActual,int.Parse(root.childNodes[0].text),root.childNodes[1].text,StateConst.ESPERAR_CORRECCION,root.childNodes[4].text,1,intCodCreador,strPrev);
//							array.Add(sMach);
//							sMach.Check(SolicitudActual,objM._Evento,objM._Input);
                        }
                        else
                        {
                            if (objM._Evento == Eventos.SOLICITUD_CORREGIDA)
                            {
                                blnActual      = false;
                                intIndexActual = 0;
                                while (arrayList.MoveNext())
                                {
                                    blnActual = ((StateMachine)arrayList.Current).Check(SolicitudActual);
                                    intIndexActual++;
                                    if (blnActual)
                                    {
                                        break;
                                    }
                                }
                                array.RemoveAt(intIndexActual - 1);
                                StateMachine sMach = new StateProcSmpl(SolicitudActual, int.Parse(root.childNodes[0].text), root.childNodes[1].text, StateConst.ESPERAR_CORRECCION, root.childNodes[4].text, 1, intCodCreador, strPrev);
                                array.Add(sMach);
                                // *Anterior
                                //sMach.Check(SolicitudActual,objM._Evento,objM._Input);
                            }
                            // +Nuevo
                            if ((objM._Evento == Eventos.SOLICITUD_APROBADA) ||
                                (objM._Evento == Eventos.RECHAZADO_PARCIAL) ||
                                (objM._Evento == Eventos.RECHAZADO_TOTAL))
                            {
                                //+ Nuevo
                                intNumPosAct   = Convert.ToInt32(ds.Tables[0].Rows[0]["swf_num_posicion_actual"]);
                                intCodWF       = Convert.ToInt32(ds.Tables[0].Rows[0]["swf_cod_workflow"]);
                                strNumRef      = Convert.ToString(ds.Tables[0].Rows[0]["swf_str_referencia"]);
                                strDescRuta    = Convert.ToString(ds.Tables[0].Rows[0]["swf_desc_ruta"]);
                                intEstatusWF   = Convert.ToInt32(ds.Tables[0].Rows[0]["hwf_cod_estatuswkf"]);
                                intEstatusDoc  = Convert.ToInt32(ds.Tables[0].Rows[0]["hwf_cod_estatusdoc"]);
                                strPrevXml     = Convert.ToString(ds.Tables[0].Rows[0]["hwf_str_prevxmldata"]);
                                strXml         = Convert.ToString(ds.Tables[0].Rows[0]["hwf_str_xmldata"]);
                                intCodEmpDesde = Convert.ToInt32(ds.Tables[0].Rows[0]["hwf_cod_empleado_origen"]);
                                intCodEmpHasta = Convert.ToInt32(ds.Tables[0].Rows[0]["hwf_cod_empleado_destino"]);
                                intCodCreador  = Convert.ToInt32(ds.Tables[0].Rows[0]["swf_cod_empleado_creador"]);
                                //+

                                blnActual      = false;
                                intIndexActual = 0;
                                while (arrayList.MoveNext())
                                {
                                    blnActual = ((StateMachine)arrayList.Current).Check(SolicitudActual);
                                    intIndexActual++;
                                    if (blnActual)
                                    {
                                        break;
                                    }
                                }
                                if (blnActual)
                                {
                                    array.RemoveAt(intIndexActual - 1);
                                }

                                StateMachine sMach = new StateProcSmpl((int)SolicitudActual, intCodWF, strNumRef, intEstatusWF, intEstatusDoc, strDescRuta, intNumPosAct, strPrevXml, strXml, intCodCreador, intCodEmpDesde, intCodEmpHasta);
                                array.Add(sMach);
                            }
                            // +
                            //*else
                            //*{
                            arrayList = array.GetEnumerator();
                            while (arrayList.MoveNext())
                            {
                                ((StateMachine)arrayList.Current).Check(SolicitudActual, objM._Evento, objM._Input);
                            }
                            //*}
                        }
                    }
                }
                catch
                {
                    //arrayList = array.GetEnumerator();
                    EstadoActual = StateConst.INICIO;

                    //while ( arrayList.MoveNext() )
                    //{
                    //    ((StateMachine)arrayList.Current).Check();
                    //    EstadoActual = ((StateMachine)arrayList.Current).EstadoActual;
                    //    if(EstadoActual == StateConst.FIN)
                    //    {
                    //        array.Remove(arrayList.Current);
                    //    }
                    //}

                    int i = 0, count = array.Count;
                    while (i < count)
                    {
                        ((StateMachine)array[i]).Check();
                        EstadoActual = ((StateMachine)array[i]).EstadoActual;
                        if (EstadoActual == StateConst.FIN)
                        {
                            array.RemoveAt(i);
                            count--;
                        }
                        else
                        {
                            i++;
                        }
                    }

                    arrayList = array.GetEnumerator();
                }                 // end catch
            }
        }
Ejemplo n.º 7
0
        private void StartSystem(object sender, DoWorkEventArgs e)
        {
            Bot.OnCallbackQuery += BotOnCallbackQueryReceived;
            //Bot.OnInlineQuery += BotOnInlineQueryReceived;
            Bot.OnInlineResultChosen += BotOnChosenInlineResultReceived;
            Bot.OnReceiveError       += BotOnReceiveError;
            Bot.OnMessage            += BotOnMessageReceived;

            Bot.StartReceiving();


            System.Messaging.MessageQueue msgQ = new System.Messaging.MessageQueue(".\\Private$\\botshoppayment");


            EventLog.WriteEntry("BotHandler", "Queue intialized", EventLogEntryType.Warning, 240);


            Access.Queue_Payment pm_input = new Access.Queue_Payment();
            Object o = new Object();

            Type[] arrTypes = new Type[2];
            arrTypes[0]    = pm_input.GetType();
            arrTypes[1]    = o.GetType();
            msgQ.Formatter = new System.Messaging.XmlMessageFormatter(arrTypes);

            while (_Die == false)
            {
                try
                {
                    EventLog.WriteEntry("BotHandler", "Listener intialized", EventLogEntryType.Warning, 241);

                    pm_input = (Queue_Payment)msgQ.Receive().Body;

                    EventLog.WriteEntry("BotHandler", "Item receieved", EventLogEntryType.Warning, 242);

                    if (pm_input.Store != ConfigurationManager.AppSettings["StoreName"])
                    {
                        string sSource = "BotHandler";

                        EventLog.WriteEntry(sSource, "Item return to queue", EventLogEntryType.Warning, 234);

                        System.Messaging.Message msg = new System.Messaging.Message();
                        msg.Body = pm_input;
                        msgQ.Send(msg);
                        continue;
                    }
                    else
                    {
                        try
                        {
                            EventLog.WriteEntry("BotHandler", "Item handled", EventLogEntryType.Warning, 243);

                            using (Access.GoldoonEntities db = new Access.GoldoonEntities())
                            {
                                var _getOrder = db.Orders.Where(a => a.Id == pm_input.OrderId).FirstOrDefault();
                                if (_getOrder != null)
                                {
                                    _getOrder.Status        = Logic.Utilities.EnumStatus.Paid;
                                    _getOrder.Paymetn_Refid = pm_input.RefId;

                                    db.SaveChanges();

                                    var _getCart = db.Carts.Where(a => a.User_Id == _getOrder.UserId).ToList();
                                    db.Carts.RemoveRange(_getCart);
                                    db.SaveChanges();

                                    var keyboard = new InlineKeyboardMarkup(new[]
                                    {
                                        new[]
                                        {
                                            InlineKeyboardButton.WithCallbackData(Logic.Utilities.Enum.Home.Text, Logic.Utilities.Enum.Home.Command)
                                        }
                                    });

                                    var sb = new StringBuilder();
                                    sb.AppendLine("پرداخت انجام شده و سفارش شما ثبت شد، به همین زودیا بهتون خبر میدیم");
                                    sb.AppendLine("شماره پیگیری : " + pm_input.RefId);


                                    Bot.SendTextMessageAsync(_getOrder.User.Token, sb.ToString(),
                                                             replyMarkup: keyboard);


                                    string[] admin = ConfigurationManager.AppSettings["AdminToken"].Split('-');
                                    sb.Clear();
                                    sb.AppendLine("سفارش جدید");
                                    sb.AppendLine("@" + _getOrder.User.Username + "به نام " + _getOrder.User.Name);
                                    sb.AppendLine("سفارشات :");

                                    int TotalPrice = 0;
                                    foreach (var ord in _getOrder.OrderItems)
                                    {
                                        sb.AppendLine(ord.Product.Name + "-" + ord.Quantity);
                                        TotalPrice = TotalPrice + (ord.Product.Price.HasValue ? ord.Product.Price.Value : 0);
                                    }
                                    sb.AppendLine("مبلغ پرداخت شده :" + TotalPrice);
                                    sb.AppendLine("شماره پیگیری : " + pm_input.RefId);


                                    foreach (var item in admin)
                                    {
                                        Bot.SendTextMessageAsync(item, sb.ToString(),
                                                                 replyMarkup: new ReplyKeyboardRemove());
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            string sSource = "BotHandler";

                            EventLog.WriteEntry(sSource, ex.ToString(), EventLogEntryType.Warning, 236);
                        }
                    }
                }
                catch (Exception ex)
                {
                    EventLog.WriteEntry("BotHandler", ex.ToString(), EventLogEntryType.Warning, 295);
                }
            }
        }
Ejemplo n.º 8
0
        public void update()
        {
            values = new PointF[COUNT];
            double value = 0.0;

            mq = new System.Messaging.MessageQueue(@".\Private$\MyQueue");

            string mes = null;
            int n = 0;

            for (n = 0; n < 1280; n++)
                {
                    mq.Receive();
                    mq.Receive();
                    System.Messaging.Message message = mq.Receive();
                    message.Formatter = new System.Messaging.XmlMessageFormatter(new String[] { "System.String,mscorlib" });
                    mes = message.Body.ToString();
                    value = System.Convert.ToDouble(mes);
                    value = Math.Abs(value - HEIGHT) - 1200;
                    values[n] = new PointF((float)n, (float)value);
                }
        }
Ejemplo n.º 9
0
 public void DoIt()
 {
     var messageQueue = new System.Messaging.MessageQueue(@"FormatName:Direct=OS:<HOST NAME>\Private$\<PRIVATE QUEUE NAME>");
     var message      = messageQueue.Receive(new TimeSpan(0, 0, 3)); // 3 SECOND TIMEOUT
     var messageBody  = ConvertStreamToByteArray(message.BodyStream);
 }