Beispiel #1
0
        public void Handle(CheckIntervalElapsedMessage message)
        {
            if (Interlocked.CompareExchange(ref _ticket, 1, 0) == 0)
            {
                _taskFactory.StartNew(() =>
                {
                    try
                    {
                        if (!_pluginMetadata.IsSyncronizableProfile)
                        {
                            return;
                        }
                        foreach (var account in _collection)
                        {
                            try
                            {
                                if (account.Profiles.Empty())
                                {
                                    continue;
                                }

                                var queueName            = _transport.GetQueueName(account.Name.Value);
                                var queueIsNotOverloaded = MsmqHelper.QueueIsNotOverloaded(queueName,
                                                                                           "Failed to count messages in queue for account '{0}'"
                                                                                           .Fmt(account.Name.Value), 10);
                                if (!queueIsNotOverloaded)
                                {
                                    continue;
                                }
                                foreach (var profile in account.Profiles)
                                {
                                    var lastSyncDate = profile.Get <LastSyncDate>().FirstOrDefault();
                                    if (IsTimeToSyncronize(profile, lastSyncDate) && profile.Initialized)
                                    {
                                        _bus.SetOut(profile.ConvertToPluginProfile().Name);
                                        _bus.SetOut(account.Name);
                                        _bus.SendLocal(lastSyncDate != null
                                                                                                               ? new TickMessage(lastSyncDate.Value)
                                                                                                               : new TickMessage(null));
                                        ObjectFactory.GetInstance <ILogManager>().GetLogger(GetType()).Info("TickMesage sent");
                                        profile.Get <LastSyncDate>().ReplaceWith(new LastSyncDate(CurrentDate.Value));
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                LogManager.GetLogger(GetType())
                                .Error(string.Format("Failed to send tick message for account '{0}'", account.Name.Value), e);
                            }
                        }
                    }
                    finally
                    {
                        Interlocked.Decrement(ref _ticket);
                    }
                });
            }
        }
Beispiel #2
0
        public void IsQueueEmpty_NotEmptyQueue_ReturnsFalse()
        {
            var message = new Message();
            var queue   = new MessageQueue(_QueueName);

            queue.Send(message);

            var isEmpty = MsmqHelper.IsQueueEmpty(_QueueName);

            Expect(isEmpty, Is.False);
        }
Beispiel #3
0
    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            MessageQueue myQueue = MsmqHelper.CreateQueue();

            this.Label1.Text = "成功。";
        }
        catch (Exception ex)
        {
            this.Label1.Text = "失败!" + ex.ToString();
        }
    }
Beispiel #4
0
    //private MessageQueue _messageQueue;

    //public MessageQueueHelper(bool workflowCreated)
    //{
    //    this._messageQueue = MsmqHelper.InitializeQueue();
    //    this._messageQueue.Send(workflowCreated);
    //}

    public static SendMessage(object workflowCreated)
    {
        using (MessageQueue msmsq = MsmqHelper.InitializeQueue())
        {
            msmq.Send(workflowCreated);
            msmq.Close();

            //MsmqHelper.DisposeQueue(msmq);
            // 2. You should explicitly call Close object to immediately release
            // unmanaged resources, while managed ones will be released
            // at next GC rounds, as soon as possible
        }
    }
Beispiel #5
0
 public static void ReceiveMessage()
 {
     try
     {
         MessageQueue myQueue = MsmqHelper.CreateQueue();
         myQueue.Formatter         = new XmlMessageFormatter(new Type[] { typeof(ItemInfo) });
         myQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(MyReceiveCompleted);
         myQueue.BeginReceive();
     }
     catch (Exception ex)
     {
     }
 }
