public HttpResponseMessage Status()
        {
            HttpResponseMessage response;
            var currentRun = TestRuns.FirstOrDefault(r => r.RunStatus == RunStatus.Started);

            if (currentRun == null)
            {
                var result = new
                {
                    isActive = false,
                };
                response = Request.CreateResponse(result);
            }
            else
            {
                var result = new
                {
                    isActive            = true,
                    runId               = currentRun.Id.ToString(),
                    queuedTests         = currentRun.RemainingTests,
                    completedTests      = currentRun.CompletedTests,
                    inProgressTests     = currentRun.InProgressTests,
                    inProgressTestNames = currentRun.ActiveTestNames,
                };
                response = Request.CreateResponse(result);
            }
            return(response);
        }
        public bool TryGetSource(string uri, out ISource source)
        {
            source = default;
            var prov = _providers.FirstOrDefault(x => x.CanAccept(uri));

            return(prov != null && prov.TryGetSource(uri, out source));
        }
Esempio n. 3
0
    //this method gets called once but the HeartbeatController gets an action as a param that it then
    //executes on a timer. I haven't included that but you get the idea

    //This method also checks for tasks that have stopped and restarts them if the manifest call says they should be running.
    //Will also start any new tasks included in the manifest and stop any that aren't included in the manifest.
    internal void MonitorTasks()
    {
        HeartbeatController.Beat(() =>
        {
            HeartBeatHappened?.Invoke(this, null);
            List <int> tasksToStart = new List <int>();

            //this is an api call or whatever drives your config that says what tasks must be running.
            var newManifest = this.GetManifest(Properties.Settings.Default.ResourceId);

            //task Removed Check - If a Processor is removed from the task pool, cancel it if running and remove it from the Tasks List.
            List <int> instanceIds = new List <int>();
            newManifest.Processors.ForEach(x => instanceIds.Add(x.ProcessorId));
            var removed = Tasks.Select(x => x.ProcessorId).ToList().Except(instanceIds).ToList();

            if (removed.Count() > 0)
            {
                foreach (var extaskId in removed)
                {
                    var task = Tasks.FirstOrDefault(x => x.ProcessorId == extaskId);
                    task.CancellationTokenSource?.Cancel();
                }
            }

            foreach (var newtask in newManifest.Processors)
            {
                var oldtask = Tasks.FirstOrDefault(x => x.ProcessorId == newtask.ProcessorId);
                //Existing task check
                if (oldtask != null && oldtask.Task != null)
                {
                    if (!oldtask.Task.IsCanceled && (oldtask.Task.IsCompleted || oldtask.Task.IsFaulted))
                    {
                        var ex = oldtask.Task.Exception;

                        tasksToStart.Add(oldtask.ProcessorId);
                        continue;
                    }
                }
                else         //New task Check
                {
                    tasksToStart.Add(newtask.ProcessorId);
                }
            }

            foreach (var item in tasksToStart)
            {
                var taskToRemove = Tasks.FirstOrDefault(x => x.ProcessorId == item);
                if (taskToRemove != null)
                {
                    Tasks.Remove(taskToRemove);
                }

                var task = newManifest.Processors.FirstOrDefault(x => x.ProcessorId == item);
                if (task != null)
                {
                    CreateProcessorTask(task);
                }
            }
        });
    }
Esempio n. 4
0
        public Device AddDevice(string deviceIdentifier, string callerIdentifier)
        {
            var dbDevice = db.FirstOrDefault(x => x.CallerIdentifier == callerIdentifier);

            if (dbDevice == null)
            {
                var device = new Device
                {
                    CallerIdentifier = callerIdentifier,
                    DeviceIdentifier = deviceIdentifier,
                    Id = Guid.NewGuid().ToString()
                };

                db.Add(device);
                return(device);
            }


            if (dbDevice.DeviceIdentifier == deviceIdentifier)
            {
                return(dbDevice);
            }

            throw new CallerIdentifierAlreadyRegistered(dbDevice.DeviceIdentifier, callerIdentifier);
        }
