Ejemplo n.º 1
0
        public void SynchronizedListUnitTest()
        {
            SynchronizedList<string> list = new SynchronizedList<string>();

            list.Add("one");
            list.Add("two");
            Assert.IsTrue(list.Count == 2);

            foreach (string name in list)
            {
                Assert.IsTrue(list.Contains(name));
            }

            list.Remove("one");
            Assert.IsTrue(list.Count == 1);

            list.Insert(0, "one");
            Assert.IsTrue(list.Count == 2);
            Assert.IsTrue(list.Contains("one"));
            Assert.IsTrue(list[0] == "one");

            list.RemoveAt(0);
            Assert.IsFalse(list.Contains("one"));

            list.Clear();
            Assert.IsTrue(list.Count == 0);
        }
        public void PostMessageToQueue(string queueUriWithSas, KustoIngestionMessage message, FileObject fileObject)
        {
            Log.Info($"post: {queueUriWithSas}", ConsoleColor.Magenta);
            _totalBlobIngestQueued++;

            CloudQueue        queue        = new CloudQueue(new Uri(queueUriWithSas));
            CloudQueueMessage queueMessage = new CloudQueueMessage(JsonConvert.SerializeObject(message));

            OperationContext context = new OperationContext()
            {
                ClientRequestID = message.Id,
            };

            queue.AddMessage(queueMessage, _messageTimeToLive, null, null, context);

            if (Config.KustoUseIngestMessage)
            {
                _messageList.Add(message.Id);
            }
            else
            {
                _messageList.Add(fileObject.RelativeUri);
            }

            Log.Info($"queue message id: {message.Id}");
        }
Ejemplo n.º 3
0
        public void Save(CompositionDiagramElement element, bool isComposition)
        {
            if (element == null)
            {
                throw new ArgumentNullException(nameof(element));
            }

            if (!isComposition)
            {
                if (!_strategies.Contains(element))
                {
                    _strategies.Add(element);
                }
            }
            else
            {
                DiagramElements.Add(element);
            }

            var path     = isComposition ? _compositionsPath : _strategiesPath;
            var settings = _compositionRegistry.Serialize(element);
            var file     = Path.Combine(path, element.GetFileName());

            _serializer.Serialize(settings, file);
        }
Ejemplo n.º 4
0
        public void TestListActions()
        {
            var list = new SynchronizedList <string>();

            Parallel.For(0, 100, i =>
            {
                list.Add(i.ToString("g"));
                list.Add((i + 100).ToString("g"));
                list.Remove((i + 300).ToString("g"));
                Assert.IsFalse(string.IsNullOrEmpty(list[0]));
                list.AddRange(new[] { (i + 200).ToString("g"), (i + 300).ToString("g"), (i + 400).ToString("g") });
                list.Remove((i + 200).ToString("g"));
            });

            list.RemoveAll(ele => ele.Length == 3 && ele.StartsWith("4"));
            Assert.AreEqual(300, list.Count);

            var list2 = ListExtensions.ToSynchronizedList(list, new object());

            Assert.AreEqual(300, list2.Count);
            list2.Add("abcdefg");
            Assert.AreEqual("abcdefg", list2.Last());
            Assert.IsTrue(list2.Contains("356"));

            list = new SynchronizedList <string>(list2);
            list.Reverse();
            Assert.AreEqual(301, list.Count);
            Assert.AreEqual("abcdefg", list.First());
            list.RemoveAt(0);
            Assert.AreEqual(300, list.Count);
            Assert.IsTrue(list2.Contains("17"));
            list.Clear();
            Assert.AreEqual(0, list.Count);
        }
Ejemplo n.º 5
0
        private void OnPromotionUnapplied(PromotionUnapplied @event)
        {
            Interlocked.Decrement(ref _usages);

            int usagesForThisUser;

            _usagesPerUser.TryGetValue(@event.AccountId, out usagesForThisUser);
            _usagesPerUser[@event.AccountId] = Interlocked.Decrement(ref usagesForThisUser);

            _orderIds.Remove(@event.OrderId);

            _usersWhiteList.Add(@event.AccountId);
        }