Beispiel #6
0
        public MsmqDistribution(string typeName = null)
        {
            if (!string.IsNullOrEmpty(typeName))
            {
                m_TypeName = typeName;
            }
            else
            {
                m_TypeName = typeof(T).FullName.Replace(".", "_");
            }

            m_MsmqHelper = new MsmqHelper(string.Format(MQPathFormat, Defaults.ProcessName, m_TypeName));
        }
        private static void SendProductMSMQMessage(DataService.IngredientImportService service, int databaseId, string customerDbConnectionString)
        {
            List <Tuple <int?, string> > ingrIds = Start.CollectProductIds;

            var isRecipeEnabled     = service.IsOrchestrationEnabled(Constants.EntityType.Ingredient);
            var isIngredientEnabled = service.IsOrchestrationEnabled(Constants.EntityType.Dish);

            //if one of two types are enabled get all affected products
            if (isRecipeEnabled || isIngredientEnabled)
            {
                var updatedEntities = service.GetUpdatedEntities(ingrIds)
                                      .Where(c => (c.EntityTypeId == Constants.EntityType.Ingredient && isIngredientEnabled) || (c.EntityTypeId == Constants.EntityType.Dish && isRecipeEnabled))
                                      .ToList();

                try
                {
                    int pageSize;
                    if (!int.TryParse(ConfigurationManager.AppSettings["pageSize"], out pageSize))
                    {
                        pageSize = 20;
                    }

                    if (!updatedEntities.Any())
                    {
                        return;
                    }
                    var groupedProducts = updatedEntities.GroupBy(c => new { c.EntityTypeId, c.MessageActionType });
                    foreach (var groupedProduct in groupedProducts)
                    {
                        var count = groupedProduct.Count();
                        var pages = (int)Math.Ceiling((double)count / pageSize);

                        for (var i = 0; i < pages; i++)
                        {
                            var skip              = i == 0 ? i : i * pageSize;
                            var productIds        = groupedProduct.OrderBy(c => c.EntityId).Skip(skip).Take(pageSize).Select(c => c.EntityId);
                            var jsonProductIds    = JsonConvert.SerializeObject(productIds);
                            var entityType        = groupedProduct.Key.EntityTypeId;
                            var messageActionType = groupedProduct.Key.MessageActionType;
                            MsmqHelper.Send(default(int), (int)entityType, databaseId, customerDbConnectionString, messageActionType, null, jsonProductIds);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex);
                    throw;
                }
            }
        }
        public void Init()
        {
            var checkInterval = TimeSpan.FromSeconds(Settings.Default.DefaultCheckInterval);

            _checkTimer = new System.Timers.Timer {
                Interval = checkInterval.TotalMilliseconds
            };
            _checkTimer.Elapsed += (sender, elapsedEventArgs) =>
            {
                try
                {
                    var transport = ObjectFactory.GetInstance <IMsmqTransport>();
                    if (transport != null)
                    {
                        if (transport.QueueIsNotEmpty())
                        {
                            return;
                        }

                        if (
                            !MsmqHelper.QueueIsNotOverloaded(transport.InputQueue,
                                                             "Failed to count messages in main queue '{0}'".Fmt(
                                                                 transport.InputQueue),
                                                             Settings.Default.MessagesInQueueCountThreshold))
                        {
                            return;
                        }
                    }

                    _bus.CleanupOutgoingHeaders();
                    _bus.SendLocal(new CheckIntervalElapsedMessage());
                }
                catch (Exception e)
                {
                    LogManager.GetLogger(GetType()).Fatal(
                        "Failed to send CheckIntervalElapsedMessage. Plugin will not do any synchronization work.", e);
                }
            };

            _checkTimer.Start();

            _infoSenderTimer = new System.Timers.Timer {
                Interval = _infoSendInterval.TotalMilliseconds
            };
            _infoSenderTimer.Elapsed += (sender, elapsedEventArgs) => new PluginInitializer().SendInfoMessages();
            _infoSenderTimer.Start();
        }
Beispiel #9
0
        public void IsQueueEmpty_InvalidQueue_ThrowsException()
        {
            var invalidQueueName = @".\private$\invalidQueueName";

            MsmqHelper.IsQueueEmpty(invalidQueueName);
        }
Beispiel #10
0
        public void IsQueueEmpty_EmptyQueue_ReturnsTrue()
        {
            var isEmpty = MsmqHelper.IsQueueEmpty(_QueueName);

            Expect(isEmpty);
        }
Beispiel #11
0
    protected void Button2_Click(object sender, EventArgs e)
    {
        ItemInfo item = MsmqHelper.ReceiveMessage();

        this.Label1.Text = item.ToString();
    }
Beispiel #12
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        bool success = MsmqHelper.Delete();

        this.Label1.Text = success.ToString();
    }