Esempio n. 5
0
        private void ScheduleNext()
        {
            lock (scheduleLock)
            {
                WebsiteDefinition websiteDefinition;

                do
                {
                    websiteDefinition = null;
                    var next = crawlUrlRepository.PeekNext();
                    if (next != null)
                    {
                        websiteDefinition = websiteDefinitions.FirstOrDefault(x => x.Website.IsRelativeUrl(next) && x.UrlsInProcess < (x.Website.MaxConcurrentConnections * 2));
                        if (websiteDefinition != null)
                        {
                            next = crawlUrlRepository.Next();

                            next.WebsiteDefinition = websiteDefinition;
                            var inputCount = websiteProcessingDefinitions[websiteDefinition].Post(next);
                            log.DebugFormat("Process block for '{0}' has {1} pending messages", websiteDefinition.Website.RootUrl, inputCount);

                            RaisePageProcessing(next);

                            Interlocked.Increment(ref websiteDefinition.UrlsInProcess);
                        }
                    }
                } while (websiteDefinition != null);
            }
        }
 /// <summary>
 /// (全局使用)注册连接方式
 /// </summary>
 /// <param name="connection"></param>
 /// <param name="dbName"></param>
 /// <param name="isReplace">是否替换掉之前db连接</param>
 public static void RegisterDataBase(Func <IDbConnection, IDbConnection> connection, string dbName, bool isReplace = false)
 {
     //验证总连接池是否注册过
     //不存在时注入到总连接池中
     if (!_connectionPool.Any(x => x.DbName == dbName))
     {
         //首次测试注册得到连接字符串(防止传空)
         using (var dbConn = connection.Invoke(null))
         {
             var dbConnection = dbConn as DbConnection;
             _connectionPool.Add(new ConnectionPool
             {
                 FuncConnection   = connection,
                 DbName           = dbName,
                 ConnectionString = dbConnection.ConnectionString,
                 Database         = dbConnection.Database,
                 DataSource       = dbConnection.DataSource
             });
         }
     }
     else
     {
         if (isReplace)
         {
             var connectionPool = _connectionPool.FirstOrDefault(x => x.DbName == dbName);
             //首次测试注册得到连接字符串(防止传空)
             using (var dbConn = connection.Invoke(null))
             {
                 connectionPool.FuncConnection   = connection;
                 connectionPool.ConnectionString = dbConn.ConnectionString;
             }
         }
     }
 }
Esempio n. 7
0
        public Task <string> Add(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new Exception();
            }

            string ec = null;

            try
            {
                ec = _computerTypes.FirstOrDefault(x => x == name);
            }
            catch (Exception)
            {
                throw;
            }

            if (ec != null)
            {
                throw new DuplicateTypeException();
            }

            _computerTypes.Add(name);

            return(Task.FromResult(name));
        }
Esempio n. 8
0
        public bool VerificarDuplicidade(int[] numero, string modeloAposta)
        {
            Aposta aposta = _apostas
                            .FirstOrDefault(x => x.Comparar(numero) && x.ModeloAposta == modeloAposta);

            return(aposta != null);
        }
        public ObjectMap GetObjectMap(Type entityType)
        {
            ObjectMap map;

            if (typeof(ContentBase).IsAssignableFrom(entityType))
            {
                map = _objectMaps.FirstOrDefault(m => m.ContentType == entityType);
            }
            else
            {
                map = _objectMaps.FirstOrDefault(m => m.ViewModelType == entityType);

                if (map == null)
                {
                    map = _objectMaps.FirstOrDefault(m => m.ListModelType == entityType);
                }
            }

            if (map == null)
            {
                return(new ObjectMap(entityType, entityType, entityType));
            }

            return(map);
        }
