public void TestOpenCommand()
        {
            var driveModel = new DriveModel
            {
                Name            = "Test",
                RootDirectory   = "/test",
                TotalSpaceBytes = 42,
                FreeSpaceBytes  = 21
            };
            var fileSizeFormatterMock  = new Mock <IFileSizeFormatter>();
            var pathServiceMock        = new Mock <IPathService>();
            var filePanelViewModelMock = new Mock <IFilesPanelViewModel>();

            filePanelViewModelMock
            .SetupSet(m => m.CurrentDirectory = driveModel.RootDirectory)
            .Verifiable();
            var fileOperationsMediatorMock = new Mock <IFilesOperationsMediator>();

            fileOperationsMediatorMock
            .SetupGet(m => m.ActiveFilesPanelViewModel)
            .Returns(filePanelViewModelMock.Object);

            var viewModel = new DriveViewModel(fileSizeFormatterMock.Object,
                                               pathServiceMock.Object, fileOperationsMediatorMock.Object, driveModel);

            Assert.True(viewModel.OpenCommand.CanExecute(null));
            viewModel.OpenCommand.Execute(null);

            filePanelViewModelMock
            .VerifySet(m => m.CurrentDirectory = driveModel.RootDirectory, Times.Once);
        }
Beispiel #2
0
        public DriveView()
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);

            _driveViewModel = new DriveViewModel(AppBootstrapper.NavigationService, AppBootstrapper.DriveServices);
            BindingContext  = _driveViewModel;
        }
Beispiel #3
0
 private void OpenDrive_MouseDown(object sender, MouseButtonEventArgs e)
 {
     if (e.ClickCount == 2)
     {
         DriveViewModel drive = (DriveViewModel)((FrameworkElement)sender).Tag;
         Process.Start(drive.Name);
     }
 }
Beispiel #4
0
 public static BllDrive ToBllDrive(this DriveViewModel drive)
 {
     return(new BllDrive
     {
         Name = drive.Name.Insert(1, ":"),
         DriveType = drive.DriveType,
         TotalSize = drive.TotalSize,
         TotalFreeSpace = drive.TotalFreeSpace
     });
 }
Beispiel #5
0
        protected override void OnDisappearing()
        {
            base.OnDisappearing();

            _runLoop = false;
            DriveViewModel vm = this.BindingContext as DriveViewModel;

            if (vm != null)
            {
                vm.Disconnect();
            }
        }
Beispiel #6
0
 /// <summary>
 /// handle a item double click (using Interaction.Triggers is not working because on list
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void Item_MouseDoubleClick(object sender, MouseButtonEventArgs e)
 {
     try
     {
         DriveViewModel model = DataContext as DriveViewModel;
         if (model == null)
         {
             return;
         }
     }
     catch (Exception err)
     {
         LogHelper.Manage("ExplorerView:Grouping", err);
     }
 }
