public void SingleQueueControllerTest()
        {
            var manager = new QueueMessageManagerSql();

            // sample - create 3 message
            for (int i = 0; i < 3; i++)
            {
                var item = new QueueMessageItem()
                {
                    QueueName = "Queue1",
                    Message = "Print Image",
                    Action = "PRINTIMAGE",
                    TextInput = "4334333" // image Id
                };

                // sets appropriate settings for submit on item
                manager.SubmitRequest(item);

                // item has to be saved
                Assert.IsTrue(manager.Save(), manager.ErrorMessage);
                Console.WriteLine("added " + manager.Item.Id);
            }

            Console.WriteLine("Starting... Async Manager Processing");

            // create a new Controller to process in the background
            // on separate threads
            var controller = new QueueController()
            {
                ConnectionString = "QueueMessageManager",
                ThreadCount = 2,
                WaitInterval = 200,
                QueueName = "Queue1"
            };
        

            Console.WriteLine("Wait: " + controller.WaitInterval);

            // ExecuteStart Event is where your processing logic goes
            controller.ExecuteStart += controller_ExecuteStart;

            // ExecuteFailed and ExecuteComplete let you take actions on completion
            controller.ExecuteComplete += controller_ExecuteComplete;
            controller.ExecuteFailed += controller_ExecuteFailed;

            // actually start the queue
            controller.StartProcessingAsync();

            // For test we have to keep the threads alive 
            // to allow the 3 requests to process
            Thread.Sleep(2000);

            // shut down
            controller.StopProcessing();

            Thread.Sleep(200);  

            Console.WriteLine("Stopping... Async Manager Processing");
            Assert.IsTrue(true);
        }