Ejemplo n.º 6
0
 internal void InitializeDtuGroups()
 {
     try
     {
         var groups = DbAccessorHelper.DbAccessor.QuerySensorGroups();
         foreach (SensorGroup sg in groups)
         {
             DtuGroup dg = dtuGroups.FirstOrDefault(g => g.Exists(sg.GroupId) || g.Exists(sg.DtuId));
             if (dg != null)
             {
                 dg.Add(sg);
             }
             else
             {
                 DtuGroup dgp = new DtuGroup();
                 dgp.Add(sg);
                 dtuGroups.Add(dgp);
             }
         }
     }
     catch (Exception e)
     {
         Log.WarnFormat("InitializeDtuGroups error: {0}", e);
     }
 }
        public void TestSingleInstance()
        {
            Assert.True(_singleInstance.StartApplication());

            var events = new SynchronizedList <SingleInstanceEventArgs>();

            _singleInstance.NewInstance += SingleInstance_NewInstance;

            Assert.True(_singleInstance.NotifyFirstInstance(new[] { "a", "b", "c" }));
            Assert.True(_singleInstance.NotifyFirstInstance(new[] { "123" }));

            while (events.Count < 2)
            {
                Thread.Sleep(50);
            }

            Assert.Equal(2, events.Count);
            var orderedEvents = events.OrderBy(args => args.Arguments.Length).ToList();

            Assert.Equal(new[] { "123" }, orderedEvents[0].Arguments);
            Assert.Equal(new[] { "a", "b", "c" }, orderedEvents[1].Arguments);

            void SingleInstance_NewInstance(object sender, SingleInstanceEventArgs e)
            {
                Assert.Equal(_singleInstance, sender);
                events.Add(e);
            }
        }
Ejemplo n.º 8
0
        private static void OnException(string msg, Exception ex)
        {
            if (ex != null)
            {
                Exceptions.Add(new ExceptionInfo(msg, ex));
                var delay = TimeSinceLastException.TotalMinutes;
                if (delay > 60)
                {
                    excepRaisingSpeed = 1;
                    recentExceptions  = 0;
                }
                else
                {
                    ++recentExceptions;
                    excepRaisingSpeed = (3 * excepRaisingSpeed + (1 / delay)) / 4;
                }

                if (recentExceptions > 5 && excepRaisingSpeed > 50 && !RealmServer.IsShuttingDown)
                {
                    //World.Broadcast("[Warning] Server has become unstable...");
                    //RealmServer.Instance.ShutdownIn(5000);
                    return;
                }
                lastExceptionTime = DateTime.Now;
            }

            NotifyException(msg, ex);
        }
Ejemplo n.º 9
0
        private void CandlesClick(object sender, RoutedEventArgs e)
        {
            var tf = (TimeSpan)CandlesPeriods.SelectedItem;

            var range = TimeSpan.FromTicks(tf.Ticks * 10000);

            if (range.TotalYears() > 5)
            {
                range = TimeSpan.FromTicks(TimeHelper.TicksPerYear * 5);
            }

            var wnd = new DatesWindow {
                From = DateTime.Today - range
            };

            if (!wnd.ShowModal(this))
            {
                return;
            }

            foreach (var security in SecurityPicker.SelectedSecurities)
            {
                var chartWnd = new ChartWindow(new CandleSeries(typeof(TimeFrameCandle), security, tf)
                {
                    From = wnd.From,
                    To   = wnd.To
                });

                _chartWindows.Add(chartWnd);
                chartWnd.Closed += (s, e1) => _chartWindows.Remove(chartWnd);

                chartWnd.Show();
            }
        }
        public void TestDisposed()
        {
            SynchronizedList <int> list = new SynchronizedList <int>(new SimpleReadWriteLocking());

            list.Dispose();
            list.Add(1);
        }