Beispiel #13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string   itemName    = Request.Form["itemname"].ToString();
        int      itemAppId   = Convert.ToInt32(Request.Form["itemid"]);
        int      itemId      = Convert.ToInt32(Request.Form["itemwebid"]);
        int      catId       = Convert.ToInt32(Request.Form["catid"]);
        decimal  itemPrice   = Convert.ToDecimal(Request.Form["itemprice"]);
        DateTime itemBuyDate = Convert.ToDateTime(Request.Form["itembuydate"]);
        int      userId      = Convert.ToInt32(Request.Form["userid"]);
        byte     recommend   = Convert.ToByte(Request.Form["recommend"]);
        int      regionId    = Convert.ToInt32(Request.Form["regionid"]);
        string   regionType  = (regionId == 0 ? "" : Request.Form["regiontype"] ?? "m");
        string   itemType    = Request.Form["itemtype"].ToString();
        string   ztId        = Request.Form["ztid"] ?? "0";
        string   cardId      = Request.Form["cardid"] ?? "0";
        string   remark      = Request.Form["remark"] ?? "";

        ItemInfo item = useMsmq ? new ItemInfo() : bll.GetItemByItemAppId(userId, itemAppId);

        item.ItemType       = itemType;
        item.ItemName       = itemName;
        item.CategoryTypeID = catId;
        item.ItemPrice      = itemPrice;
        item.ItemBuyDate    = itemBuyDate;
        item.ItemAppID      = itemAppId;
        item.Recommend      = recommend;
        item.RegionID       = regionId;
        item.RegionType     = regionType;
        item.Synchronize    = 0;
        item.UserID         = userId;
        item.ZhuanTiID      = Convert.ToInt32(ztId);
        item.CardID         = Convert.ToInt32(cardId);
        item.ModifyDate     = DateTime.Now;
        item.Remark         = remark;

        //写日志
        log.Info(string.Format(" ItemInfo -> {0}", item.ToString()));

        bool success = false;

        if (useMsmq)
        {
            //string json = Newtonsoft.Json.JsonConvert.SerializeObject(item);
            success = MsmqHelper.SendMessage(item);
        }
        else
        {
            if (item.ItemID > 0)
            {
                success = bll.UpdateItemByItemAppId(item);
            }
            else if (itemId > 0)
            {
                item                = bll.GetItemByItemId(itemId);
                item.ItemType       = itemType;
                item.ItemName       = itemName;
                item.CategoryTypeID = catId;
                item.ItemPrice      = itemPrice;
                item.ItemBuyDate    = itemBuyDate;
                item.ItemAppID      = itemAppId;
                item.Recommend      = recommend;
                item.RegionID       = regionId;
                item.RegionType     = regionType;
                item.Synchronize    = 0;
                item.UserID         = userId;
                item.ZhuanTiID      = Convert.ToInt32(ztId);
                item.CardID         = Convert.ToInt32(cardId);
                item.ModifyDate     = DateTime.Now;
                item.Remark         = remark;

                if (item.ItemID > 0)
                {
                    success = bll.UpdateItemWithSync(item);
                }
                else
                {
                    success = bll.InsertItemWithSync(item);
                }
            }
            else
            {
                success = bll.InsertItemWithSync(item);
            }
        }

        string result = "{";

        if (success)
        {
            result += "\"result\":\"" + item.ItemID + "\"";
        }
        else
        {
            result += "\"result\":\"0\"";
        }
        result += "}";

        Response.Write(result);
        Response.End();
    }