Пример #2
0
        /// <summary>
        /// Saves the passed message item or the attached item
        /// to the database and creates a MSMQ message for the ID
        /// to be picked up.
        ///
        /// Call this after updating properties
        /// or individual values.
        ///
        /// Inserts or updates based on whether the ID exists
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public override bool Save(QueueMessageItem item = null)
        {
            if (item == null)
            {
                item = Item;
            }

            bool isNew = false;

            if (item != null)
            {
                isNew = item.__IsNew;
            }

            // first write the SQL record
            if (!base.Save(item))
            {
                return(false);
            }

            if (!isNew)
            {
                return(true);
            }

            // now write the MSMQ entry - if it fails
            // the queue item is removed
            return(InsertIdIntoQueue(item));
        }
        public void AddQueueItem()
        {
            var qm = new QueueMessageManagerSql(connectionString);

            var item = new QueueMessageItem()
            {
                Message = "Single SQL Entry",
                TextInput = "Process This",
                QueueName="MPWF",
                Action="HELLOWORLD",
                Xml = @"<doc>
    <company>West Wind</company>
    <name>Rick</name>    
</doc>
" 
            };
            Assert.IsTrue(qm.SubmitRequest(item, null, true), qm.ErrorMessage);
            
        }
        public void AddManyQueueItems()
        {
            var qm = new QueueMessageManagerSql(connectionString);

            for (int i = 0; i < 10; i++)
            {
                var item2 = new QueueMessageItem()
                {
                    Message = "Sql Queue Entry",
                    TextInput = "Process This",
                    QueueName = "MPWF",
                    Action = "GOBIG",
                    Xml = string.Format(@"<doc>
    <company>East Wind</company>
    <name>Rick</name> 
    <time>{0}</time>
</doc>
",DateTime.Now.ToString("MMM dd - HH:mm:ss"))
                };
                Thread.Sleep(300);

                Assert.IsTrue(qm.SubmitRequest(item2, null, true), qm.ErrorMessage);
            }
        }
 /// <summary>
 /// Resubmits an existing message by clearing out all
 /// completion/date settings and then resubmitting the
 /// entry.
 /// 
 /// This method calls Save() and actually saves the message
 /// to disk.
 /// </summary>
 /// <param name="item"></param>
 /// <returns></returns>
 public virtual bool ResubmitMessage(QueueMessageItem item = null)
 {
     SubmitRequest(item);
     return Save(item);
 }
        public void QueueControllerMultipleTest()
        {
            var manager = new QueueMessageManagerSql();

            // sample - create 3 message in 'default' queue
            for (int i = 0; i < 3; i++)
            {
                var item = new QueueMessageItem()
                {
                    Message = "Print Image",
                    Action = "PRINTIMAGE",
                    TextInput = "4334333", // image Id
                    QueueName = "Queue1"
                };

                // sets appropriate settings for submit on item
                manager.SubmitRequest(item);

                // item has to be saved
                Assert.IsTrue(manager.Save(), manager.ErrorMessage);
                Console.WriteLine("added to Queue1:" + manager.Item.Id);
            }

            // sample - create 3 message in 'default' queue
            for (int i = 0; i < 3; i++)
            {
                var item = new QueueMessageItem()
                {
                    Message = "Print Image (2nd)",
                    Action = "PRINTIMAGE",
                    TextInput = "5334333", // image Id
                    QueueName = "Queue2"
                };

                // sets appropriate settings for submit on item
                manager.SubmitRequest(item);

                // item has to be saved
                Assert.IsTrue(manager.Save(), manager.ErrorMessage);
                Console.WriteLine("added to Queue2: " + manager.Item.Id);
            }

            

            // create a new Controller to process in the background
            // on separate threads
            var controller = new QueueControllerMultiple(new List<QueueController>()
            {
                new QueueControllerMultiple()
                {
                    QueueName = "Queue1",
                    WaitInterval = 300,
                    ThreadCount = 5
                },
                new QueueControllerMultiple()
                {
                    QueueName = "Queue2",
                    WaitInterval = 500,
                    ThreadCount = 3
                }
            });                     
                        

            // Point all controllers at the same execution handlers
            // Alternately you can configure each controller with their
            // own event handlers or implement custom controller subclasses
            // that use the OnXXX handlers to handle the events
            controller.ExecuteStart += controller_ExecuteStart;
            controller.ExecuteComplete += controller_ExecuteComplete;
            controller.ExecuteFailed += controller_ExecuteFailed;
            
            // actually start the queue
            Console.WriteLine("Starting... Async Manager Processing");

            controller.StartProcessingAsync();

            // For test we have to keep the threads alive 
            // to allow the 10 requests to process
            Thread.Sleep(2000);

            // shut down
            controller.StopProcessing();
            
            Thread.Sleep(200);

            Console.WriteLine("Stopping... Async Manager Processing");
            Assert.IsTrue(true);

            Console.WriteLine("Processed: " + controller.MessagesProcessed);
        }
        /// <summary>
        /// Saves the passed message item or the attached item
        /// to the database. Call this after updating properties
        /// or individual values.
        /// 
        /// Inserts or updates based on whether the ID exists
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public override bool Save(QueueMessageItem item = null)
        {
            SetError();

            if (item == null)
                item = Item;
            if (item == null)
            {
                SetError("No item passed to save.");
                return false;
            }

            var result = Collection.Save(item);
            if (!result.HasLastErrorMessage)
                return true;

            SetError(result.ErrorMessage);
            return false;
        }
 /// <summary>
 /// Writes out a message to the SignalR hub
 /// </summary>
 /// <param name="queueItem"></param>
 /// <param name="elapsed"></param>
 /// <param name="waiting"></param>
 public virtual void WriteMessage(QueueMessageItem queueItem, int elapsed = 0, int waiting = -1)
 {
     // forward to SignalR Hub broadcast
     QueueMonitorServiceHub.WriteMessage(queueItem, elapsed, waiting);
 }
        /// <summary>
        /// Saves the passed message item or the attached item
        /// to the database and creates a MSMQ message for the ID
        /// to be picked up. 
        /// 
        /// Call this after updating properties
        /// or individual values.
        /// 
        /// Inserts or updates based on whether the ID exists
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public override bool Save(QueueMessageItem item = null)
        {
            if (item == null)
                item = Item;

            bool isNew = false;
            if (item!= null)
                isNew = item.__IsNew;

            // first write the SQL record
            if (!base.Save(item))
                return false;

            if (!isNew)
                return true;

            // now write the MSMQ entry - if it fails
            // the queue item is removed
            return InsertIdIntoQueue(item);            
        }
        /// <summary>
        /// Writes out a message to all SignalR clients
        /// </summary>
        /// <param name="queueItem"></param>
        /// <param name="elapsed"></param>
        /// <param name="waiting"></param>
        public static void WriteMessage(QueueMessageItem queueItem, int elapsed = 0, int waiting = -1)
        {
            string elapsedString = string.Empty;
            if (elapsed > 0)
                elapsedString = (Convert.ToDecimal(elapsed) / 1000).ToString("N2") + "s";

            // Write out message to SignalR clients            
             HubContext.Clients.All.writeMessage(queueItem.Message,
                    queueItem.Status,
                    DateTime.Now.ToString("HH:mm:ss"),
                    queueItem.Id,
                    elapsedString,
                    waiting);
        }
        /// <summary>
        /// Creates a new item instance and properly
        /// initializes the instance's values.
        /// </summary>
        /// <returns></returns>
        public QueueMessageItem CreateItem(QueueMessageItem entity = null)
        {
            if (entity == null)
                Item = new QueueMessageItem();
            else
                Item = entity;

            Item.__IsNew = true;

            // ensure item is properly configured
            Item.Submitted = DateTime.UtcNow;
            Item.Status = "Submitted";
            Item.Started = null;
            Item.Completed = null;

            return Item;
        }
        /// <summary>
        /// Resubmit message into the queue as a cleared and message
        /// to be reprocessed. All date flags are cleared.
        /// 
        /// This method immediately writes the queue item to disk
        /// immediately. This version also writes an MSMQ item for
        /// the ID.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public override bool ResubmitMessage(QueueMessageItem item = null)
        {
            if (!base.ResubmitMessage(item))
                return false;

            return InsertIdIntoQueue(item);
        }
 public void Notify(QueueMessageItem queueItem, int elapsed = 0, int waiting = 0)
 {
     WriteMessage(queueItem, elapsed, waiting); 
 }
 /// <summary>
 /// Saves the passed item or the attached item
 /// to the database. Call this after updating properties
 /// or individual values.
 /// </summary>
 /// <param name="item"></param>
 /// <returns></returns>
 public abstract bool Save(QueueMessageItem item = null);
        /// <summary>
        /// Updates the QueueMessageStatus and or messages
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="status"></param>
        /// <param name="messageText"></param>
        /// <param name="percentComplete"></param>
        public bool UpdateQueueMessageStatus(QueueMessageItem item = null, string status = null, string messageText = null, int percentComplete = -1, bool autoSave = false)
        {
            if (item == null)
                item = Item;
            if (item == null)
                item = CreateItem();

            if (!string.IsNullOrEmpty(status))
                item.Status = status;

            if (!string.IsNullOrEmpty(messageText))
                item.Message = messageText;

            if (percentComplete > -1)
                item.PercentComplete = percentComplete;

            if (autoSave)
                return Save();

            return true;
        }
        /// <summary>
        /// Sets the Item record with the required settings
        /// to complete and cancel a request. Not saved to database
        /// call Save() explicitly.
        /// </summary>
        public bool CancelRequest(QueueMessageItem item = null, string messageText = null, bool autoSave = false)
        {
            if (item == null)
                item = Item;
            if (item == null)
                item = CreateItem();

            item.Status = "Cancelled";
            item.Completed = DateTime.UtcNow;
            if (item.Started == null)
                item.Started = DateTime.UtcNow.AddMilliseconds(-1);
            item.IsComplete = true;
            item.IsCancelled = true;

            if (messageText != null)
                item.Message = messageText;

            if (autoSave)
                return Save();

            return true;
        }
        /// <summary>
        /// Sets the message properties for starting a new message request operation.
        /// Note the record is not written to the database use Save explicitly
        /// </summary>
        /// <param name="item">An existing item instance</param>
        public bool SubmitRequest(QueueMessageItem item = null, string messageText = null, bool autoSave = false)
        {
            if (item == null)
                item = CreateItem();            

            item.PercentComplete = 0;
            item.Status = "Submitted";
            item.Submitted = DateTime.UtcNow;
            item.Started = null;
            item.Completed = null;
            item.IsComplete = false;
            item.IsCancelled = false;

            if (item.QueueName == null)
                item.QueueName = DefaultQueue;

            if (messageText != null)
                item.Message = messageText;

            Item = item;

            if (autoSave)
                return Save();

            return true;
        }
        /// <summary>
        /// Writes out a message to all SignalR clients
        /// </summary>
        /// <param name="queueItem"></param>
        /// <param name="elapsed"></param>
        /// <param name="waiting"></param>
        public static void WriteMessage(QueueMessageItem queueItem, 
            int elapsed = 0, 
            int waiting = -1,
            DateTime? time = null)
        {
            string elapsedString = string.Empty;
            if (elapsed > 0)
                elapsedString = (Convert.ToDecimal(elapsed)/1000).ToString("N2") + "s";

            var msg = HtmlUtils.DisplayMemo(queueItem.Message);

            if (time == null)
                time = DateTime.UtcNow;

            // Write out message to SignalR clients            
            HubContext.Clients.All.writeMessage(msg,
                queueItem.Status,
                time.Value.ToString("HH:mm:ss"),
                queueItem.Id,
                elapsedString,
                waiting, queueItem.QueueName);
        }
        /// <summary>
        /// Helper method that inserts the 
        /// </summary>
        /// <returns></returns>
        public bool InsertIdIntoQueue(QueueMessageItem item = null)
        {
            if (item == null)
                item = Item;

            // write new entries into the queue
            var queue = GetQueue(item.QueueName);
            if (queue == null)
            {
                DeleteMessage(item.Id);
                return false;
            }

            try
            {
                queue.Formatter = new StringMessageFormatter();
                queue.Send(Item.Id);
            }
            catch (Exception ex)
            {
                SetError(ex);
                DeleteMessage(item.Id);
                return false;
            }

            return true;
        }