Example #1
0
        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);
        }
Example #2
0
        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 void ReceiveServerPlayerInfo()
        {
            System.Messaging.Message message = new System.Messaging.Message();
            while (work)
            {
                try
                {
                    // Получаем информацию об игроках с сервера для обновления клиентов
                    message = queue.Receive();
                }
                catch (Exception exc)
                {
                    // Игнорируем исключение
                }

                if (message == null)
                {
                    continue;
                }
                else
                {
                    // Заполняем стол информацией об игроках
                    var players = (List <ServerPlayerInfo>)message.Body;
                    SeatPlayers(players);
                    message.Dispose();
                }
            }
        }
Example #4
0
 public void Dispose()
 {
     if (!_committed)
     {
         _txn?.Abort();
     }
     _txn?.Dispose();
     _msg.Dispose();
 }
Example #5
0
 /// <summary>
 /// Message must be provided, Sends a given msg
 /// </summary>
 /// <param name="qMsg"></param>
 /// <param name="w">   </param>
 public static void SendQMsg(ref System.Messaging.MessageQueue qMsg, ref System.Messaging.Message w)
 {
     System.Messaging.MessageQueueTransaction mqt = new System.Messaging.MessageQueueTransaction();
     mqt.Begin();
     qMsg.Send(w, mqt);
     mqt.Commit();
     mqt.Dispose();
     mqt = null;
     w.Dispose();
     w = null;
 }
        public async Task <QueueMessage <T> > ReceiveAsync(TimeSpan timeout)
        {
            if (timeout == TimeSpan.Zero)
            {
                return(await ReceiveAsync());
            }

            System.Messaging.Message message = null;

            try
            {
                message = await _messageQueue.ReceiveAsync(timeout);
            }
            catch (System.Messaging.MessageQueueException e)
            {
                if (message != null)
                {
                    message.Dispose();
                }

                if (e.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
                {
                    throw new TimeoutException("Timeout expired receiving from queue.");
                }
                else
                {
                    throw;
                }
            }

            using (message)
            {
                var item = await MessageSerializer.Deserialize((string)message.Body);

                var queueMessage = new QueueMessage <T>
                {
                    MessageId     = message.Id,
                    Item          = item,
                    CorrelationId = message.AppSpecific
                };

                return(queueMessage);
            }
        }
Example #7
0
        public void PutMessageOnMSQ(string queueName, string callId, string callData, string appid, ref ValidataionResponse response)
        {
            #region private variables
            string   message            = string.Empty;
            DateTime startTime          = DateTime.Now;
            System.Messaging.Message mm = null;
            #endregion

            log.InfoFormat("Started Enqueue Process -Start Time in:{0}  \n\n", startTime);
            try
            {
                if (InitailContext.mq == null)
                {
                    if (!MessageQueue.Exists(queueName))
                    {
                        log.DebugFormat("{0} - Queue does not exist", queueName);
                        MessageQueue.Create(queueName, true);
                    }
                    InitailContext.mq = new System.Messaging.MessageQueue(queueName);
                    InitailContext.mq.SetPermissions("Users", MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow);
                    InitailContext.mq.Authenticate = false;
                }
                mm       = new System.Messaging.Message();
                mm.Body  = callData;
                mm.Label = "QueueData";
                log.InfoFormat("Enqueued Details:{0}", mm.Body.ToString());
                //mm.TimeToReachQueue = new TimeSpan(0, 0,InitailContext.queueTimeout);
                //log.InfoFormat("Timeout {0} seconds", InitailContext.queueTimeout);
                if (InitailContext._dataConfigSetting.AppConfigSettings[appid].IsTransactionEnabled.ToString().ToUpper() == "Y")
                {
                    log.Debug("Transaction Enabled");
                    InitailContext.mq.Send(mm, "QueueData", MessageQueueTransactionType.Single);
                }
                else
                {
                    log.Debug("Transaction not Enabled");
                    InitailContext.mq.Send(mm);
                }
                response.HasQueued    = true;
                response.ErrorCode    = 0;
                response.ErrorMessage = "Success";
                response.FailureMode  = ValidationFailureMode.None;
                InitailContext.mq.Close();
                log.InfoFormat("Completed Enquee Process,Total Time taken:{0} milliseconds \n\n", DateTime.Now.Subtract(startTime).Milliseconds);
            }
            catch (Exception ex)
            {
                message               = string.Format("{0}, Call ID : {1}", ex.Message, callId);
                response.HasQueued    = false;
                response.ErrorCode    = (int)ValidationFailureMode.QueueInsertFailed;
                response.FailureMode  = ValidationFailureMode.QueueInsertFailed;
                response.ErrorMessage = message;
                log.ErrorFormat("Error : Failure Code : {0}, Error Code : {1}, Error Desc : {2} \n\n", response.FailureMode, response.ErrorCode, response.ErrorMessage);

                try
                {
                    //log.Info("Start writing file into Recovery folder");
                    //string folder = string.Format("{0}\\{1}\\{2}", ConfigurationManager.AppSettings["RecoveryFolder"].ToString(), DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("HH"));
                    //log.Debug("finished getting folder path");
                    //if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

                    ////int fileCount = Directory.GetFiles(folder).Length + 1;
                    //log.Debug("finished getting file count");

                    //string filePath = string.Format("{0}\\{1}_{2}_{3}.txt", folder, "MSMQ",DateTime.Now.Ticks.ToString(), (new Random()).Next(1000, 99999));
                    //log.Debug("finished writing file path");
                    //if (!File.Exists(filePath))
                    //{
                    //    log.Info("File is Exists");
                    //    File.WriteAllText(filePath, callData);
                    //    log.InfoFormat("Call Data with Callid : {0} , has Written to the file File Path : {1}", callId, filePath);
                    //}
                    //else
                    //{
                    //    log.DebugFormat("Filepath is not Exists {0}", filePath);
                    //}

                    //log.Debug("finished writing teh file into recovery folder");

                    MSMQ_RFService.CallDataValidation.delWriteFileIntoRecovery objwriteFile = new MSMQ_RFService.CallDataValidation.delWriteFileIntoRecovery(WriteIntoRecovery);
                    objwriteFile.BeginInvoke(callData, callId, null, null);
                }
                catch (Exception exp)
                {
                    log.ErrorFormat("Error while writing File :{0}", exp);
                }
            }
            finally
            {
                mm.Dispose();
                mm      = null;
                message = string.Empty;
            }
        }