Beispiel #7
0
        protected override void OnAppearing()
        {
            base.OnAppearing();

            DriveViewModel vm = this.BindingContext as DriveViewModel;

            if (vm != null)
            {
                vm.Connect();
            }

            _runLoop = true;
            double fpsWanted = 30;             //30 frames per seconde
            var    ms        = 1000.0 / fpsWanted;
            var    ts        = TimeSpan.FromMilliseconds(ms);

            // Create a timer that triggers roughly every 1/30 seconds
            Device.StartTimer(ts, TimerLoop);
        }
        public void TestProperties()
        {
            const string name       = "tst";
            var          driveModel = new DriveModel
            {
                Name            = "Test",
                RootDirectory   = "/test",
                TotalSpaceBytes = 42,
                FreeSpaceBytes  = 21
            };
            var fileSizeFormatterMock = new Mock <IFileSizeFormatter>();

            fileSizeFormatterMock
            .Setup(m => m.GetSizeAsNumber(It.IsAny <long>()))
            .Returns <long>((bytes) => bytes.ToString());
            fileSizeFormatterMock
            .Setup(m => m.GetFormattedSize(It.IsAny <long>()))
            .Returns <long>((bytes) => bytes + " B");
            var pathServiceMock = new Mock <IPathService>();

            pathServiceMock
            .Setup(m => m.GetFileName(driveModel.Name))
            .Returns(name);
            var filePanelViewModelMock     = new Mock <IFilesPanelViewModel>();
            var fileOperationsMediatorMock = new Mock <IFilesOperationsMediator>();

            fileOperationsMediatorMock
            .SetupGet(m => m.ActiveFilesPanelViewModel)
            .Returns(filePanelViewModelMock.Object);

            var viewModel = new DriveViewModel(fileSizeFormatterMock.Object,
                                               pathServiceMock.Object, fileOperationsMediatorMock.Object, driveModel);

            Assert.Equal(name, viewModel.DriveName);
            Assert.Equal("21", viewModel.AvailableSizeAsNumber);
            Assert.Equal("21 B", viewModel.AvailableFormattedSize);
            Assert.Equal("42", viewModel.TotalSizeAsNumber);
            Assert.Equal("42 B", viewModel.TotalFormattedSize);
        }
Beispiel #9
0
        //Create the event handler
        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            SKImageInfo info    = args.Info;
            SKSurface   surface = args.Surface;

            DriveViewModel vm = this.BindingContext as DriveViewModel;

            if (vm == null)
            {
                return;
            }


            using (var webClient = new WebClient()) {
                var canvas = surface.Canvas;

                var stream = webClient.DownloadData($"http://{Models.AppConfig.Instance.IpAddress}:8080/image/front/img.jpg?timestamp={DateTime.Now.Ticks}");
                var img    = SKBitmap.Decode(stream);


                SKRect bounds = canvas.LocalClipBounds;
                float  xRatio = (float)info.Width / (float)img.Width;
                float  yRatio = (float)info.Height / (float)img.Height;
                canvas.Scale(xRatio, yRatio);

                canvas.DrawBitmap(img, 0, 0);                //, canvas.LocalClipBounds);

                if (vm.ShowGrass)
                {
                    try {
                        var streamGrass = webClient.DownloadData($"http://{Models.AppConfig.Instance.IpAddress}:8080/image/front/grass.svg?timestamp={DateTime.Now.Ticks}&layerItems=detection&layerItems=surface&layerItems=robotMotionState&layerItems=inferenceType");
                        //SKSvg svgGrass = new SkiaSharp.SKSvg();
                        SkiaSharp.Extended.Svg.SKSvg svg = new SkiaSharp.Extended.Svg.SKSvg();
                        svg.Load(new MemoryStream(streamGrass));

                        canvas.DrawPicture(svg.Picture);
                    } catch (Exception err) {
                    }
                }
                if (vm.ShowScene)
                {
                    try {
                        var streamScene = webClient.DownloadData($"http://{Models.AppConfig.Instance.IpAddress}:8080/image/front/scene.svg?timestamp={DateTime.Now.Ticks}&layerItems=GeneralObjectDetectionTransformer&layerItems=ToadiObjectDetectionTransformer&layerItems=ChargingStationPoseTransformer");

                        SkiaSharp.Extended.Svg.SKSvg svgScene = new SkiaSharp.Extended.Svg.SKSvg();
                        svgScene.Load(new MemoryStream(streamScene));


                        canvas.DrawPicture(svgScene.Picture);
                    } catch (Exception err) {
                    }
                }



                img.Dispose();
                canvas.Dispose();

                //using (var canvas = surface.Canvas) {
                //	// use KBitmap.Decode to decode the byte[] in jpeg format
                //	using (var bitmap = SKBitmap.Decode(stream)) {

                //		using (var paint = new SKPaint()) {
                //			// clear the canvas / fill with black
                //			//canvas.DrawColor(SKColors.Black);
                //			canvas.DrawBitmap(bitmap, canvas.LocalClipBounds);
                //			//canvas.DrawBitmap(bitmap, 0, 0, paint); // SKRect.Create(640, 480)
                //			//canvas.DrawBitmap(bitmap, SKRect.Create(640, 480), SKRect.Create((float)canvasView.Width, (float)canvasView.Height));
                //		}

                //	}
                //}
            }
        }
