public async Task Test1()
        {
            DateTime        dateTime1    = new DateTime(2019, 07, 10, 14, 00, 00);
            DateTime        dateTime2    = new DateTime(2019, 07, 09, 14, 00, 00);
            DateTime        dateTimeTo   = new DateTime(2019, 07, 10, 18, 00, 00);
            DateTime        dateTimeFrom = new DateTime(2019, 07, 09, 10, 00, 00);
            TargetViewModel targetView   = new TargetViewModel("ControllerCount");

            TargetViewModel[] targetViewArray = new TargetViewModel[1] {
                targetView
            };
            DataPoint <int> expectDataPoint1 = new DataPoint <int>(dateTime1, 1000);
            DataPoint <int> expectDataPoint2 = new DataPoint <int>(dateTime2, 1100);

            DataPoint <int>[] expectedDataPoints = new DataPoint <int>[2] {
                expectDataPoint1, expectDataPoint2
            };
            DataSeries <int>         expectedDataSeries     = new DataSeries <int>(targetView.ToString(), expectedDataPoints);
            List <DataSeries <int> > expectedDataSeriesList = new List <DataSeries <int> >();

            expectedDataSeriesList.Add(expectedDataSeries);

            var mockDataAccess = new Mock <ITimeSeriesData>();

            mockDataAccess.Setup(data => data.GetDataTimeSeriesData(It.IsAny <DateTime>(), It.IsAny <DateTime>(), "DataTimeSeries"))
            .ReturnsAsync(new List <DeviceCounts>
            {
                new DeviceCounts(dateTime1, "10000", "1000", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100"), new DeviceCounts(dateTime2, "11000", "1100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100", "100")
            });
            var target = new RequestHandler(mockDataAccess.Object);

            var result = await target.GetOutputTimeSeries(dateTimeTo, dateTimeFrom, targetViewArray, "DataTimeSeries");

            CollectionAssert.AreEqual(expectedDataSeriesList[0].Datapoints, result[0].Datapoints);
        }
예제 #2
0
        public void CreateTarget_BusinessLogicException()
        {
            //Arrange
            var testTargetVm = new TargetViewModel()
            {
                TargetId = 5, Name = "zaz", OrganizationId = 2
            };
            var testTarget = new Target()
            {
                Id = 5, TargetName = "техніка", OrganizationId = 2
            };

            var reposirory = new Mock <ITargetRepository>();

            reposirory.Setup(x => x.Create(testTarget));

            var unitOfWork = new Mock <IUnitOfWork>();

            unitOfWork.Setup(x => x.TargetRepository)
            .Returns(reposirory.Object);

            var finOpService = new Mock <IFinOpService>();

            var service = new TargetService(unitOfWork.Object, finOpService.Object);

            //Act
            var exception = Record.Exception(() => service.CreateTarget(testTargetVm));

            //Assert
            Assert.NotNull(exception);
            Assert.IsType <BusinessLogicException>(exception);
            Assert.True(ErrorMessages.CantCreatedItem == exception.Message);
        }
예제 #3
0
        // ReSharper disable once MethodTooLong
        // ReSharper disable once TooManyArguments
        private static List <TargetViewModel> BuildReport(List <Position> positions, DateTime startPeriod, string vehicleName, List <Periods> periods)
        {
            List <TargetViewModel> targets = new List <TargetViewModel>();

            foreach (var position in periods.Distinct())
            {
                var trgt = new TargetViewModel();
                // get the first period
                var firstPosition = GetFirstPosition(positions, position);
                //get  last period
                var lastPosition = GetLastPosition(positions, position);
                // set the begnings of the period
                SetBegningsTrip(firstPosition, trgt);
                // set the ends of the period
                SetEndsTrip(lastPosition, trgt);
                // calculate distance , speeds , and duration
                GetDistanceAndDuration(positions, lastPosition, firstPosition, trgt);
                var index = GetPreviousPositionIndexx(positions, lastPosition);
                if (index == -1)
                {
                    index = 0;
                }
                trgt.Speed       = positions.ElementAt(index).Speed;
                trgt.VehicleName = vehicleName;
                trgt.CurrentDate = startPeriod.Date.ToShortDateString();
                targets.Add(trgt);
            }

            return(targets);
        }
예제 #4
0
        public void CreateTarget_ArgumentException()
        {
            //Arrange
            var testTargetVm = new TargetViewModel()
            {
                Name = "", OrganizationId = 2
            };

            var reposirory = new Mock <ITargetRepository>();
            var unitOfWork = new Mock <IUnitOfWork>();

            unitOfWork.Setup(x => x.TargetRepository)
            .Returns(reposirory.Object);

            var finOpService = new Mock <IFinOpService>();

            var service = new TargetService(unitOfWork.Object, finOpService.Object);

            //Act
            var exception = Record.Exception(() => service.CreateTarget(testTargetVm));

            //Assert
            Assert.NotNull(exception);
            Assert.IsType <ArgumentException>(exception);
            Assert.True(ErrorMessages.RequiredFieldMessage == exception.Message);
        }
예제 #5
0
        // ReSharper disable once MethodTooLong
        // ReSharper disable once TooManyArguments
        private static void GetDistanceAndDuration(List <Position> positions, Position lastPosition, Position firstPosition,
                                                   TargetViewModel trgt)
        {
            // ReSharper disable once ComplexConditionExpression
            if (lastPosition != null && firstPosition != null)
            {
                var index = GetPreviousPositionIndexx(positions, lastPosition);
                if (index == -1)
                {
                    index = 0;
                }
                var p1 = new GeofenceHelper.Position();
                p1.Latitude  = positions.ElementAt(index).Lat;
                p1.Longitude = positions.ElementAt(index).Long;
                var p2 = new GeofenceHelper.Position();
                p2.Latitude  = firstPosition.Lat;
                p2.Longitude = firstPosition.Long;

                trgt.Distance = Math.Round(GeofenceHelper.HaversineFormula(p1, p2, GeofenceHelper.DistanceType.Kilometers), 2);
                var avgSpeed = GetAvgSpeed(positions, firstPosition, lastPosition);
                trgt.AvgSpeed = Math.Round(avgSpeed, 2);
                trgt.MaxSpeed = Math.Round(GetMaxSpeed(positions, firstPosition, lastPosition), 2);
            }

            if (double.IsNaN(trgt.Distance))
            {
                trgt.Distance = 0;
            }
            trgt.Duration = (DateTime.Parse(trgt.EndPeriod) - DateTime.Parse(trgt.StartPeriod)).TotalSeconds;
        }
예제 #6
0
 private static void SetEndsTrip(Position lastPosition, TargetViewModel trgt)
 {
     if (lastPosition != null)
     {
         trgt.EndPeriod     = lastPosition.Timestamp.ToString("O");
         trgt.EndPeriod1    = lastPosition.Timestamp.ToString("g");
         trgt.ArrivalAddres = lastPosition.Address;
     }
 }
예제 #7
0
 private Target ConvertViewModelToTarget(TargetViewModel targetVm)
 {
     return(new Target()
     {
         Id = targetVm.TargetId,
         TargetName = targetVm.Name,
         OrganizationId = targetVm.OrganizationId,
         ParentTargetId = targetVm.ParentTargetId
     });
 }
예제 #8
0
        public void AddTarget(double azimuth, double range, double width, double opacityMultiplier = 1)
        {
            var newTarget = new TargetViewModel(azimuth, range, width, opacityMultiplier)
            {
                Thickness = ScanLine.TargetsThickness,
                Length    = ScanLine.TargetsLength,
                Opacity   = OpacityMultiplier
            };

            AddComponent(newTarget);
        }
예제 #9
0
        private static void SetBegningsTrip(Position firstPosition, TargetViewModel trgt)
        {
            if (firstPosition != null)
            {
                trgt.MotionStatus = firstPosition.MotionStatus.ToString();

                trgt.StartPeriod  = firstPosition.Timestamp.ToString("O");
                trgt.StartPeriod1 = firstPosition.Timestamp.ToString("g");

                trgt.Latitude     = firstPosition.Lat;
                trgt.Logitude     = firstPosition.Long;
                trgt.StartAddres  = firstPosition.Address;
                trgt.MotionStatus = firstPosition.MotionStatus.ToString();
            }
        }
        public void ShowCanvas()
        {
            var viewModel = new TargetViewModel();

            viewModel.SelectedDart.Y = DartBoard.Instance.GetTripleField(60).Target.Y;
            viewModel.SelectedDart.X = DartBoard.Instance.GetTripleField(60).Target.X;
            foreach (var point in points)
            {
                viewModel.NextCommand.Execute(null);
                viewModel.SelectedDart.Y = point.Y < 0 ? 0 : point.Y > 339 ? 339 : point.Y;
                viewModel.SelectedDart.X = point.X < 0 ? 0 : point.X > 339 ? 339 : point.X;
            }
            viewModel.NextCommand.Execute(null);
            var window = new TargetWindow {
                DataContext = viewModel
            };

            window.Show();
        }
예제 #11
0
        private void FillGridView()
        {
            var qtr          = Quater;
            var partnerId    = PartnerId;
            var targetVMList = new List <TargetViewModel>();
            var products     = _db.Products.OrderBy(p => p.SortOrder);

            foreach (var product in products)
            {
                var target = _db.Targets.FirstOrDefault(t => t.PartnerId == partnerId && t.QuarterYear == qtr && t.ProductId == product.ProductId);

                if (target == null)
                {
                    target = new Data.Models.Target();
                }

                var targetVM = new TargetViewModel
                {
                    TargetId           = target.TargetId,
                    M1                 = target.M1,
                    M2                 = target.M2,
                    M3                 = target.M3,
                    PartnerId          = target.PartnerId,
                    ProductCategory    = product.ProductCategory,
                    ProductDescription = product.ProductDescription,
                    ProductId          = product.ProductId,
                    QuarterYear        = target.QuarterYear
                };

                var prevQtr       = Utility.QuarterHelper.GetPrevQuarter(Quater);
                var prevQtrTarget = _db.Targets.Where(t => t.PartnerId == PartnerId && t.ProductId == product.ProductId && t.QuarterYear == prevQtr.QuarterYear).ToList();
                if (prevQtrTarget.Any())
                {
                    targetVM.PrevQtr = prevQtrTarget.Sum(t => t.M1 + t.M2 + t.M3);
                }

                targetVMList.Add(targetVM);
            }
            GridView1.DataSource = targetVMList;
            GridView1.DataBind();
            GridView1.UseAccessibleHeader    = true;
            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
예제 #12
0
        public void CreateTarget()
        {
            //Arrange
            var testTargetVm = new TargetViewModel()
            {
                Name = "техніка", OrganizationId = 2
            };
            var testTargetA = new Target()
            {
                TargetName = "техніка", OrganizationId = 2
            };
            var testTargetB = new Target()
            {
                Id = 5, TargetName = "техніка", OrganizationId = 2
            };

            var reposirory = new Mock <ITargetRepository>();

            reposirory.Setup(x => x.Create(It.IsAny <Target>()))
            .Returns(testTargetB);

            var unitOfWork = new Mock <IUnitOfWork>();

            unitOfWork.Setup(x => x.TargetRepository)
            .Returns(reposirory.Object);

            var finOpService = new Mock <IFinOpService>();

            var service = new TargetService(unitOfWork.Object, finOpService.Object);

            //Act
            var result = service.CreateTarget(testTargetVm);

            //Assert
            Assert.NotNull(result);
            Assert.IsType <TargetViewModel>(result);

            Assert.True(0 != result.TargetId);
            Assert.True(testTargetVm.Name == result.Name);
            Assert.True(testTargetVm.OrganizationId == result.OrganizationId);

            unitOfWork.Verify(x => x.TargetRepository);
        }
예제 #13
0
        // ReSharper disable once MethodTooLong
        // ReSharper disable once TooManyArguments
        public List <TargetViewModel> BuildReport(List <Position> positions, DateTime startPeriod, string vehicleName, List <Periods> periods)
        {
            List <TargetViewModel> targets = new List <TargetViewModel>();
            var i   = 50;
            var max = periods.Count;

            foreach (var position in periods.Distinct())
            {
                if (i < 100)
                {
                    i += 100 / max;
                }
                else
                {
                    i = 99;
                }
                UpdateProgress?.Invoke(i);
                var trgt = new TargetViewModel();
                // get the first period
                var firstPosition = GetFirstPosition(positions, position);
                //get  last period
                var lastPosition = GetLastPosition(positions, position);
                // set the begnings of the period
                SetBeginningsTrip(firstPosition, trgt);
                // set the ends of the period
                SetEndsTrip(lastPosition, trgt);
                // calculate distance , speeds , and duration
                GetDistanceAndDuration(positions, trgt, position.Start, position.End);
                var index = GetPreviousPositionIndex(positions, lastPosition);
                if (index == -1)
                {
                    index = 0;
                }
                trgt.Speed       = positions.ElementAt(index).Speed;
                trgt.VehicleName = vehicleName;
                trgt.CurrentDate = startPeriod.Date.ToShortDateString();
                targets.Add(trgt);
            }

            return(targets);
        }
예제 #14
0
        public TargetViewModel EditTarget(TargetViewModel item)
        {
            if (item.Name.Length == 0)
            {
                throw new System.ArgumentException(ErrorMessages.RequiredFieldMessage);
            }

            try
            {
                var targetToUpdate = ConvertViewModelToTarget(item);

                var result = _unitOfWork.TargetRepository.Update(targetToUpdate);
                _unitOfWork.SaveChanges();

                return(ConvertTargetToViewModel(result));
            }
            catch (System.Exception ex)
            {
                throw new BusinessLogicException(ErrorMessages.UpdateDataError, ex);
            }
        }
예제 #15
0
        public TargetViewModel CreateTarget(TargetViewModel addTarget)
        {
            if (addTarget.Name.Length == 0)
            {
                throw new System.ArgumentException(ErrorMessages.RequiredFieldMessage);
            }

            try
            {
                var addTarg = ConvertViewModelToTarget(addTarget);

                var result = _unitOfWork.TargetRepository.Create(addTarg);
                _unitOfWork.SaveChanges();

                return(ConvertTargetToViewModel(result));
            }
            catch (System.Exception ex)
            {
                throw new BusinessLogicException(ErrorMessages.CantCreatedItem, ex);
            }
        }
예제 #16
0
        public MainViewModel(
            Dispatcher dispatcher,
            IEventAggregator eventAggregator,
            ISeriesSelectorController seriesSelectorController,
            IUiModeChanges uiModeModel,
            ITargetLocation targetModel,
            ITransformation transformationInterface,
            IStripsViewerLayoutController viewerLayoutController,
            ICalibration calibrationInterface,
            IMovementDetection movementDetectionModel,
            ILocateXD locateXDModel,
            IStripsManager stripsManager,
            IACPC acpcInterface,
            IRigidNPR rigidNPRInterface)
        {
            _dispatcher               = dispatcher;
            _eventAggregator          = eventAggregator;
            _seriesSelectorController = seriesSelectorController;

            _uiModeModel                        = uiModeModel;
            _uiModeModel.ModeChanged           += (s, a) => UiModeChanged?.Invoke(s, a);
            _uiModeModel.LayerVisiblityChanged += (s, a) => LayerVisibilityChanged?.Invoke(s, a);

            _viewerLayoutController = viewerLayoutController;
            _stripsManager          = stripsManager;
            _rigidNPR = rigidNPRInterface;

            ACPC = new TargetViewModel(targetModel, transformationInterface, calibrationInterface, acpcInterface);

            MD      = new MDViewModel(movementDetectionModel);
            XDCalib = new XDCalibViewModel(locateXDModel);

            SwitchLayoutCommand      = new DelegateCommand <StripsViewerLayout>(SwitchLayout);
            AppWorkingOcurredCommand = new DelegateCommand(() => _eventAggregator.GetEvent <AppWorkingEvent>().Publish());

            StripsViewerLayouts = new ObservableCollection <StripsViewerLayout>(_viewerLayoutController.Layouts);

            _seriesSelectorController.SeriesSelected += OnSeriesSelected;
            _stripsManager.Changed += OnStripsManagerChanged;
        }
예제 #17
0
        /// <summary>
        /// Gets the Target record by TargetId and UserId.
        /// </summary>
        public async Task <TargetViewModel> GetTargetAsync(string id, ClaimsPrincipal user)
        {
            var userId = _userService.GetUserId(user);
            var result = await _targetRepository.GetAsync(x => x.Id == id && x.UserId == userId);

            var target = result.FirstOrDefault();

            if (target == null)
            {
                return(null);
            }

            var targetViewModel = new TargetViewModel
            {
                Id = target.Id,
                MonitoringInterval = target.MonitoringInterval,
                Name   = target.Name,
                Url    = target.Url,
                UserId = target.UserId
            };

            return(targetViewModel);
        }
예제 #18
0
        // ReSharper disable once MethodTooLong
        // ReSharper disable once TooManyArguments
        private static void GetDistanceAndDuration(List <Position> positions, TargetViewModel trgt, DateTime currenPosition, DateTime positionEnd)
        {
            // ReSharper disable once ComplexConditionExpression
            var points   = positions.Where(x => x.Timestamp >= currenPosition && x.Timestamp <= positionEnd).ToList();
            var avgSpeed = points.Average(x => x.Speed);

            trgt.AvgSpeed = Math.Round(avgSpeed, 2);
            trgt.MaxSpeed = Math.Round(points.Max(x => x.Speed), 2);

            trgt.Distance = 0;
            // ReSharper disable once ComplexConditionExpression
            if (points.Any() && trgt.MotionStatus != "Stopped")
            {
                var firstPos = points.First();
                foreach (var p in points.OrderBy(x => x.Timestamp).Skip(1))
                {
                    var dis = Math.Round(GeofenceHelper.HaversineFormula(new GeofenceHelper.Position {
                        Latitude = firstPos.Lat, Longitude = firstPos.Long
                    }, new GeofenceHelper.Position {
                        Latitude = p.Lat, Longitude = p.Long
                    }, GeofenceHelper.DistanceType.Kilometers), 2);
                    if (!double.IsNaN(dis))
                    {
                        trgt.Distance += dis;
                    }
                    firstPos = p;
                }
            }

            if (double.IsNaN(trgt.Distance))
            {
                trgt.Distance = 0;
            }
            trgt.Distance = Math.Round(trgt.Distance, 2);
            trgt.Duration = (DateTime.Parse(trgt.EndPeriod) - DateTime.Parse(trgt.StartPeriod)).TotalSeconds;
        }
예제 #19
0
 public TargetViewModel AddTarget([FromBody] TargetViewModel target)
 {
     return(_targetService.CreateTarget(target));
 }
예제 #20
0
 public TargetViewModel EditTarget([FromBody] TargetViewModel target)
 {
     return(_targetService.EditTarget(target));
 }
예제 #21
0
        public List <(Double, Double)> EvaluateSalesman(string salesman, string period, DateTime start, DateTime end)
        {
            try
            {
                if (period == "monthly")
                {
                    List <Double> Evaluation = new List <double>();
                    //Evaluate Visits
                    TargetViewModel         n             = new TargetViewModel();
                    List <(Double, Double)> result        = new List <(Double, Double)>();
                    VisitServices           visitServices = new VisitServices(_db);
                    var userId = _db.Aspnetusers.Where(x => x.FullName == salesman).Select(x => x.Id).SingleOrDefault();
                    for (var month = start.Month; month <= end.Month; month++)
                    {
                        var resultVisits = visitServices.GetVistisBySalesmanByMonth(salesman, month, null);
                        var target       = GetVisitTartgetByMonth(salesman, month, null);
                        if (target != 0)
                        {
                            n.Visits = (resultVisits * 100) / target;
                        }

                        else
                        {
                            Console.WriteLine("No Visit Target detected");
                            return(null);
                        }
                        //Evaluate Sales
                        List <double> resultSales = new List <double>();
                        var           Sales       = GetSalesbySalesmanByMonth(salesman, month, null);
                        var           Salestarget = GetSalesTargetByMonth(salesman, month, null);
                        if (Salestarget != 0)
                        {
                            n.Sales = (Sales * 100) / Salestarget;
                        }
                        else
                        {
                            Console.WriteLine("No Sales Target detected");
                            return(null);
                        }
                        var vis = Convert.ToDouble(n.Visits);
                        var sal = Convert.ToDouble(n.Sales);
                        result.Add((vis, sal));
                    }

                    return(result);
                }
                else if (period == "annual")
                {
                    List <Double> Evaluation = new List <double>();
                    //Evaluate Visits
                    TargetViewModel         n      = new TargetViewModel();
                    List <(Double, Double)> result = new List <(Double, Double)>();

                    VisitServices visitServices = new VisitServices(_db);
                    var           userId        = _db.Aspnetusers.Where(x => x.FullName == salesman).Select(x => x.Id).SingleOrDefault();
                    for (var year = start.Year; year <= end.Year; year++)
                    {
                        var resultVisits = visitServices.GetVistisBySalesmanByMonth(salesman, null, year);
                        var target       = GetVisitTartgetByMonth(salesman, null, year);

                        if (target != 0)
                        {
                            n.Visits = (resultVisits * 100) / target;
                        }

                        else
                        {
                            Console.WriteLine("No Visit Target detected");
                            return(null);
                        }
                        //Evaluate Sales
                        List <double> resultSales = new List <double>();
                        var           Sales       = GetSalesbySalesmanByMonth(salesman, null, year);
                        var           Salestarget = GetSalesTargetByMonth(salesman, null, year);
                        if (Salestarget != 0)
                        {
                            n.Sales = (Sales * 100) / Salestarget;
                        }
                        else
                        {
                            Console.WriteLine("No Sales Target detected");
                            return(null);
                        }
                        var vis = Convert.ToDouble(n.Visits);
                        var sal = Convert.ToDouble(n.Sales);
                        result.Add((vis, sal));
                    }

                    return(result);
                }
                return(null);
            }
            catch (Exception)
            {
                return(null);
            }
        }
예제 #22
0
 public IActionResult AddTarget([FromBody] TargetViewModel target)
 {
     return(Ok(_targetService.CreateTarget(target)));
 }