Esempio n. 10
0
        /// <summary>
        /// Overrides the controlled instance
        /// </summary>
        /// <typeparam name="T">Old controlled instance</typeparam>
        /// <typeparam name="T2">Overriding instance</typeparam>
        protected void OverrideControlledInstance <T, T2>()   where T : AbstractedSubController
            where T2 : new()
        {
            var oldController = _abstractedSubControllers.FirstOrDefault(x => x is T);

            if (typeof(T2) == typeof(T) || oldController == null)
            {
                // nothing to override
                return;
            }

            var instance = new T2();

            var controller = instance as AbstractedSubController;

            if (controller == null)
            {
                return;
            }

            controller.Character = Character;

            oldController.OnOverwritten();

            _abstractedSubControllers =
                new ConcurrentBag <AbstractedSubController>(_abstractedSubControllers.Except(new[] { oldController }))
            {
                controller
            };

            controller.OnAdded();
        }
        /// <summary>
        /// Update the changed streams, remove those that are not mentioned
        /// in streams config.
        /// </summary>
        public void UpdateStreams()
        {
            var mentionedProcNames = new HashSet <string>();

            foreach (var streamCfg in _streamsConfig.StreamSources)
            {
                var procEntry =
                    processes.FirstOrDefault(x => x.Name == streamCfg.Name);

                if (procEntry == null ||
                    procEntry.Proc == null ||
                    procEntry.Proc.HasExited)
                {
                    StartChunkingTask(streamCfg);
                }
                else if (procEntry.Hash != streamCfg.GetHashCode())
                {
                    procEntry.Restart(() => StartChunkingTask(streamCfg));
                }

                mentionedProcNames.Add(streamCfg.Name);
            }

            var removedProcs =
                processes.Where(x => !mentionedProcNames.Contains(x.Name));

            foreach (var procEntry in removedProcs)
            {
                procEntry.CloseProcess();
            }
        }
Esempio n. 12
0
 public async Task <bool> PlayMusic(string mark, string filePath, double volume, bool isRepeat)
 {
     if (MusicMarks.FirstOrDefault(s => s == mark) == null)
     {
         MusicMarks.Add(mark);
     }
     return(await MusicSourceService.PlayMusic(mark, filePath, volume, isRepeat));
 }
Esempio n. 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        public void Accept(long id)
        {
            var m = _log.FirstOrDefault(_ => _.Id == id);

            if (null != m)
            {
                m.Accepted = true;
            }
        }
Esempio n. 14
0
        public void ProcessOrders(Product prod, string who = default)
        {
            Product product = products.FirstOrDefault(pr => pr.Name == prod.Name);

            if (product?.Quantity >= prod.Quantity)
            {
                product.Quantity -= prod.Quantity;
                Console.WriteLine($"{prod.Name} - {prod.Quantity}шт");
            }
        }
Esempio n. 15
0
        public static async Task<T> GetOrCreateAsync<T>(object key, Func<ICacheEntry, Task<T>> factory)
        {
            lock (Lock)
            {
                if (CacheKeys.FirstOrDefault(w => w == key) == null)
                    CacheKeys.Add(key);
            }

            return await Cache.GetOrCreateAsync(key, factory);
        }
Esempio n. 16
0
        public async Task SetName(string userName)
        {
            if (chatUsers.FirstOrDefault(p => p.ChatUserName == userName) != null)
            {
                await Clients.Caller.SendAsync("ReceiveMessage", userName + "has been used by another user");

                return;
            }
            chatUsers.First(p => p.ConnectionId == Context.ConnectionId).ChatUserName = userName;
            await Clients.Caller.SendAsync("ReceiveMessage", "set name success");
        }