Ejemplo n.º 11
0
            public void PostStatus()
            {
                var status = new
                {
                    Message = new
                    {
                        ErrorPageCount,
                        LeftPageCount,
                        Speed,
                        StartTime,
                        Status,
                        SuccessPageCount,
                        ThreadCount,
                        TotalPageCount
                    },
                    Name,
                    Machine   = Log.Machine,
                    UserId    = _userId,
                    TaskGroup = _taskGroup,
                    Timestamp = DateTime.Now
                };

                var task = _client.PostAsync(StatusServer, new StringContent(JsonConvert.SerializeObject(status), Encoding.UTF8, "application/json"));

                StatusUpLoadTasks.Add(task);
                task.ContinueWith((t) =>
                {
                    StatusUpLoadTasks.Remove(t);
                });
            }
Ejemplo n.º 12
0
        public OWINApplication AddApplication(string path, PathParameters parameters, AppFunc application)
        {
            var app = new OWINApplication(path, parameters, application);

            applications.Add(app);
            return(app);
        }
Ejemplo n.º 13
0
        private static void OnException(string msg, Exception ex)
        {
            if (ex != null)
            {
                Exceptions.Add(new ExceptionInfo(msg, ex));
                double totalMinutes = TimeSinceLastException.TotalMinutes;
                if (totalMinutes > 60.0)
                {
                    excepRaisingSpeed = 1.0;
                    recentExceptions  = 0;
                }
                else
                {
                    ++recentExceptions;
                    excepRaisingSpeed =
                        (3.0 * excepRaisingSpeed + 1.0 / totalMinutes) / 4.0;
                }

                if (recentExceptions > 5 && excepRaisingSpeed > 50.0 &&
                    !ServerApp <RealmServer> .IsShuttingDown)
                {
                    return;
                }
                lastExceptionTime = DateTime.Now;
            }

            NotifyException(msg, ex);
        }
Ejemplo n.º 14
0
        public void SynchronizedListContainsTest()
        {
            tlog.Debug(tag, $"SynchronizedListContainsTest START");
            try
            {
                var sl = new SynchronizedList <int>();
                Assert.IsNotNull(sl, "null SynchronizedList");
                sl.Add(1);
                var ret = sl.Contains(1);
                Assert.AreEqual(true, ret, "Should be equal");
                Assert.AreEqual(1, sl.Count, "Should be equal");

                int[] ia = new int[] { 1, 2, 3 };
                sl.CopyTo(ia, 0);

                var ret2 = sl.GetEnumerator();
                Assert.IsNotNull(ret2, "null SynchronizedList");
                var ret3 = sl.IndexOf(1);
                sl.Insert(0, 2);
                var ret4 = sl[1];
                sl[1] = 7;
                sl.Remove(1);

                sl.Insert(0, 3);
                sl.RemoveAt(0);
            }
            catch (Exception e)
            {
                Assert.Fail("Caught Exception" + e.ToString());
            }
            tlog.Debug(tag, $"SynchronizedListContainsTest END");
        }
Ejemplo n.º 15
0
        private void Chart_OnSubscribeIndicatorElement(ChartIndicatorElement element, CandleSeries series, IIndicator indicator)
        {
            _dataThreadActions.Add(() =>
            {
                var chartData = new ChartDrawData();

                foreach (var candle in _allCandles.CachedValues)
                {
                    chartData.Group(candle.OpenTime).Add(element, indicator.Process(candle));
                }

                Chart.Reset(new[] { element });
                Chart.Draw(chartData);

                _indicators[element] = indicator;
            });
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Send message.
        /// </summary>
        /// <param name="message">Message.</param>
        public override void SendInMessage(Message message)
        {
            if (message.IsBack)
            {
                if (message.Adapter == this)
                {
                    message.Adapter = null;
                    message.IsBack  = false;
                }

                base.SendInMessage(message);
                return;
            }

            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                _connected = false;
                _pendingMessages.Clear();

                base.SendInMessage(message);
                break;
            }

            case MessageTypes.Connect:
            case MessageTypes.Disconnect:
                break;

            case MessageTypes.Time:
            {
                if (!_connected)
                {
                    return;
                }

                break;
            }

            default:
            {
                if (!_connected)
                {
                    if (_maxMessageCount > 0 && _pendingMessages.Count == _maxMessageCount)
                    {
                        throw new InvalidOperationException(LocalizedStrings.MaxMessageCountExceed);
                    }

                    _pendingMessages.Add(message.Clone());
                    return;
                }

                break;
            }
            }

            base.SendInMessage(message);
        }
        public void TestAddWithOrdinal()
        {
            SynchronizedList <int> list = new SynchronizedList <int>(new IgnoreLocking());

            for (int i = 0; i < 10; i++)
            {
                Assert.AreEqual(i, list.Add(i));
            }
        }
