public async void TestLeaderBoardCalculation()
        {
            // Setup
            var totalTimes = new[] { 2.2, 1.1, 3.3, 0.0, 0.0 };

            var runDaoMock = new Mock <IRunDao>();

            runDaoMock.Setup(d => d.GetAllRunsForRace(It.IsAny <Race>(), It.IsAny <int>()))
            .Returns(Task.FromResult(
                         totalTimes.Select(t => new Run {
                TotalTime = t
            })
                         ));

            var daoProvider = DaoProviderHelper.GetPartialDaoProvider(runDao: runDaoMock.Object);
            var runService  = new RunService(daoProvider, new SimulatorRaceClock());

            // Execute
            var leaderBoard = (await runService.GetLeaderBoard(null, 1)).ToArray();

            // Assert
            Assert.Equal(totalTimes.Length, leaderBoard.Length);
            Assert.Equal(1.1, leaderBoard[0].TotalTime);
            Assert.Equal(2.2, leaderBoard[1].TotalTime);
            Assert.Equal(3.3, leaderBoard[2].TotalTime);
            Assert.Equal(0.0, leaderBoard[3].TotalTime);
            Assert.Equal(0.0, leaderBoard[4].TotalTime);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Close the run
        /// </summary>
        void CloseRun()
        {
            var profile = _repository.Profiles.First();
            var run     = _repository.Runs.Find(profile.CurrentRunNumber);

            // if there are any incomplete calls return
            var calls = _repository.Calls.Where(x => x.RunNumber == run.RunNumber);

            if (calls.Any(x => !x.Visited))
            {
                var message = Resources.GetString(Resource.String.message_run_incomplete);
                UserDialogs.Instance.Alert(message);
                return;
            }

            var confirmConfig = new ConfirmConfig
            {
                Message  = Resources.GetString(Resource.String.message_close_run),
                OnAction = (confirm => {
                    if (confirm)
                    {
                        RunService.CloseRun(_repository, run);
                        Activity.RunOnUiThread(_fragmentActionListener.PopToRoot);
                    }
                })
            };

            UserDialogs.Instance.Confirm(confirmConfig);
        }
        /// <summary>
        /// Close Run Event
        /// </summary>
        void CloseRun()
        {
            var runNumber = _run.RunNumber;

            // if there are any incomplete calls return
            var calls = _repository.Calls.Where(x => x.RunNumber == runNumber);

            if (calls.Any(x => !x.Visited))
            {
                var message = Resources.GetString(Resource.String.message_run_incomplete);
                UserDialogs.Instance.Alert(message);
                return;
            }

            var confirmConfig = new ConfirmConfig
            {
                Message  = Resources.GetString(Resource.String.message_close_run),
                OnAction = (confirm => {
                    if (confirm)
                    {
                        // because we are on a seperate thread we need a new realm
                        var run = _repository.Runs.Find(runNumber);
                        RunService.CloseRun(_repository, run);
                        RefreshData();
                    }
                })
            };

            UserDialogs.Instance.Confirm(confirmConfig);
        }
Ejemplo n.º 4
0
        private SubmitRunResult Run(Task task, string input, string runString)
        {
            var runService    = new RunService(_runnerPath, _workingDirectory);
            var configuration = new Configuration(runString, _workingDirectory, task.TimeLimitMilliseconds, task.MemoryLimitBytes);

            configuration.InputFile  = input;
            configuration.OutputFile = "output.txt"; //TODO

            var runResult = runService.Run(configuration);

            var result = new SubmitRunResult
            {
                Description              = runResult.Description,
                Output                   = runResult.Output,
                PeakMemoryBytes          = runResult.PeakMemoryBytes,
                RunStatus                = runResult.RunStatus,
                TextStatus               = runResult.TextStatus,
                TimeConsumedMilliseconds = runResult.TimeConsumedMilliseconds,
                TimePassedMilliseconds   = runResult.TimePassedMilliseconds
            };

            if (runResult.RunStatus == RunStatus.Success)
            {
                var checkAnswerResult = CheckAnswer(configuration);
                result.CheckMessage = checkAnswerResult.Message;
                result.CheckStatus  = checkAnswerResult.CheckStatus;
            }

            return(result);
        }
        public void TestRunStatusChangedEventInvocation()
        {
            // Setup
            var runDaoMock = new Mock <IRunDao>();

            runDaoMock.Setup(d => d.GetBySkierAndRace(It.IsAny <Race>(), It.IsAny <int>(), It.IsAny <Skier>()))
            .Returns(Task.FromResult(
                         new Run {
                Status = RunStatus.Ready
            })
                     );

            var daoProvider = DaoProviderHelper.GetPartialDaoProvider(runDao: runDaoMock.Object);
            var runService  = new RunService(daoProvider, new SimulatorRaceClock());

            var eventTriggered = false;

            runService.RunStatusChanged += (race, runNumber, skier, runStatus) => eventTriggered = true;

            // Execute
            runService.UpdateRunStatus(null, 1, null, RunStatus.InProgress);

            // Assert
            Assert.True(eventTriggered);
        }
Ejemplo n.º 6
0
            public virtual void Dispose()
            {
                runService = null; //service

                if (list != null)
                {
                    if (list.Count > 0)
                    {
                        foreach (Node n in list)
                        {
                            n.Dispose();
                        }
                    }

                    list.Clear();
                }

                list = null;

                if (activity != null)
                {
                    activity.Dispose();
                }

                activity = null;
            }
        public async void TestInterimTimesCalculation()
        {
            // Setup
            var timestamps = new[] { 1576850000.000, 1576850001.111, 1576850002.222 };

            var sensorMeasurementDaoMock = new Mock <ISensorMeasurementDao>();

            sensorMeasurementDaoMock.Setup(d => d.GetMeasurementsForRun(It.IsAny <Run>()))
            .Returns(Task.FromResult(
                         timestamps.Select(t => new SensorMeasurement {
                Timestamp = t
            })
                         ));

            var runDaoMock = new Mock <IRunDao>();

            runDaoMock.Setup(d => d.GetBySkierAndRace(It.IsAny <Race>(), It.IsAny <int>(), It.IsAny <Skier>()))
            .Returns(Task.FromResult(new Run()));

            var daoProvider = DaoProviderHelper.GetPartialDaoProvider(
                sensorMeasurementDao: sensorMeasurementDaoMock.Object,
                runDao: runDaoMock.Object
                );
            var runService = new RunService(daoProvider, new SimulatorRaceClock());

            // Execute
            var calculatedTimespans = (await runService.GetInterimTimes(null, 1, null)).ToArray();

            // Assert
            Assert.Equal(timestamps.Length - 1, calculatedTimespans.Length);
            Assert.Equal(calculatedTimespans[0], TimeSpan.FromSeconds(timestamps[1] - timestamps[0]));
            Assert.Equal(calculatedTimespans[1], TimeSpan.FromSeconds(timestamps[2] - timestamps[0]));
        }
Ejemplo n.º 8
0
        protected override void CreateComponents()
        {
            RunServiceImpl = new RunService(RunWindowStrategy.WinForms);
            ServiceImpl    = CreateMainService();

            AddComponent(RunService);
            AddComponent(Service);
        }
Ejemplo n.º 9
0
        public void RunCmdTest()
        {
            var service = new RunService(_runnerPath, _workingDirectory);

            var configuration = new Configuration("cmd", _workingDirectory, 1000, 10 * 1024 * 1024);

            service.Run(configuration);
        }
Ejemplo n.º 10
0
        public void TestQuery()
        {
            int expected = 10;
            var service  = new RunService(_booksContext);
            var result   = service.QueryBooks();

            Assert.Equal(expected, result.Count());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Remove call
        /// </summary>
        /// <param name="adapterPosition">Index.</param>
        void RemoveCall(int adapterPosition)
        {
            var call = _calls[adapterPosition];

            RunService.RemoveCall(_repository, call);

            _adapter.NotifyItemRemoved(adapterPosition);
            TogglePlaceholderVisibility();
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Remove Call
 /// </summary>
 /// <param name="adapterPosition">Adapter position.</param>
 /// <param name="action">Action.</param>
 void OnCallAction(int adapterPosition, CallViewHolderAction action)
 {
     if (action == CallViewHolderAction.Remove)
     {
         var call = _calls[adapterPosition];
         RunService.RemoveCall(_repository, call);
         //_adapter.NotifyItemChanged(adapterPosition);
     }
 }
Ejemplo n.º 13
0
        public void MemoryLimitTest()
        {
            var service = new RunService(_runnerPath, _workingDirectory);

            var configuration = new Configuration(@"notepad", _workingDirectory, 1000, 10 * 1024);

            var result = service.Run(configuration);

            Assert.That(result.RunStatus, Is.EqualTo(RunStatus.MemoryLimitExceeded));
        }
Ejemplo n.º 14
0
        public void RuntimeErrorSolutionTest()
        {
            var service = new RunService(_runnerPath, _workingDirectory);

            var fileName      = Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestSolutions\RuntimeError.exe");
            var configuration = new Configuration(fileName, _workingDirectory, 1000, 10 * 1024 * 1024);

            var result = service.Run(configuration);

            Assert.That(result.RunStatus, Is.EqualTo(RunStatus.RuntimeError));
        }
Ejemplo n.º 15
0
        public void SetUp()
        {
            _fileServiceMock         = new Mock <IFileService>();
            _parserServiceMock       = new Mock <IParserService>();
            _userFeedbackServiceMock = new Mock <IUserFeedbackService>();

            _sut = new RunService(
                _fileServiceMock.Object,
                _parserServiceMock.Object,
                _userFeedbackServiceMock.Object);

            fixture = new Fixture();
        }
Ejemplo n.º 16
0
        public void InvocationFailedTest()
        {
            var service = new RunService(_runnerPath, _workingDirectory);

            var fileName      = Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestSolutions\AB.exe");
            var configuration = new Configuration(fileName, _workingDirectory, 1000, 10 * 1024 * 1024)
            {
                InputFile  = "input.txt",
                OutputFile = "output.txt"
            };

            var result = service.Run(configuration);

            Assert.That(result.RunStatus, Is.EqualTo(RunStatus.InvocationFailed));
        }
Ejemplo n.º 17
0
            internal static void Start(object obj)
            {
                _queue = new ConcurrentWorkQueue <Action>(action => action());

                Game.Init();
                RunService.Init();
                SocialService.Init();
                HttpService.Init();
                ScriptService.Init();
                //AnalyticsService.Init();

                _resetter.Set();
                var stopwatch        = Stopwatch.StartNew();
                var physicsStopwatch = Stopwatch.StartNew();

                while (!CancelTokenSource.IsCancellationRequested)
                {
                    var step = stopwatch.Elapsed.TotalSeconds;
                    stopwatch.Restart();

                    // User Input
                    InputService.Step();

                    Game.FocusedCamera?.UpdateCamera(step);

                    // Network Replication
                    Game.NetworkServer?.Update(step);
                    Game.NetworkClient?.Update(step);

                    // wait() resume
                    ScriptService.ResumeWaitingScripts();

                    // Stepped
                    RunService.Update(step);
                    _queue.Work();

                    // Physics
                    var physicsStep = (float)physicsStopwatch.Elapsed.TotalSeconds;
                    foreach (var world in Game.Worlds)
                    {
                        world.Key.Physics?.Step(physicsStep);
                    }
                    physicsStopwatch.Restart();

                    // Heartbeat
                    RunService.Service.Heartbeat.Fire(step);
                }
            }
            public void ThrowArgumentNullExceptionWhenPassedCategoryNameIsEmpty()
            {
                //Arrange
                var mockedRunRepository = new Mock <IRunRepository>();
                Func <IUnitOfWork> mockedUnitOfWorkFactory = () => { return(new Mock <IUnitOfWork>().Object); };
                var    serviceUnderTest         = new RunService(mockedRunRepository.Object, mockedUnitOfWorkFactory);
                string expectedExceptionMessage = "categoryName";

                //Act
                var exc = Assert.Throws <ArgumentException>(() => {
                    serviceUnderTest.GetRunsInCategory("");
                });

                //Assert
                StringAssert.Contains(expectedExceptionMessage, exc.Message);
            }
Ejemplo n.º 19
0
        /// <summary>
        /// Commit the run
        /// </summary>
        void CommitRun(bool pop)
        {
            var runName = _runNameEditText.Text;

            if (string.IsNullOrWhiteSpace(runName))
            {
                runName = _run.RunNumber;
            }

            RunService.UpdateRunName(_repository, _run, runName);

            if (pop)
            {
                _fragmentActionListener.Pop();
            }
        }
Ejemplo n.º 20
0
        public async Task PostRunOk()
        {
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddJsonFile("AppSettings.json");
            IConfiguration configuration = configurationBuilder.Build();

            RunService srv =
                new RunService(
                    new DBRunContext(new DbContextOptionsBuilder <DBRunContext>().UseInMemoryDatabase("DBRuns").Options),
                    configuration
                    );

            RunsController rc       = new RunsController(srv);
            var            identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "00000000-0000-0000-0000-000000000000"));
            identity.AddClaim(new Claim(ClaimTypes.Role, "USER"));

            rc.ControllerContext             = new ControllerContext();
            rc.ControllerContext.HttpContext = new DefaultHttpContext();
            rc.HttpContext.User = new ClaimsPrincipal(identity);



            // Arrange
            RunInput runInput01 =
                new RunInput()
            {
                Date     = new System.DateTime(2020, 6, 20, 19, 51, 0),
                Distance = 5600,
                Time     = 1100,
                Location = "Poggibonsi,IT"
            };


            // Act
            IActionResult retValue =
                await rc.PostRun(
                    new Guid("00000000-0000-0000-0000-000000000000"),
                    runInput01
                    );


            // Assert
            Assert.IsTrue(retValue is OkResult);
        }
Ejemplo n.º 21
0
        public void SetUp()
        {
            _csvServiceMock          = new Mock <ICsvService>();
            _enrollmentServiceMock   = new Mock <IEnrollmentObjectService>();
            _fileServiceMock         = new Mock <IFileService>();
            _userFeedbackServiceMock = new Mock <IUserFeedbackService>();
            _jsonServiceMock         = new Mock <IJsonService>();

            _sut = new RunService(
                _csvServiceMock.Object,
                _enrollmentServiceMock.Object,
                _fileServiceMock.Object,
                _userFeedbackServiceMock.Object,
                _jsonServiceMock.Object);

            fixture = new Fixture();
        }
Ejemplo n.º 22
0
        protected override void CreateComponents()
        {
            RunServiceImpl       = new RunService(RunWindowStrategy.WinForms);
            KeyServiceImpl       = new KeyServiceHotKey(RunServiceImpl);
            RectangleServiceImpl = new RectangleService();
            WindowOsServiceImpl  = new WindowOsService();
            WindowRepositoryImpl = new WindowRepository(new WindowId.WindowIdEqualityComparer());
            ScreenOsServiceImpl  = new ScreenOsService();
            ScreenRepositoryImpl = new ScreenRepository();

            AddComponent(RunService);
            AddComponent(KeyService);
            AddComponent(RectangleService);
            AddComponent(WindowOsService);
            AddComponent(WindowRepository);
            AddComponent(ScreenOsService);
            AddComponent(ScreenRepository);
        }
Ejemplo n.º 23
0
        public void UseFilesTest()
        {
            using (var input = CreateFile("input.txt"))
            {
                input.Write("1 2");
            }

            var service = new RunService(_runnerPath, _workingDirectory);

            var fileName      = Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestSolutions\AB.exe");
            var configuration = new Configuration(fileName, _workingDirectory, 1000, 10 * 1024 * 1024)
            {
                InputFile  = "input.txt",
                OutputFile = "output.txt"
            };

            var result = service.Run(configuration);

            Assert.That(result.RunStatus, Is.EqualTo(RunStatus.Success));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Get data
        /// </summary>
        void GetData(Bundle savedInstanceState)
        {
            // try to get the run row guid from memory - potential set by activityresult
            if (_runNumber == null)
            {
                // try to get it from saved state, and finally from arguments
                _runNumber = savedInstanceState != null?
                             savedInstanceState.GetString(BundleArguments.RunNumber) : Arguments.GetString(BundleArguments.RunNumber);
            }

            // if the row run guid doesn't exist create a new run
            _run = _runNumber == null?RunService.CreateRun(_repository) : _repository.Find <Run>(_runNumber);

            // set the run row guid for persisting
            _runNumber = _run.RunNumber;

            _calls = _repository.Calls
                     .Where(x => x.RunNumber == _runNumber && !x.Removed)
                     .OrderBy(x => x.Sequence)
                     .ToList();
        }
Ejemplo n.º 25
0
        public async Task InsertOk()
        {
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddJsonFile("AppSettings.json");
            IConfiguration configuration = configurationBuilder.Build();

            RunService srv =
                new RunService(
                    new DBRunContext(new DbContextOptionsBuilder <DBRunContext>().UseInMemoryDatabase("DBRuns").Options),
                    configuration
                    );


            // Arrange
            int expected = 1;

            RunInput runInput01 =
                new RunInput()
            {
                Date     = new System.DateTime(2020, 6, 20, 19, 51, 0),
                Distance = 5600,
                Time     = 1100,
                Location = "Poggibonsi,IT"
            };


            // Act
            int retValue =
                await srv.InsertRunAsync(
                    new Guid("00000000-0000-0000-0000-000000000000"),
                    runInput01
                    );


            // Assert
            int actual = retValue;

            Assert.AreEqual(expected, actual, 0, "Ok, record inserted");
        }
Ejemplo n.º 26
0
        public static void RunGetDeltasBatch()
        {
            var subscription = new Subscription(88L, String.Empty);
            var runId        = RunService.StartRun(subscription.SubscriptionDataSetId, "SET_DELTA");

            try {
                RunResultType <TesterEntity> result;
                using (var uow = new UnitOfWork(DatabaseUtil.GetConnection())) {
                    var x = Api.Publisher.PushEvent(EventCacheLockingStrategyType.BypassCacheLocking);

                    using var repoCache = new CacheEntryRepository <TesterEntity>(uow);
                    result = Api.Subscriber.PullBatchDeltas(
                        subscription,
                        runId,
                        Util.PullPublisherDataSet,
                        EmptyPublisherDataSetGetDeltasStrategyType.DefaultProcessingDeleteAll,
                        TesterEntity.IsEqual,
                        Api.Subscriber.CreateCacheOperationBatch <long, TesterEntity>(
                            repoCache.BeginTransaction,
                            repoCache.CommitTransaction,
                            repoCache.RollbackTransaction,
                            repoCache.GetRunIdMaxOfDataSet,

                            repoCache.Insert <long, TesterEntity>,
                            repoCache.Update <long, TesterEntity>,
                            repoCache.GetNewestById <long, TesterEntity>,
                            repoCache.GetDataSetRunExcludingDeltaState <long, TesterEntity>));

                    var messages = result.DeltaSnapshots.ToList();
                }
                Console.WriteLine("CONSUMER: " + (result.IsSuccess ? "SUCCESS" : "FAILURE") + " " + result.ErrorMsgs.FirstOrDefault()
                                  + $" RunId:{result.RunId} DataSetCount:{result.DataSetCount} DeltaCount:{result.DeltaCount}");

                RunService.CompleteRun(result.RunId, result.IsSuccess, result.IsSuccess ? null : result.ErrorMsgs.FirstOrDefault(), result.DataSetCount, result.DeltaCount);
            } catch (Exception ex) {
                Console.WriteLine($"CONSUMER: {ex.Message}");
                RunService.CompleteRun(runId, false, ex.Message, 0, 0);
            }
        }
Ejemplo n.º 27
0
        public async Task InsertDistanceTimeLEZero(int distance, int time)
        {
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddJsonFile("AppSettings.json");
            IConfiguration configuration = configurationBuilder.Build();

            RunService srv =
                new RunService(
                    new DBRunContext(new DbContextOptionsBuilder <DBRunContext>().UseInMemoryDatabase("DBRuns").Options),
                    configuration
                    );



            // Arrange
            RunInput runInput01 =
                new RunInput()
            {
                Date     = new System.DateTime(2020, 6, 20, 19, 51, 0),
                Distance = distance,
                Time     = time,
                Location = "Poggibonsi,IT"
            };



            // Assert
            await Assert.ThrowsExceptionAsync <ArgumentOutOfRangeException>(
                () =>
                srv.InsertRunAsync(
                    new Guid("00000000-0000-0000-0000-000000000000"),
                    runInput01
                    )
                );
        }
Ejemplo n.º 28
0
        void RgtWarning(int d, int p)
        {
            RGTPOSManager       RGTPOSMgr       = new RGTPOSManager();
            AssayRunParaService AssayRunParaSer = new AssayRunParaService();
            RunService          RunSer          = new RunService();
            TroubleLogService   TroubleLogSer   = new TroubleLogService();

            int rgtwarncount  = RunSer.GetRgtWarnCount();
            int rgtleastcount = RunSer.GetRgtLeastCount();

            RGTPosition rgp = RGTPOSMgr.Get(1, p.ToString());

            if (rgp != null)
            {
                AssayRunPara arp = AssayRunParaSer.Get(rgp.Assay) as AssayRunPara;
                int          c   = 0;
                int          v   = rgp.CType.Volume * rgp.ValidPercent / 100 * 1000;
                switch (rgp.AssayPara)
                {
                case "R1":
                    c = arp.R1Vol == 0 ? 0 : v / arp.R1Vol;
                    if (c < rgtleastcount)
                    {
                        if (RunSer.IsMutiRgtEnable() == true)    //多试剂位开关标志
                        {
                            RGTPosition mrgt = RGTPOSMgr.GetEnableMutiRgtPosition(rgp);
                            if (mrgt != null)
                            {
                                RGTPOSMgr.BetweenMutiRgtPositionAndRgtPositionChange(mrgt, rgp);

                                TroubleLog trouble = new TroubleLog();
                                trouble.TroubleCode = @"0000773";
                                trouble.TroubleType = TROUBLETYPE.WARN;
                                trouble.TroubleUnit = @"试剂";
                                trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂1由于余量不足开始启用其多试剂位{2}. ", p, rgp.Assay, mrgt.Position);
                                TroubleLogSer.Save(trouble);
                            }
                            else
                            {
                                if (RunSer.IsLockRgtEnable() == true)
                                {
                                    rgp.IsLocked = true;
                                    RGTPOSMgr.UpdateLockState(rgp);

                                    TroubleLog trouble = new TroubleLog();
                                    trouble.TroubleCode = @"0000773";
                                    trouble.TroubleType = TROUBLETYPE.WARN;
                                    trouble.TroubleUnit = @"试剂";
                                    trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂1由于余量不足将锁定其对应的工作表. ", p, rgp.Assay);
                                    TroubleLogSer.Save(trouble);
                                }
                                else
                                {
                                    TroubleLog trouble = new TroubleLog();
                                    trouble.TroubleCode = @"0000773";
                                    trouble.TroubleType = TROUBLETYPE.ERR;
                                    trouble.TroubleUnit = @"试剂";
                                    trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂1由于余量不足. ", p, rgp.Assay);
                                    TroubleLogSer.Save(trouble);
                                }
                            }
                        }
                        else
                        {
                            if (RunSer.IsLockRgtEnable() == true)
                            {
                                rgp.IsLocked = true;
                                RGTPOSMgr.UpdateLockState(rgp);

                                TroubleLog trouble = new TroubleLog();
                                trouble.TroubleCode = @"0000773";
                                trouble.TroubleType = TROUBLETYPE.WARN;
                                trouble.TroubleUnit = @"试剂";
                                trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂1由于余量不足将锁定其对应的工作表. ", p, rgp.Assay);
                                TroubleLogSer.Save(trouble);
                            }
                            else
                            {
                                TroubleLog trouble = new TroubleLog();
                                trouble.TroubleCode = @"0000773";
                                trouble.TroubleType = TROUBLETYPE.ERR;
                                trouble.TroubleUnit = @"试剂";
                                trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂1由于余量不足. ", p, rgp.Assay);
                                TroubleLogSer.Save(trouble);
                            }
                        }
                    }

                    if (c < rgtwarncount && c > rgtleastcount)
                    {
                        TroubleLog trouble = new TroubleLog();
                        trouble.TroubleCode = @"0000773";
                        trouble.TroubleType = TROUBLETYPE.WARN;
                        trouble.TroubleUnit = @"设备";
                        trouble.TroubleInfo = string.Format("试剂位{0}项目{1}:试剂1余量即将耗尽. ", p, rgp.Assay);
                        TroubleLogSer.Save(trouble);
                        return;
                    }
                    break;

                case "R2":
                    c = arp.R2Vol == 0 ? 0 : v / arp.R2Vol;
                    if (c < rgtleastcount)
                    {
                        if (RunSer.IsMutiRgtEnable() == true)    //多试剂位开关标志
                        {
                            RGTPosition mrgt = RGTPOSMgr.GetEnableMutiRgtPosition(rgp);
                            if (mrgt != null)
                            {
                                RGTPOSMgr.BetweenMutiRgtPositionAndRgtPositionChange(mrgt, rgp);

                                TroubleLog trouble = new TroubleLog();
                                trouble.TroubleCode = @"0000773";
                                trouble.TroubleType = TROUBLETYPE.WARN;
                                trouble.TroubleUnit = @"试剂";
                                trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂2由于余量不足开始启用其多试剂位{2}. ", p, rgp.Assay, mrgt.Position);
                                TroubleLogSer.Save(trouble);
                            }
                            else
                            {
                                if (RunSer.IsLockRgtEnable() == true)
                                {
                                    rgp.IsLocked = true;
                                    RGTPOSMgr.UpdateLockState(rgp);

                                    TroubleLog trouble = new TroubleLog();
                                    trouble.TroubleCode = @"0000773";
                                    trouble.TroubleType = TROUBLETYPE.WARN;
                                    trouble.TroubleUnit = @"试剂";
                                    trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂2由于余量不足将锁定其对应的工作表. ", p, rgp.Assay);
                                    TroubleLogSer.Save(trouble);
                                }
                                else
                                {
                                    TroubleLog trouble = new TroubleLog();
                                    trouble.TroubleCode = @"0000773";
                                    trouble.TroubleType = TROUBLETYPE.ERR;
                                    trouble.TroubleUnit = @"试剂";
                                    trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂2余量不足. ", p, rgp.Assay);
                                    TroubleLogSer.Save(trouble);
                                }
                            }
                        }
                        else
                        {
                            if (RunSer.IsLockRgtEnable() == true)
                            {
                                rgp.IsLocked = true;
                                RGTPOSMgr.UpdateLockState(rgp);

                                TroubleLog trouble = new TroubleLog();
                                trouble.TroubleCode = @"0000773";
                                trouble.TroubleType = TROUBLETYPE.WARN;
                                trouble.TroubleUnit = @"试剂";
                                trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂2余量不足将锁定其对应的工作表. ", p, rgp.Assay);
                                TroubleLogSer.Save(trouble);
                            }
                            else
                            {
                                TroubleLog trouble = new TroubleLog();
                                trouble.TroubleCode = @"0000773";
                                trouble.TroubleType = TROUBLETYPE.ERR;
                                trouble.TroubleUnit = @"试剂";
                                trouble.TroubleInfo = string.Format("试剂位{0}项目{1}试剂2余量不足. ", p, rgp.Assay);
                                TroubleLogSer.Save(trouble);
                            }
                        }
                    }
                    if (c < rgtwarncount && c > rgtleastcount)
                    {
                        TroubleLog trouble = new TroubleLog();
                        trouble.TroubleCode = @"0000775";
                        trouble.TroubleType = TROUBLETYPE.WARN;
                        trouble.TroubleUnit = @"设备";
                        trouble.TroubleInfo = string.Format("试剂位{0}项目{1}:试剂2余量即将耗尽. ", p, rgp.Assay);
                        TroubleLogSer.Save(trouble);
                        return;
                    }
                    break;
                }
            }
        }
Ejemplo n.º 29
0
        public string Parse(List <byte> Data)
        {
            if (Data.Count < 904)
            {
                LogService.Log("非法数据包:" + MachineControlProtocol.BytelistToHexString(Data), LogType.Debug);
                return(null);
            }

            RunService             RunSer             = new RunService();
            RGTPOSManager          RGTPOSMgr          = new RGTPOSManager();
            TroubleLogService      TroubleLogSer      = new TroubleLogService();
            RealTimeCUVDataService RealTimeCUVDataSer = new RealTimeCUVDataService();

            int Pt1stWn  = 0;
            int Pt3ndWn  = 0;
            int Pt26thWn = 0;

            int BlkCUVNO = MachineControlProtocol.HexConverToDec(Data[904], Data[905], Data[906]);
            int BlkWN    = MachineControlProtocol.HexConverToDec(Data[2], Data[3], Data[4]);

            RealTimeCUVDataSer.SaveCuvNumber(BlkWN, BlkCUVNO);

            for (int i = 2; i < 886; i = i + 17)
            {
                int   WN  = MachineControlProtocol.HexConverToDec(Data[i], Data[i + 1], Data[i + 2]);
                int   PT  = MachineControlProtocol.HexConverToDec(Data[i + 3], Data[i + 4]);
                float PWL = MachineControlProtocol.HexConverToFloat(Data[i + 5], Data[i + 6], Data[i + 7], Data[i + 8], Data[i + 9], Data[i + 10]);
                float SWL = MachineControlProtocol.HexConverToFloat(Data[i + 11], Data[i + 12], Data[i + 13], Data[i + 14], Data[i + 15], Data[i + 16]);

                if (PWL > -0.000001 && PWL < 0.000001)
                {
                    PWL = 3.5f;
                }
                else
                {
                    PWL = (float)Math.Log10(10 / PWL) * MachineInfo.LightSpan;
                }
                if (SWL > -0.000001 && SWL < 0.000001)
                {
                    SWL = 3.5f;
                }
                else
                {
                    SWL = (float)Math.Log10(10 / SWL) * MachineInfo.LightSpan;
                }

                if (WN != 0 && PT != 0)
                {
                    RealTimeCUVDataService.SaveABS(WN, PT, PWL, SWL);
                }
                if (PT == 1)
                {
                    Pt1stWn = WN;
                }
                if (PT == 3)
                {
                    Pt3ndWn = WN;
                }
                if (PT == 26)
                {
                    Pt26thWn = WN;
                }

                //Console.WriteLine(string.Format("WN:{0}PT:{1}PWL:{2}SWL:{3}", WN, PT, PWL, SWL));
            }
            //温度
            float tcv = MachineControlProtocol.HexConverToFloat(Data[887], Data[888], Data[889], Data[890]);

            RunSer.UpdateLatestCUVPanelTemperature(tcv * 10);
            float tr1 = MachineControlProtocol.HexConverToFloat(Data[891], Data[892], Data[893], Data[894]);

            RunSer.UpdateLatestR1PanelTemperature(tr1 * 10);
            LogService.Log(string.Format("反应盘温度:{0};试剂盘温度 :{1}", tcv * 10, tr1 * 10), LogType.Debug);
            //试剂余量
            int R1P = MachineControlProtocol.HexConverToDec(Data[896], Data[897]);
            int R1V = MachineControlProtocol.HexConverToDec(Data[898], Data[899]);

            RGTPOSMgr.UpdateLatestRgtVol(1, R1P, R1V);
            RgtWarning(1, R1P);
            int R2P = MachineControlProtocol.HexConverToDec(Data[900], Data[901]);
            int R2V = MachineControlProtocol.HexConverToDec(Data[902], Data[903]);

            RGTPOSMgr.UpdateLatestRgtVol(1, R2P, R2V);
            RgtWarning(1, R2P);
            LogService.Log(string.Format("R1位置:{0} R1体积:{1} R2位置:{2} R2体积:{3}", R1P, R1V, R2P, R2V), LogType.Debug);
            //查找错误报头
            int erindex = 0;

            for (int i = 0; i < Data.Count(); i++)
            {
                if (Data[i] == 0x1C)
                {
                    erindex = i;
                    break;
                }
            }
            //错误信息
            if (Data[erindex] == 0x1C)
            {
                LogService.Log(MachineControlProtocol.BytelistToHexString(Data), LogType.Debug);

                int errcount = Data[erindex + 2] - 0x30;
                //Console.WriteLine(string.Format("there is {0} errors!", errcount));
                for (int i = 0; i < errcount; i++)
                {
                    int index = (erindex + 3) + i * 7;

                    string cmdname = string.Format("{0}{1}", (char)Data[index], (char)Data[index + 1]);
                    if (cmdname == "77" && Data[index + 2] == 0x30)//R1
                    {
                        RealTimeCUVDataService.RunningErrors(Pt1stWn, "R1");

                        Result r = new RealTimeCUVDataService().GetResultFromRealTimeWorkNum(Pt1stWn);
                        if (r != null)
                        {
                            TroubleLog trouble = new TroubleLog();
                            trouble.TroubleCode = @"0000770";
                            trouble.TroubleType = TROUBLETYPE.ERR;
                            trouble.TroubleUnit = @"设备";
                            trouble.TroubleInfo = string.Format("样本{0}项目{1}反应进程{2}:添加试剂1失败. ", r.SMPNO, r.ItemName, r.TCNO);
                            TroubleLogSer.Save(trouble);
                        }
                    }
                    if (cmdname == "77" && Data[index + 2] == 0x31)//R2
                    {
                        RealTimeCUVDataService.RunningErrors(Pt26thWn, "R2");

                        Result r = new RealTimeCUVDataService().GetResultFromRealTimeWorkNum(Pt26thWn);
                        if (r != null)
                        {
                            TroubleLog trouble = new TroubleLog();
                            trouble.TroubleCode = @"0000771";
                            trouble.TroubleType = TROUBLETYPE.ERR;
                            trouble.TroubleUnit = @"设备";
                            trouble.TroubleInfo = string.Format("样本{0}项目{1}反应进程{2}:添加试剂2失败. ", r.SMPNO, r.ItemName, r.TCNO);
                            TroubleLogSer.Save(trouble);
                        }
                    }
                    if (cmdname == "57" && Data[index + 2] == 0x30)//SMP
                    {
                        RealTimeCUVDataService.RunningErrors(Pt3ndWn, "SMP");

                        Result r = new RealTimeCUVDataService().GetResultFromRealTimeWorkNum(Pt3ndWn);
                        if (r != null)
                        {
                            TroubleLog trouble = new TroubleLog();
                            trouble.TroubleCode = @"0000570";
                            trouble.TroubleType = TROUBLETYPE.ERR;
                            trouble.TroubleUnit = @"设备";
                            trouble.TroubleInfo = string.Format("样本{0}项目{1}反应进程{2}:添加样本失败. ", r.SMPNO, r.ItemName, r.TCNO);
                            TroubleLogSer.Save(trouble);
                        }
                    }


                    TroubleLog t = new TroubleLog();
                    t.TroubleCode = string.Format("{0}{1}{2}{3}{4}{5}{6}", (char)Data[index], (char)Data[index + 1], (char)Data[index + 2], (char)Data[index + 3], (char)Data[index + 4], (char)Data[index + 5], (char)Data[index + 6]);
                    t.TroubleType = TROUBLETYPE.ERR;
                    t.TroubleUnit = @"设备";
                    t.TroubleInfo = null;
                    TroubleLogSer.Save(t);

                    LogService.Log("测试运行设备发生错误:" + t.TroubleCode, LogType.Debug);
                }
            }
            return(null);
        }
Ejemplo n.º 30
0
        private void describe_Run()
        {
            Mock <IWebSocketEventSender> websocketMock = null;
            Mock <IContainer>            containerMock = null;
            Mock <IContainerProcess>     processMock   = null;
            RunService runService = null;

            before = () =>
            {
                websocketMock = new Mock <IWebSocketEventSender>();
                containerMock = new Mock <IContainer>();
                processMock   = new Mock <IContainerProcess>();

                runService           = new RunService();
                runService.container = containerMock.Object;

                containerMock.Setup(x => x.Directory).Returns(new Mock <IContainerDirectory>().Object);
            };

            context["#Run"] = () =>
            {
                before = () => {
                    processMock.Setup(x => x.Id).Returns(5432);
                    containerMock.Setup(x => x.Run(It.IsAny <ProcessSpec>(), It.IsAny <IProcessIO>())).Returns(processMock.Object);
                };

                act = () => runService.Run(websocketMock.Object, new ApiProcessSpec());

                it["sends the process pid on the websocket"] = () =>
                {
                    websocketMock.Verify(x => x.SendEvent("pid", "5432"));
                };

                it["calls startGuard on the container"] = () =>
                {
                    containerMock.Verify(x => x.StartGuard());
                };
            };

            context["Process exits normally"] = () =>
            {
                before = () => containerMock.Setup(x => x.Run(It.IsAny <ProcessSpec>(), It.IsAny <IProcessIO>())).Returns(processMock.Object);

                context["Process exits with 1"] = () =>
                {
                    before = () => processMock.Setup(x => x.WaitForExit()).Returns(1);

                    it["sends a close event with data == '1'"] = () =>
                    {
                        var apiProcessSpec = new ApiProcessSpec();
                        runService.Run(websocketMock.Object, apiProcessSpec);

                        websocketMock.Verify(x => x.SendEvent("close", "1"));
                        websocketMock.Verify(x => x.Close(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "process finished"));
                    };
                };

                context["Process exits with 0"] = () =>
                {
                    before = () => processMock.Setup(x => x.WaitForExit()).Returns(0);

                    it["sends a close event with data == '0'"] = () =>
                    {
                        var apiProcessSpec = new ApiProcessSpec();
                        runService.Run(websocketMock.Object, apiProcessSpec);

                        websocketMock.Verify(x => x.SendEvent("close", "0"));
                        websocketMock.Verify(x => x.Close(System.Net.WebSockets.WebSocketCloseStatus.NormalClosure, "process finished"));
                    };
                };
            };

            context["Process throws an exception while running"] = () =>
            {
                before = () =>
                {
                    containerMock.Setup(x => x.Run(It.IsAny <ProcessSpec>(), It.IsAny <IProcessIO>()))
                    .Returns(processMock.Object);
                    processMock.Setup(x => x.WaitForExit()).Throws(new Exception("Running is hard"));
                };

                it["sends a close event with data == '-1'"] = () =>
                {
                    var apiProcessSpec = new ApiProcessSpec();
                    runService.Run(websocketMock.Object, apiProcessSpec);

                    websocketMock.Verify(x => x.SendEvent("close", "-1"));
                    websocketMock.Verify(x => x.Close(System.Net.WebSockets.WebSocketCloseStatus.InternalServerError, "Running is hard"));
                };
            };

            context["container#run throws an exception"] = () =>
            {
                before = () => containerMock.Setup(x => x.Run(It.IsAny <ProcessSpec>(), It.IsAny <IProcessIO>())).Throws(new Exception("filename doesn't exist"));

                it["sends an error event"] = () =>
                {
                    var apiProcessSpec = new ApiProcessSpec();
                    runService.Run(websocketMock.Object, apiProcessSpec);

                    websocketMock.Verify(x => x.SendEvent("error", "filename doesn't exist"));
                    websocketMock.Verify(x => x.Close(System.Net.WebSockets.WebSocketCloseStatus.InternalServerError, "filename doesn't exist"));
                };
            };

            describe["environment variables"] = () =>
            {
                it["passes processSpec.Env environment variables to the process"] = () =>
                {
                    containerMock.Setup(x => x.GetInfo()).Returns(new ContainerInfo());
                    runService.Run(websocketMock.Object, new ApiProcessSpec
                    {
                        Env = new string[] { "foo=bar", "jane=jill=jim" },
                    });
                    containerMock.Verify(x => x.Run(It.Is((ProcessSpec p) => p.Environment["foo"] == "bar" && p.Environment["jane"] == "jill=jim"), It.IsAny <IProcessIO>()));
                };

                it["kv pairs from processSpec.Env override a pairs from executor:env"] = () =>
                {
                    containerMock.Setup(x => x.GetInfo()).Returns(new ContainerInfo
                    {
                        Properties = new System.Collections.Generic.Dictionary <string, string> {
                            { "executor:env", "[{\"name\":\"FOO\",\"value\":\"Bar\"}]" }
                        }
                    });
                    runService.Run(websocketMock.Object, new ApiProcessSpec
                    {
                        Env = new string[] { "FOO=Baz" },
                    });
                    containerMock.Verify(x => x.Run(It.Is((ProcessSpec p) => p.Environment["FOO"] == "Baz"), It.IsAny <IProcessIO>()));
                };

                it["sets ENV[USERPROFILE]"] = () =>
                {
                    containerMock.Setup(x => x.Directory.UserPath).Returns(@"E:\Fred");

                    runService.Run(websocketMock.Object, new ApiProcessSpec());
                    containerMock.Verify(x => x.Run(It.Is((ProcessSpec p) => p.Environment["USERPROFILE"] == @"E:\Fred"), It.IsAny <IProcessIO>()));
                };

                context["when no container port is in the request"] = () =>
                {
                    it["ENV[PORT] remains unset"] = () =>
                    {
                        containerMock.Setup(x => x.GetInfo()).Returns(new ContainerInfo
                        {
                            ReservedPorts = new System.Collections.Generic.List <int> {
                                1234
                            },
                        });

                        runService.Run(websocketMock.Object, new ApiProcessSpec());
                        containerMock.Verify(
                            x =>
                            x.Run(It.Is((ProcessSpec p) => !p.Environment.ContainsKey("PORT")), It.IsAny <IProcessIO>()));
                    };
                    context["when a 'port' argument is in the request"] = () =>
                    {
                        it["sets the ENV[PORT] to the hostport matching the requested container port"] = () =>
                        {
                            containerMock.Setup(x => x.GetInfo()).Returns(new ContainerInfo {
                            });
                            containerMock.Setup(x => x.GetProperty("ContainerPort:8080")).Returns("1234");

                            runService.Run(websocketMock.Object, new ApiProcessSpec
                            {
                                Args = new string[] { "-port=8080" },
                            });

                            containerMock.Verify(x => x.Run(It.Is((ProcessSpec p) => p.Environment["PORT"] == "1234"), It.IsAny <IProcessIO>()));
                        };
                    };
                };
            };
        }