Esempio n. 17
0
        public void FindOpponent()
        {
            //// First fetch the player from our players collection having current connection id
            var player = mathPlayers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);

            if (player == null)
            {
                //// Since player would be registered before making this call,
                //// we should not reach here. If we are here, something somewhere in the flow above is broken.
                return;
            }

            //// Set that player is seraching for opponent.
            player.IsSearchingOpponent = true;

            //// We will follow a queue, so find a player who registered earlier as opponent.
            //// This would only be the case if more than 2 players are looking for opponent.
            var opponent = mathPlayers.Where(x => x.ConnectionId != Context.ConnectionId && x.IsSearchingOpponent && !x.IsPlaying).OrderBy(x => x.RegisterTime).FirstOrDefault();

            if (opponent == null)
            {
                //// Could not find any opponent, invoke opponentNotFound method in the client.
                Clients.Client(Context.ConnectionId).InvokeAsync(Constants.OpponentNotFound, mathPlayers);
                return;
            }

            //// Set both players as playing.
            player.IsPlaying           = true;
            player.IsSearchingOpponent = false;             //// Make him unsearchable for opponent search

            opponent.IsPlaying           = true;
            opponent.IsSearchingOpponent = false;

            //// Set each other as opponents.
            //player.Opponent = opponent;
            //opponent.Opponent = player;

            //// Notify both players that they can play the game by invoking opponentFound method for both the players.
            //// Also pass the opponent name and opoonet image, so that they can visualize it.
            //// Here we are directly using connection id, but group is a good candidate and use here.
            //Clients.Client(Context.ConnectionId).InvokeAsync(Constants.OpponentFound, opponent.Name, opponent.Image);
            //Clients.Client(opponent.ConnectionId).InvokeAsync(Constants.OpponentFound, player.Name, player.Image);

            var newGame = new MathGame(player, opponent);

            mathGames.Add(newGame);

            Clients.All.InvokeAsync("hello");
            Clients.All.InvokeAsync("startMathGame", newGame);
            //Clients.User(newGame.Player2.ConnectionId).InvokeAsync("startMathGame", newGame);
            //// Create a new game with these 2 player and add it to games collection.

            //StartGame(newGame);
        }
Esempio n. 18
0
        public ConnectionPool FindPool(int type)
        {
            ConnectionPool p = _pools.FirstOrDefault(f => f.Type == type);

            if (p == null)
            {
                p = new ConnectionPool((byte)type);
                _pools.Add(p);
            }
            return(p);
        }
        public void ConnectAsViewer(EndPoint endPoint, Paket paket)
        {
            var senderId = GetIdFromEndPoint(((IPEndPoint)endPoint));
            var client   = _clients.FirstOrDefault(c => c.Id.ToString() == senderId);

            if (client != null)
            {
                client.JobId    = Encoding.UTF8.GetString(paket.Data);
                client.IsMaster = true;
            }
            Console.WriteLine($"viewer {senderId} connected");
        }
Esempio n. 20
0
        /// <summary>
        /// 查询实体类信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static EntityObject QueryEntity(Type entity)
        {
            var entityType = EntitieList.FirstOrDefault(x => x.Type.FullName.Equals(entity.FullName));

            if (entityType != null)
            {
                return(entityType);
            }
            else
            {
                return(Register(entity));
            }
        }
Esempio n. 21
0
        public Type GetSubTypeRegistered(Type baseType)
        {
            var type = _registrations.FirstOrDefault(reg => baseType.IsAssignableFrom(reg.Type) && reg.Type != baseType);

            if (type != null)
            {
                return(type.Type);
            }

            type = _registrations.FirstOrDefault(reg => reg.Implementation != null &&
                                                 baseType.IsAssignableFrom(reg.Implementation));
            return(type?.Implementation);
        }
        public MockSocket GetReceivingSocket()
        {
            MockSocket  socket          = null;
            var         retries         = socketWaitRetries;
            Func <bool> socketIsMissing = () => socket == null;

            while (retries-- > 0 && socketIsMissing())
            {
                socket = sockets.FirstOrDefault(s => s.GetIdentity() != null);
                Wait(socketIsMissing);
            }
            return(socket);
        }