Ejemplo n.º 18
0
            public TimeComeRule(IConnector connector, IEnumerable <DateTimeOffset> times)
                : base(connector)
            {
                if (times == null)
                {
                    throw new ArgumentNullException(nameof(times));
                }

                var currentTime = connector.CurrentTime;

                var intervals = new SynchronizedQueue <TimeSpan>();
                var timesList = new SynchronizedList <DateTimeOffset>();

                foreach (var time in times)
                {
                    var interval = time - currentTime;

                    if (interval <= TimeSpan.Zero)
                    {
                        continue;
                    }

                    intervals.Enqueue(interval);
                    currentTime = time;
                    timesList.Add(time);
                }

                // все даты устарели
                if (timesList.IsEmpty())
                {
                    return;
                }

                Name = LocalizedStrings.Str1055;

                var index = 0;

                _timer = new MarketTimer(connector, () =>
                {
                    var activateTime = timesList[index++];

                    Activate(activateTime);

                    if (index == timesList.Count)
                    {
                        _timer.Stop();
                    }
                    else
                    {
                        _timer.Interval(intervals.Dequeue());
                    }
                })
                         .Interval(intervals.Dequeue())
                         .Start();
            }
Ejemplo n.º 19
0
        /// <summary>
        /// Send message.
        /// </summary>
        /// <param name="message">Message.</param>
        public override void SendInMessage(Message message)
        {
            if (message.IsBack)
            {
                if (message.Adapter == this)
                {
                    message.Adapter = null;
                    message.IsBack  = false;
                }

                base.SendInMessage(message);
                return;
            }

            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                _connected = false;
                _pendingMessages.Clear();

                break;
            }

            case MessageTypes.Connect:
            case MessageTypes.Disconnect:
                break;

            case MessageTypes.Time:
            {
                if (!_connected)
                {
                    return;
                }

                break;
            }

            default:
            {
                if (!_connected)
                {
                    _pendingMessages.Add(message.Clone());
                    return;
                }

                break;
            }
            }

            base.SendInMessage(message);
        }
    public static void InitializeWorkers()
    {
        running   = true;
        m_Workers = new List <Thread>();
        for (int i = 0; i < System.Environment.ProcessorCount - 1; ++i)
        {
            _ReadyLists.Add(new SynchronizedQueue <IEnumerator>());

            var thr = new Thread(WorkerFunc);
            thr.Start(i);
            m_Workers.Add(thr);
        }
    }
Ejemplo n.º 21
0
 public void AddAuction(Auction newAuction)
 {
     if (newAuction == null)
     {
         return;
     }
     auctions.Add(newAuction.ItemLowId, newAuction);
     items.Add(newAuction.ItemLowId);
     if (!newAuction.IsNew)
     {
         return;
     }
     newAuction.Create();
 }
Ejemplo n.º 22
0
 public void AddAuction(Auction newAuction)
 {
     if (newAuction == null)
     {
         return;
     }
     auctions.Add(newAuction.ItemLowId, newAuction);
     items.Add(newAuction.ItemLowId);
     //if this is a new one created by player, it should be save in database
     if (newAuction.IsNew)
     {
         newAuction.Create();
     }
 }