Beispiel #10
0
    public async Task RefreshAsync()
    {
        using (await RefreshAsyncLock.LockAsync())
        {
            Drives.Clear();

            DriveInfo[] drives;

            try
            {
                drives = DriveInfo.GetDrives();
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Getting drives");

                await Services.MessageUI.DisplayMessageAsync(Resources.DriveSelection_RefreshError, MessageType.Error);

                return;
            }

            foreach (var drive in drives)
            {
                if (BrowseVM.AllowedTypes != null && !BrowseVM.AllowedTypes.Contains(drive.DriveType))
                {
                    continue;
                }

                ImageSource icon  = null;
                string      label = null;
                string      path;
                string      format    = null;
                ByteSize?   freeSpace = null;
                ByteSize?   totalSize = null;
                DriveType?  type      = null;
                bool?       ready     = null;

                try
                {
                    label = drive.VolumeLabel;
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "Getting drive label");
                }

                try
                {
                    path = drive.Name;

                    try
                    {
                        using var shellObj = ShellObject.FromParsingName(path);
                        var thumb = shellObj.Thumbnail;
                        thumb.CurrentSize = new System.Windows.Size(16, 16);
                        icon = thumb.GetTransparentBitmap()?.ToImageSource();
                    }
                    catch (Exception ex)
                    {
                        Logger.Debug(ex, "Getting drive icon");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "Getting drive name");
                    continue;
                }

                try
                {
                    format = drive.DriveFormat;
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "Getting drive format");
                }

                try
                {
                    freeSpace = ByteSize.FromBytes(drive.TotalFreeSpace);
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "Getting drive freeSpace");
                }

                try
                {
                    totalSize = ByteSize.FromBytes(drive.TotalSize);
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "Getting drive totalSize");
                }

                try
                {
                    type = drive.DriveType;
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "Getting drive type");
                }

                try
                {
                    ready = drive.IsReady;
                    if (!drive.IsReady && !BrowseVM.AllowNonReadyDrives)
                    {
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "Getting drive ready");
                    if (!BrowseVM.AllowNonReadyDrives)
                    {
                        continue;
                    }
                }

                // Create the view model
                var vm = new DriveViewModel()
                {
                    Path      = path,
                    Icon      = icon,
                    Format    = format,
                    Label     = label,
                    Type      = type,
                    FreeSpace = freeSpace,
                    TotalSize = totalSize,
                    IsReady   = ready
                };

                Drives.Add(vm);
            }
        }
    }
        public IActionResult Report([FromBody] DriveViewModel driveViewModel)
        {
            try
            {
                var appLogin = loginRepo.AsQueryable().Where(l => l.GuId == driveViewModel.Authorization.GuId).SingleOrDefault();
                if (appLogin == null)
                {
                    var message = $"Ugyldigt login token";
                    logger.LogWarning(message);
                    return(ErrorResult(message, ErrorCodes.InvalidAuthorization, HttpStatusCode.Unauthorized));
                }

                if (appLogin.Person.Id != driveViewModel.DriveReport.ProfileId)
                {
                    var message = $"Forsøg på at indberette kørsel på forkert person";
                    logger.LogWarning(message);
                    return(ErrorResult(message, ErrorCodes.ReportAndUserDoNotMatch, HttpStatusCode.Unauthorized));
                }

                var duplicateReportCheck = driveReportRepo.AsQueryable().Where(t => t.AppUuid == driveViewModel.DriveReport.Uuid).Any();
                if (duplicateReportCheck)
                {
                    var message = "Indberetning afvist da den allerede er indberettet";
                    logger.LogWarning(message);
                    return(ErrorResult(message, ErrorCodes.DuplicateReportFound, HttpStatusCode.OK));
                }
                var appReport = driveViewModel.DriveReport;

                var points    = new List <DriveReportPoint>();
                var viaPoints = new List <DriveReportPoint>();
                for (var i = 0; i < appReport.route.GPSCoordinates.Count; i++)
                {
                    var coordinate = appReport.route.GPSCoordinates.ToArray()[i];
                    points.Add(new DriveReportPoint
                    {
                        Latitude  = coordinate.Latitude,
                        Longitude = coordinate.Longitude,
                    });

                    if (coordinate.IsViaPoint || i == 0 || i == appReport.route.GPSCoordinates.Count - 1)
                    {
                        var address = addressCoordinates.GetAddressFromCoordinates(new Address
                        {
                            Latitude  = coordinate.Latitude,
                            Longitude = coordinate.Longitude
                        });

                        viaPoints.Add(new DriveReportPoint()
                        {
                            Latitude     = coordinate.Latitude,
                            Longitude    = coordinate.Longitude,
                            StreetName   = address.StreetName,
                            StreetNumber = address.StreetNumber,
                            ZipCode      = address.ZipCode,
                            Town         = address.Town,
                        });
                    }
                }

                var rate         = rateRepo.AsQueryable().Where(r => r.Id == appReport.RateId).First();
                var licensePlate = appLogin.Person.LicensePlates.Where(p => p.IsPrimary).FirstOrDefault();

                DriveReport newReport = new DriveReport();
                newReport.AppUuid              = appReport.Uuid;
                newReport.FourKmRule           = appReport.FourKmRule;
                newReport.IsFromApp            = true;
                newReport.HomeToBorderDistance = appReport.HomeToBorderDistance;
                newReport.StartsAtHome         = appReport.StartsAtHome;
                newReport.EndsAtHome           = appReport.EndsAtHome;
                newReport.Purpose              = appReport.Purpose;
                newReport.PersonId             = appReport.ProfileId;
                newReport.EmploymentId         = appReport.EmploymentId;
                newReport.KmRate               = rate.KmRate;
                newReport.UserComment          = appReport.ManualEntryRemark;
                newReport.Status               = ReportStatus.Pending;
                newReport.LicensePlate         = licensePlate != null ? licensePlate.Plate : "UKENDT";
                newReport.Comment              = "";
                newReport.DriveReportPoints    = viaPoints;
                newReport.Distance             = appReport.route.TotalDistance;
                newReport.KilometerAllowance   = appReport.route.GPSCoordinates.Count > 0 ? KilometerAllowance.Calculated : KilometerAllowance.Read;
                newReport.DriveDateTimestamp   = (Int32)(Convert.ToDateTime(appReport.Date).Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
                newReport.CreatedDateTimestamp = (Int32)(Convert.ToDateTime(appReport.Date).Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
                newReport.TFCode               = rate.Type.TFCode;
                newReport.TFCodeOptional       = rate.Type.TFCodeOptional;
                newReport.FullName             = appLogin.Person.FullName;
                newReport.RouteGeometry        = GeoService.Encode(points);
                driveService.Create(newReport);

                return(Ok());
            }
            catch (Exception ex)
            {
                var message = "Kunne ikke gemme indberetning fra app";
                logger.LogError(ex, $"{message}, uuid: {driveViewModel.DriveReport.Uuid}");
                return(ErrorResult(message, ErrorCodes.SaveError, HttpStatusCode.BadRequest));
            }
        }
Beispiel #12
0
 public DrivePage(DriveInfo d)
 {
     InitializeComponent();
     DataContext = new DriveViewModel(d);
 }