Esempio n. 23
0
        /// <summary>
        /// Creates a new instance of the specified type asyncronously.
        /// </summary>
        /// <typeparam name="TInterface">The type of the interface.</typeparam>
        /// <returns></returns>
        public async Task <TInterface> CreateInstanceAsync <TInterface>() where TInterface : class
        {
            return(await Task.Run(() =>
            {
                BindingStructure binding = _objects.FirstOrDefault(x => x.BindingType == typeof(TInterface));
                if (binding.ConcreteType == null || binding.BindingType == null)
                {
                    return default(TInterface);
                }

                return Activator.CreateInstance(binding.ConcreteType, binding.Parameters) as TInterface;
            }));
        }
Esempio n. 24
0
        //public MockSocket GetRouterSocket()
        //{
        //    MockSocket socket = null;
        //    var retries = socketWaitRetries;

        //    while (retries-- > 0 && socket == null)
        //    {
        //        socket = sockets.FirstOrDefault(IsRouterSocket);
        //        Wait(socket);
        //    }

        //    return socket;
        //}

        //private bool IsRouterSocket(MockSocket s)
        //    => Equals(s?.GetIdentity(), config.RouterAddress.Identity);

        public MockSocket GetScaleoutFrontendSocket()
        {
            MockSocket socket  = null;
            var        retries = socketWaitRetries;

            while (retries-- > 0 && socket == null)
            {
                socket = sockets.FirstOrDefault(IsScaleOutFrontendSocket);
                Wait(socket);
            }

            return(socket);
        }
        public void Delete(string id)
        {
            var person = _persons.FirstOrDefault(p => p.Id == id);

            if (person != null)
            {
                if (!_persons.TryTake(out person))
                {
                    throw new InvalidOperationException("删除失败");
                }
                return;
            }
            throw new InvalidOperationException("该对象不存在");
        }
        private void AddWebClientToRoom(WebClientActionJoin webClientActionJoin, IWebSocketConnection connection)
        {
            var room = _socketRooms.FirstOrDefault(x => x.ConnectedClients.Any(client => client.RfIdCardNumber == webClientActionJoin.RfIdCardNo));

            if (room == null)
            {
                room = new SocketRoom();
            }

            var newClient = new BrowserSocketClient(room, connection, webClientActionJoin.RfIdCardNo);

            room.AddClient(newClient);

            _joinedClients.TryAdd(connection, newClient);
        }
Esempio n. 27
0
        public T GetDeviceByName <T>(string name) where T : MiHomeDevice
        {
            var device = _devicesList.FirstOrDefault(x => x.Name == name);

            switch (device)
            {
            case null:
                return(null);

            case T _:
                return(_devicesList.First(x => x.Name == name) as T);
            }

            throw new InvalidCastException($"Device with name '{name}' cannot be converted to {nameof(T)}");
        }
Esempio n. 28
0
        private Classifier.IInputData Read(int rowID, ConcurrentBag <Plot> bag)
        {
            Monitor.Enter(Plots);
            var    row     = Plots.Rows[rowID];
            string cad_num = row["CAD_NUM"];
            string vri_doc = row["VRI_DOC"];
            int    area    = (int)(row["Площадь"] * 10000);

            Monitor.Exit(Plots);

            if (String.IsNullOrEmpty(cad_num))
            {
                return(null);
            }
            var plot = bag.FirstOrDefault(p => p.CadNum.Equals(cad_num, StringComparison.InvariantCulture));

            if (plot != null)
            {
                return(new Classifier.InputDataDB(plot, area));
            }
            else
            {
                string bti_code = "";
                bool   lo       = false;
                bool   mid      = false;
                bool   hi       = false;
                return(new Classifier.InputData(vri_doc, area, bti_code, lo, mid, hi));
            }
        }