Ejemplo n.º 23
0
            protected override void OnAdded(IndicatorToken item)
            {
                if (item == null)
                {
                    throw new ArgumentNullException("item");
                }

                _resetHandlers.Add(new ResetEventHandler(item, _manager));
                item.Indicator.Reset();

                _manager.ProcessIndicator(item);

                base.OnAdded(item);
            }
Ejemplo n.º 24
0
 public void SynchronizedListAddTest()
 {
     tlog.Debug(tag, $"SynchronizedListAddTest START");
     try
     {
         var sl = new SynchronizedList <int>();
         Assert.IsNotNull(sl, "null SynchronizedList");
         sl.Add(1);
     }
     catch (Exception e)
     {
         Assert.Fail("Caught Exception" + e.ToString());
     }
     tlog.Debug(tag, $"SynchronizedListAddTest END");
 }
Ejemplo n.º 25
0
                public void AddCandle(Candle candle)
                {
                    if (_firstTime == null)
                    {
                        _firstTime = candle.OpenTime;
                    }

                    lock (_candles.SyncRoot)
                    {
                        if ((candle.OpenTime.Date - _firstTime.Value.Date).TotalDays >= 3)
                        {
                            _firstTime = candle.OpenTime;
                            FlushCandles(_candles.CopyAndClear());
                        }

                        _candles.Add(candle);
                    }
                }
Ejemplo n.º 26
0
        public void Push(Action <object> func, object obj)
        {
            lock (this)
            {
                if (_exit)
                {
                    throw new SpiderExceptoin("Pool is exit.");
                }

                while (_tasks.Count() > _cachedSize)
                {
                    Thread.Sleep(10);
                }

                Task task = Task.Factory.StartNew((o) => { func(o); }, obj);
                _tasks.Add(task);
            }
        }
Ejemplo n.º 27
0
        public void Push(Func <object, bool> func, object obj)
        {
            lock (this)
            {
                if (_exit)
                {
                    throw new SpiderExceptoin("Pool is exit.");
                }

                // List中保留比最大线程数多5个
                while (_tasks.Count() > _cachedSize)
                {
                    Thread.Sleep(10);
                }

                Task task = _factory.StartNew((o) => { func(o); }, obj);
                _tasks.Add(task);
            }
        }
Ejemplo n.º 28
0
        private void OnNewsReceived(CommunityNews news)
        {
            var now = DateTime.UtcNow;

            lock (_news.SyncRoot)
            {
                _news.RemoveWhere(n => n.EndDate <= now);

                if (GetContent(news).IsEmpty())
                {
                    return;
                }

                _news.Add(news);
                _index = 0;
            }

            this.GuiAsync(() => ShowNews(news));
        }
Ejemplo n.º 29
0
        public async Task TestSingleInstance_NotifyFirstInstance()
        {
            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

            var applicationId = Guid.NewGuid();

            using var singleInstance = new SingleInstance(applicationId);
            Assert.True(singleInstance.StartApplication(), "Cannot start the instance");

            // Be sure the server is ready
            await Task.Delay(50);

            var events = new SynchronizedList <SingleInstanceEventArgs>();

            singleInstance.NewInstance += SingleInstance_NewInstance;

            Assert.True(singleInstance.NotifyFirstInstance(new[] { "a", "b", "c" }), "Cannot notify first instance 1");
            await Task.Delay(50);

            Assert.True(singleInstance.NotifyFirstInstance(new[] { "123" }), "Cannot notify first instance 2");

            while (!cts.Token.IsCancellationRequested && events.Count < 2)
            {
                await Task.Delay(50);
            }

            Assert.Equal(2, events.Count);
            var orderedEvents = events.OrderBy(args => args.Arguments.Length).ToList();

            Assert.Equal(new[] { "123" }, orderedEvents[0].Arguments);
            Assert.Equal(new[] { "a", "b", "c" }, orderedEvents[1].Arguments);

            void SingleInstance_NewInstance(object sender, SingleInstanceEventArgs e)
            {
                Assert.Equal(singleInstance, sender);
                events.Add(e);
            }
        }
        public void TestLock()
        {
            LockCounterFactory <SimpleReadWriteLocking> factory = new LockCounterFactory <SimpleReadWriteLocking>();
            ILockStrategy          lck  = factory.Create();
            SynchronizedList <int> list = new SynchronizedList <int>(lck);

            Assert.IsTrue(ReferenceEquals(lck, list.Lock));
            list.Add(42);
            Assert.AreEqual(1, factory.TotalWriterCount);
            Assert.AreEqual(0, factory.TotalReaderCount);

            list[0] = 51;
            Assert.AreEqual(2, factory.TotalWriterCount);

            list.Insert(1, 52);
            Assert.AreEqual(3, factory.TotalWriterCount);

            list.RemoveAt(1);
            Assert.AreEqual(4, factory.TotalWriterCount);

            list.Remove(-1);
            Assert.AreEqual(5, factory.TotalWriterCount);

            Assert.AreEqual(51, list[0]);
            Assert.AreEqual(1, factory.TotalReaderCount);

            foreach (int i in list)
            {
                GC.KeepAlive(i);
            }
            Assert.AreEqual(2, factory.TotalReaderCount);

            Assert.AreEqual(0, list.IndexOf(51));
            Assert.AreEqual(3, factory.TotalReaderCount);

            Assert.AreEqual(1, list.Count);
            Assert.AreEqual(4, factory.TotalReaderCount);
        }