Esempio n. 29
0
        private IChutzpahWebServerHost SetupWebServerHost(ConcurrentBag <TestContext> testContexts, TestOptions options)
        {
            var needsServer = options.Engine.GetValueOrDefault() != Engine.Phantom;

            IChutzpahWebServerHost webServerHost     = null;
            var contextUsingWebServer                = testContexts.Where(x => x.TestFileSettings.Server?.Enabled.GetValueOrDefault() == true).ToList();
            var contextWithChosenServerConfiguration = contextUsingWebServer.FirstOrDefault();

            if (contextWithChosenServerConfiguration == null && needsServer)
            {
                foreach (var testContext in testContexts)
                {
                    testContext.TestFileSettings.Server = ForcedChutzpahWebServerConfiguration.Instance;
                }

                contextUsingWebServer = testContexts.ToList();
                contextWithChosenServerConfiguration = testContexts.FirstOrDefault();
            }

            if (contextWithChosenServerConfiguration != null)
            {
                var webServerConfiguration = contextWithChosenServerConfiguration.TestFileSettings.Server;
                webServerHost = webServerFactory.CreateServer(webServerConfiguration, ActiveWebServerHost);

                // Stash host object on context for use in url generation
                contextUsingWebServer.ForEach(x => x.WebServerHost = webServerHost);
            }

            return(webServerHost);
        }
Esempio n. 30
0
        private List <Discrepancy> GetDescrepancies()
        {
            List <Discrepancy> discrepancies       = new List <Discrepancy>();
            List <PageResult>  expectedCrawlResult = GetExpectedCrawlResult();

            foreach (PageResult actualPage in _actualCrawledPages)
            {
                Discrepancy discrepancy = ReturnIfIsADiscrepency(expectedCrawlResult.FirstOrDefault(p => p.Url == actualPage.Url), actualPage);
                if (discrepancy != null)
                {
                    discrepancies.Add(discrepancy);
                }
            }

            if (expectedCrawlResult.Count != _actualCrawledPages.Count)
            {
                foreach (PageResult expectedPage in expectedCrawlResult)
                {
                    PageResult expectedPageInActualResult = _actualCrawledPages.FirstOrDefault(a => a.Url == expectedPage.Url);
                    if (expectedPageInActualResult == null)
                    {
                        discrepancies.Add(new Discrepancy {
                            Actual = null, Expected = expectedPage, DiscrepencyType = DiscrepencyType.MissingPageFromResult
                        });
                    }
                }
            }

            return(discrepancies);
        }
Esempio n. 31
0
        public void GetUriInParallelTest()
        {
            // arrange
            var request = new BasicRequest("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", new[] {"a", "b", "c"});
            var tileInfo = new TileInfo {Index = new TileIndex(3, 4, "5")};
            var urls = new ConcurrentBag<Uri>(); // List is not thread save

            // act
            var requests = new List<Func<Uri>>();
            for (var i = 0; i < 100; i++) requests.Add(() => request.GetUri(tileInfo));
            Parallel.ForEach(requests, r => urls.Add(r()));

            // assert
            Assert.True(urls.FirstOrDefault(u => u.ToString() == "http://b.tile.openstreetmap.org/5/3/4.png") != null);
        }
Esempio n. 32
0
        public void GetUriMultiThreadedTest()
        {
            // arrange
            var request = new BingRequest(
                "http://t{s}.tiles.virtualearth.net/tiles/r{quadkey}.jpeg?g={apiversion}&token={userkey}",
                "pindakaas", "555", new[] { "000", "111" });
            var tileInfo = new TileInfo { Index = new TileIndex(3, 4, "5") };
            var urls = new ConcurrentBag<Uri>(); // List is not thread save

            // act
            var requests = new List<Func<Uri>>();
            for (var i = 0 ; i < 100; i++) requests.Add(() => request.GetUri(tileInfo));
            Parallel.ForEach(requests, r => urls.Add(r()));

            // assert
            Assert.True(urls.FirstOrDefault(u => u.ToString() == "http://t111.tiles.virtualearth.net/tiles/r00211.jpeg?g=555&token=pindakaas") != null);
        }