Ejemplo n.º 31
0
        public override void Entry(IModHelper helper)
        {
            IMultiplayerApi multiplayerApi = this.GetCoreApi().GetMultiplayerApi();

            // Sync all the levels
            this.SyncLevel(multiplayerApi, "combatLevel", () => Game1.player.combatLevel.Value, n => Game1.player.combatLevel.Value       = n);
            this.SyncLevel(multiplayerApi, "farmingLevel", () => Game1.player.farmingLevel.Value, n => Game1.player.farmingLevel.Value    = n);
            this.SyncLevel(multiplayerApi, "fishingLevel", () => Game1.player.fishingLevel.Value, n => Game1.player.fishingLevel.Value    = n);
            this.SyncLevel(multiplayerApi, "foragingLevel", () => Game1.player.foragingLevel.Value, n => Game1.player.foragingLevel.Value = n);
            this.SyncLevel(multiplayerApi, "miningLevel", () => Game1.player.miningLevel.Value, n => Game1.player.miningLevel.Value       = n);
            this.SyncLevel(multiplayerApi, "luckLevel", () => Game1.player.luckLevel.Value, n => Game1.player.luckLevel.Value             = n);

            // Sync the exp
            SynchronizedList <int> expList = new SynchronizedList <int>(n => n.MakeSynchronized());

            multiplayerApi.Synchronize("expList", expList);
            foreach (int exp in Game1.player.experiencePoints)
            {
                expList.Add(exp);
            }
            GameEvents.UpdateTick += (sender, args) => {
                for (int i = 0; i < Game1.player.experiencePoints.Count; i++)
                {
                    int cur    = Game1.player.experiencePoints[i];
                    int synced = expList[i];

                    // Choose whichever is higher
                    if (cur < synced)
                    {
                        Game1.player.experiencePoints[i] = synced;
                    }
                    else if (synced < cur)
                    {
                        expList[i] = cur;
                    }
                }
            };
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Listens for an incoming client connection and starts a new thread for client communication when a client connects.
        /// </summary>
        private void Listen()
        {
            SynchronizedList<Thread> threadList = new SynchronizedList<Thread>();

            listener.Start();
            listen = true;

            while (listen)
            {
                if (listener.Pending())
                {
                    TcpClient client = listener.AcceptTcpClient();

                    clientQueue.Enqueue(client);

                    Thread thread = new Thread(new ThreadStart(ServiceClient));
                    thread.IsBackground = true;
                    thread.Start();

                    threadList.Add(thread);
                }
                else
                {
                    Thread.Sleep(TimeSpan.Zero);
                }
            }

            listener.Stop();

            foreach (Thread thread in threadList)
            {
                thread.Join();
            }
        }