Пример #1
0
        public string GetCurrentPackageTempFile()
        {
            var tempFile = Path.GetTempFileName();

            try
            {
                // handle signed packages since they cannot be resaved without losing the signature
                if (IsSigned && _package is ISignaturePackage zip)
                {
                    File.Copy(zip.Source, tempFile, overwrite: true);
                }
                else
                {
                    PackageHelper.SavePackage(PackageMetadata, GetFiles(), tempFile, useTempFile: false);
                }
            }
            catch (Exception e)
            {
                UIServices.Show(e.Message, MessageLevel.Error);
            }

            if (File.Exists(tempFile))
            {
                return(tempFile);
            }

            return(null);
        }
        public DeploymentViewModel(IDeviceProvider deviceProvider,
                                   IWindowsOptionsProvider optionsProvider,
                                   IWoaDeployer deployer, UIServices uiServices, AdvancedViewModel advancedViewModel,
                                   WimPickViewModel wimPickViewModel, ILowLevelApi lowLevelApi)
        {
            this.optionsProvider   = optionsProvider;
            this.deployer          = deployer;
            this.uiServices        = uiServices;
            this.advancedViewModel = advancedViewModel;
            this.wimPickViewModel  = wimPickViewModel;

            var isSelectedWim = wimPickViewModel.WhenAnyObservable(x => x.WimMetadata.SelectedImageObs)
                                .Select(metadata => metadata != null);

            FullInstallWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                 ReactiveCommand.CreateFromTask(Deploy, isSelectedWim), uiServices.Dialog);
            IsBusyObservable = FullInstallWrapper.Command.IsExecuting;
            isBusy           = IsBusyObservable.ToProperty(this, model => model.IsBusy);

            RefreshDisksCommandWrapper = new CommandWrapper <Unit, ICollection <Disk> >(this,
                                                                                        ReactiveCommand.CreateFromTask(lowLevelApi.GetDisks), uiServices.Dialog);
            disks = RefreshDisksCommandWrapper.Command
                    .Select(x => x.Select(disk => new DiskViewModel(disk)))
                    .ToProperty(this, x => x.Disks);

            this.WhenAnyValue(x => x.SelectedDisk).Where(x => x != null).Subscribe(x => deviceProvider.Device = new RaspberryPi(lowLevelApi, x.Disk));
        }
Пример #3
0
        public AdvancedViewModel(ISettingsService settingsService, IFileSystemOperations fileSystemOperations,
                                 UIServices uiServices, IProviderBasedWindowsDeployer deployer,
                                 IDiskLayoutPreparer preparer,
                                 IWindowsOptionsProvider optionsProvider, IDeviceProvider deviceProvider, IDownloadProgress progress, StatusViewModel statusViewModel, IPhone phone)
        {
            StatusViewModel      = statusViewModel;
            this.settingsService = settingsService;
            this.uiServices      = uiServices;
            this.deployer        = deployer;
            this.preparer        = preparer;
            this.optionsProvider = optionsProvider;
            this.deviceProvider  = deviceProvider;
            this.progress        = progress;
            this.phone           = phone;

            sizeReservedForWindows =
                this.WhenAnyValue(x => x.GbsReservedForWindows, ByteSize.FromGigaBytes)
                .ToProperty(this, x => x.SizeReservedForWindows);

            DeleteDownloadedWrapper     = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(() => DeleteDownloaded(fileSystemOperations)), uiServices.Dialog);
            ForceDualBootWrapper        = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(ForceDualBoot), uiServices.Dialog);
            ForceDisableDualBootWrapper = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(ForceDisableDualBoot), uiServices.Dialog);

            BackupCommandWrapper  = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(Backup), uiServices.Dialog);
            RestoreCommandWrapper = new CommandWrapper <Unit, Unit>(this, ReactiveCommand.CreateFromTask(Restore), uiServices.Dialog);

            IsBusyObservable = Observable.Merge(new []
            {
                DeleteDownloadedWrapper.Command.IsExecuting,
                BackupCommandWrapper.Command.IsExecuting,
                RestoreCommandWrapper.Command.IsExecuting,
                ForceDualBootWrapper.Command.IsExecuting,
                ForceDisableDualBootWrapper.Command.IsExecuting,
            });
        }
Пример #4
0
        private void AddFileToFolder(PackageFolder folder, string file)
        {
            if (folder == null)
            {
                string guessFolderName = FileHelper.GuessFolderNameFromFile(file);
                bool   confirmed       = UIServices.Confirm(
                    String.Format(CultureInfo.CurrentCulture, Resources.ConfirmToMoveFileIntoFolder, file, guessFolderName));

                if (confirmed)
                {
                    if (RootFolder.ContainsFolder(guessFolderName))
                    {
                        folder = (PackageFolder)RootFolder[guessFolderName];
                    }
                    else
                    {
                        folder = RootFolder.AddFolder(guessFolderName);
                    }
                }
                else
                {
                    folder = RootFolder;
                }
            }

            folder.AddFile(file);
        }
Пример #5
0
        public string?GetCurrentPackageTempFile()
        {
            var tempFile = Path.GetTempFileName();

            try
            {
                // handle signed packages since they cannot be resaved without losing the signature
                if (IsSigned)
                {
                    File.Copy(PackagePath, tempFile, overwrite: true);
                }
                else
                {
                    PackageHelper.SavePackage(PackageMetadata, GetFiles(), tempFile, useTempFile: false);
                }
            }
            catch (Exception e)
            {
                if (!(e is ArgumentException))
                {
                    DiagnosticsClient.Notify(e);
                }
                UIServices.Show(e.Message, MessageLevel.Error);
            }

            if (File.Exists(tempFile))
            {
                return(tempFile);
            }

            return(null);
        }
        internal bool SaveMetadataAfterEditSource(string editedFilePath)
        {
            if (!File.Exists(editedFilePath))
            {
                return(true);
            }

            using (Stream metadataFileStream = File.OpenRead(editedFilePath))
            {
                try
                {
                    using (var str = ManifestUtility.ReadManifest(metadataFileStream))
                    {
                        Manifest manifest    = Manifest.ReadFrom(str, true);
                        var      newMetadata = new EditablePackageMetadata(manifest.Metadata, _uiServices);
                        PackageMetadata = newMetadata;

                        return(true);
                    }
                }
                catch (Exception exception)
                {
                    bool confirmExit = UIServices.ConfirmCloseEditor(
                        "There is an error in the metadata source.",
                        exception.GetBaseException().Message +
                        Environment.NewLine +
                        Environment.NewLine +
                        "Do you want to cancel your changes and return?");

                    return(confirmExit);
                }
            }
        }
Пример #7
0
        private void ExecuteBackupBindingsCmd(object param)
        {
            if (string.IsNullOrEmpty(this.BindingsBackupPath) || !Directory.Exists(this.BindingsBackupPath))
            {
                NotificationHelper.WriteNotification("Chemin de backup invalide.");
            }
            else
            {
                var appList = this.AllSelected ? this._services.GetAllApplications() : (param as IEnumerable).Cast <Application>();
                NotificationHelper.WriteNotification(
                    string.Format("Début du backup de {0} application(s).", appList.Count())
                    );

                UIServices.SetBusyState();

                foreach (var app in appList)
                {
                    NotificationHelper.WriteNotification("Export du binding pour " + app.Name + " dans " + this.BindingsBackupPath + "...");

                    var trace = this._services.ExportBinding(app.Name, this.BindingsBackupPath);

                    NotificationHelper.WriteNotification(trace);
                }
            }
        }
Пример #8
0
 async Task CheckAppConfiguration()
 {
     //try to get configuration
     configuration = appServices.GetConfiguration();
     // init configuration if it's empty ( use default api key & user current location etc ..)
     if (string.IsNullOrEmpty(configuration.APIKey))
     {
         await appServices.InitConfiguration(configuration);
     }
     //run synchronization if exist
     if (configuration.synchronization)
     {
         refreshTimer = new Timer(async(e) =>
         {
             if (canRefresh)
             {
                 await vm.BuildCompleteViewModel();
             }
             canRefresh = true;
         }, null, 0, (int.Parse(configuration.duration)) * 60 * 1000);
     }
     // run animation id exist
     if (configuration.runAnimation)
     {
         animationTimer = new Timer((e) =>
         {
             UIServices.ScaleImage(weatherImage);
         }, null, 0, AppConstants.AnimationDuration);
     }
 }
Пример #9
0
        public void RenameItem(WorkspaceItem item)
        {
            var path        = item.Path;
            var name        = Path.GetFileNameWithoutExtension(path);
            var nameWithExt = Path.GetFileName(path);
            var ext         = Path.GetExtension(path);

            var result = UIServices.CreateDialog <PromptData>(UI.Enums.DialogType.GenericPrompt, "Rename", name);

            if (!result.Success)
            {
                return;
            }

            if (name.Equals(result.Data.Value, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            switch (item.Type)
            {
            case WorkspaceItemType.Solution:
                var newSlnPath = Path.Combine(Path.GetDirectoryName(path), result.Data.Value + ext);
                File.Move(path, newSlnPath);
                Instance.OpenSolution(newSlnPath);
                break;

            case WorkspaceItemType.Project:
                var newPrjPath = Path.Combine(Path.GetDirectoryName(path), result.Data.Value + ext);
                File.Move(path, newPrjPath);

                foreach (var proj in Workspace.SlnFile.Projects)
                {
                    if (Path.GetFileName(proj.FilePath).Equals(nameWithExt, StringComparison.OrdinalIgnoreCase))
                    {
                        proj.Name     = result.Data.Value;
                        proj.FilePath = Path.Combine(Path.GetDirectoryName(proj.FilePath), result.Data.Value + ext);
                    }
                }

                Workspace.SlnFile.Write();
                Instance.OpenSolution(Workspace.SlnFile.FullPath);
                break;

            case WorkspaceItemType.Folder:
                var newDirPath = Path.Combine(Path.GetDirectoryName(path), result.Data.Value);
                Directory.Move(path, newDirPath);
                Instance.UpdateWorkspaceItems();
                break;

            case WorkspaceItemType.File:
                var newFilePath = Path.Combine(Path.GetDirectoryName(path), result.Data.Value + ext);
                File.Move(path, newFilePath);
                Instance.UpdateWorkspaceItems();
                break;

            default:
                break;
            }
        }
Пример #10
0
        private void PublishExecute()
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                UIServices.Show(Resources.NoNetworkConnection, MessageLevel.Warning);
                return;
            }

            // validate the package to see if there is any error before actually creating the package.
            var firstIssue = Validate().FirstOrDefault(p => p.Level == PackageIssueLevel.Error);

            if (firstIssue != null)
            {
                UIServices.Show(
                    Resources.PackageCreationFailed
                    + Environment.NewLine
                    + Environment.NewLine
                    + firstIssue.Description,
                    MessageLevel.Warning);
                return;
            }

            using (var mruSourceManager = new MruPackageSourceManager(
                       new PublishSourceSettings(_settingsManager)))
            {
                var publishPackageViewModel = new PublishPackageViewModel(
                    mruSourceManager,
                    _settingsManager,
                    _uiServices,
                    _credentialPublishProvider,
                    this);
                _uiServices.OpenPublishDialog(publishPackageViewModel);
            }
        }
Пример #11
0
        private Result GetOverwriteResult(SourceTarget source
                                          , IFileInfo target)
        {
            Result result = Result.Yes;

            if (target.Exists)
            {
                result = Result.No;

                if (Overwrite == OverwriteOptionConstants.Ask)
                {
                    Int64 startTicks = DateTime.Now.Ticks;

                    result = UIServices.ShowMessageBox("Overwrite \"" + target.FullName + "\"\nfrom \"" + source.SourceFile.FullName + "\"?", "Overwrite?", Buttons.YesNoCancel, Icon.Question);

                    Int64 endTicks = DateTime.Now.Ticks;

                    TimeSpan span = new TimeSpan(endTicks - startTicks);

                    CopyPaused?.Invoke(this, new EventArgs <TimeSpan>(span));
                }
                else if (Overwrite == OverwriteOptionConstants.Always)
                {
                    result = Result.Yes;
                }
            }

            return(result);
        }
Пример #12
0
        private void OnExportPublicKeyConfirmMsg(ExportPublicKeyConfirmMsg msg)
        {
            _isProcessInProgress = true;
            UIServices.SetBusyState();
            _logger.Info("export public key confirmed --> export key file");
            _logger.Info("export path: " + msg.Filename);

            MasterLogin login = _database.GetAll <MasterLogin>().FirstOrDefault();

            if (login != null)
            {
                bool success = _cryptographyService.ExportPublicKeyFile(msg.Filename, login.PublicKey);

                if (success)
                {
                    _logger.Info("export successful");
                    _messenger.Send(new ExportPublicKeySuccsessMsg());
                }
                else
                {
                    _logger.Error("export failed");
                    _messenger.Send(new ExportPublicKeyFailedMsg());
                }
            }
            else
            {
                _logger.Error("login is null!");
            }

            _isProcessInProgress = false;
        }
Пример #13
0
        private void Copy(CancellationToken cancellationToken)
        {
            RemainingTimeCalculator.Start();

            OnModelProgressMaxChanged(this, EventArgs.Empty);
            OnModelProgressValueChanged(this, EventArgs.Empty);

            Model.SizeChanged     += OnModelProgressMaxChanged;
            Model.ProgressChanged += OnModelProgressValueChanged;
            Model.CopyPaused      += OnModelCopyPaused;

            TaskIsRunning = true;

            try
            {
                Model.Copy(TargetPath, SelectedOverwriteOption, cancellationToken);
            }
            catch (Exception ex)
            {
                UIServices.ShowMessageBox(ex.Message, "Error", Buttons.OK, Icon.Error);
            }

            TaskIsRunning = false;

            Model.CopyPaused      -= OnModelCopyPaused;
            Model.ProgressChanged -= OnModelProgressValueChanged;
            Model.SizeChanged     -= OnModelProgressMaxChanged;
        }
Пример #14
0
        private void PublishExecute()
        {
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                UIServices.Show(Resources.NoNetworkConnection, MessageLevel.Warning);
                return;
            }

            if (!this.IsValid)
            {
                UIServices.Show(Resources.PackageHasNoFile, MessageLevel.Warning);
                return;
            }

            string storedKey = _settingsManager.ReadApiKeyFromSettingFile();
            var    publishPackageViewModel = new PublishPackageViewModel(_settingsManager.PublishPackageLocation, this)
            {
                PublishKey = storedKey
            };

            _uiServices.OpenPublishDialog(publishPackageViewModel);

            string newKey = publishPackageViewModel.PublishKey;

            if (!String.IsNullOrEmpty(newKey))
            {
                _settingsManager.WriteApiKeyToSettingFile(newKey);
            }
        }
Пример #15
0
 public DialogViewModel(IViewModel dialogContext, UIServices uiServices, ILogger logger)
 {
     _context             = dialogContext;
     _dialogManager       = uiServices.DialogManager;
     _folderBrowserDialog = uiServices.FolderBrowserDialog;
     _log = logger;
 }
Пример #16
0
        private void AddFiles()
        {
            OpenFileDialogOptions options = new OpenFileDialogOptions();

            options.CheckFileExists = true;
            options.Filter          = "Film files|*.avi;*.srt;*.mkv;*.mp4;*.flv|Recent files|RecentFiles.*.xml|All files|*.*";
            options.InitialFolder   = LastFolder;
            options.Title           = "Select File(s) to Copy";

            String[] fileNames;
            if (UIServices.ShowOpenFileDialog(options, out fileNames))
            {
                LastFolder = IOServices.GetFileInfo(fileNames[0]).FolderName;

                foreach (String file in fileNames)
                {
                    if ((file.Contains("RecentFiles")) && (file.EndsWith(".xml")))
                    {
                        Model.ReadXml(file);

                        TryAutoApplyFilter();
                    }
                    else
                    {
                        Model.AddEntry(file);
                    }
                }

                RaiseFileEntriesChanged();
            }
        }
Пример #17
0
        internal void SubmitToGameState()
        {
            if (GameState.CanMeldLayOff(_meldOwner) &&
                AssociatedWithGameStateAlready == false &&
                _submittingMeld == false)
            {
                if (_temporaryCardsList.Count >= 3)
                {
                    _submittingMeld = true;
                    GameState.Meld(_meldOwner, _temporaryCardsList);
                    AssociateWithMeldInGameState(GameState.GetMelds(_meldOwner).Count - 1);
                    _submittingMeld = false;
                }
                else
                {
                    var playerCardsShape = UIServices.GetPlayerCardsShape(_meldOwner);
                    foreach (var c in _temporaryCardsList.ToArray())
                    {
                        playerCardsShape.CancelDrag(c);
                        _temporaryCardsList.Remove(c);
                    }

                    RenderContents();
                }
            }
        }
Пример #18
0
        public MainViewModel(IObservable <LogEvent> events, ICollection <DeployerItem> deployersItems, IPackageImporterFactory importerFactory, UIServices uiServices, ISettingsService settingsService, Func <Task <Phone> > getPhoneFunc)
        {
            DualBootViewModel = new DualBootViewModel(uiServices.DialogService, getPhoneFunc);

            DeployersItems = deployersItems;

            this.importerFactory = importerFactory;
            this.uiServices      = uiServices;
            this.settingsService = settingsService;
            this.getPhoneFunc    = getPhoneFunc;

            ShowWarningCommand = ReactiveCommand.CreateFromTask(() =>
                                                                uiServices.DialogService.ShowAlert(this, Resources.TermsOfUseTitle,
                                                                                                   Resources.WarningNotice));

            SetupPickWimCommand();

            var isDeployerSelected =
                this.WhenAnyValue(model => model.SelectedDeployerItem, (DeployerItem x) => x != null);
            var isSelectedWim = this.WhenAnyObservable(x => x.WimMetadata.SelectedImageObs)
                                .Select(metadata => metadata != null);

            var canDeploy =
                isSelectedWim.CombineLatest(isDeployerSelected, (hasWim, hasDeployer) => hasWim && hasDeployer);

            FullInstallWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                 ReactiveCommand.CreateFromTask(DeployUefiAndWindows, canDeploy), uiServices.DialogService);
            WindowsInstallWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                    ReactiveCommand.CreateFromTask(DeployWindows, canDeploy), uiServices.DialogService);
            InjectDriversWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                   ReactiveCommand.CreateFromTask(InjectPostOobeDrivers, isDeployerSelected),
                                                                   uiServices.DialogService);

            ImportDriverPackageWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                         ReactiveCommand.CreateFromTask(ImportDriverPackage), uiServices.DialogService);

            var isBusyObs = Observable.Merge(FullInstallWrapper.Command.IsExecuting,
                                             WindowsInstallWrapper.Command.IsExecuting,
                                             InjectDriversWrapper.Command.IsExecuting,
                                             ImportDriverPackageWrapper.Command.IsExecuting);

            var dualBootIsBusyObs = DualBootViewModel.IsBusyObs;

            isBusyHelper = Observable.Merge(isBusyObs, dualBootIsBusyObs)
                           .ToProperty(this, model => model.IsBusy);

            progressHelper = progressSubject
                             .Where(d => !double.IsNaN(d))
                             .ObserveOn(SynchronizationContext.Current)
                             .ToProperty(this, model => model.Progress);

            isProgressVisibleHelper = progressSubject
                                      .Select(d => !double.IsNaN(d))
                                      .ToProperty(this, x => x.IsProgressVisible);

            SetupLogging(events);

            hasWimHelper = this.WhenAnyValue(model => model.WimMetadata, (WimMetadataViewModel x) => x != null)
                           .ToProperty(this, x => x.HasWim);
        }
Пример #19
0
        public AdvancedViewModel(ILumiaSettingsService lumiaSettingsService, IFileSystemOperations fileSystemOperations,
                                 UIServices uiServices, IDeploymentContext context, IOperationContext operationContext, IOperationProgress progress,
                                 IList <Meta <IDiskLayoutPreparer> > diskPreparers,
                                 ILogCollector logCollector)
        {
            this.lumiaSettingsService = lumiaSettingsService;
            this.uiServices           = uiServices;
            this.context      = context;
            this.logCollector = logCollector;

            DiskPreparers = diskPreparers;

            DeleteDownloadedWrapper = new ProgressViewModel(ReactiveCommand.CreateFromTask(() => DeleteDownloaded(fileSystemOperations)), progress, this, uiServices.ContextDialog, operationContext);

            ForceDualBootWrapper = new ProgressViewModel(ReactiveCommand.CreateFromTask(ForceDualBoot), progress, this, uiServices.ContextDialog, operationContext);

            ForceSingleBootWrapper = new ProgressViewModel(ReactiveCommand.CreateFromTask(ForceDisableDualBoot), progress, this, uiServices.ContextDialog, operationContext);

            CollectLogsCommmandWrapper = new ProgressViewModel(ReactiveCommand.CreateFromTask(CollectLogs), progress, this, uiServices.ContextDialog, operationContext);

            IsBusyObservable = Observable.Merge(DeleteDownloadedWrapper.Command.IsExecuting,
                                                ForceDualBootWrapper.Command.IsExecuting, ForceSingleBootWrapper.Command.IsExecuting,
                                                CollectLogsCommmandWrapper.Command.IsExecuting);

            preparerUpdater = this.WhenAnyValue(x => x.SelectedPreparer)
                              .Where(x => x != null)
                              .Subscribe(x =>
            {
                context.DiskLayoutPreparer        = x.Value;
                lumiaSettingsService.DiskPreparer = (string)x.Metadata["Name"];
            });

            SelectedPreparer = GetInitialDiskPreparer();
        }
Пример #20
0
        internal void ExportManifest(string fullpath, bool askForConfirmation = true, bool includeFilesSection = true)
        {
            if (File.Exists(fullpath) && askForConfirmation)
            {
                var confirmed = UIServices.Confirm(
                    Resources.ConfirmToReplaceFile_Title,
                    string.Format(CultureInfo.CurrentCulture, Resources.ConfirmToReplaceFile, fullpath));
                if (!confirmed)
                {
                    return;
                }
            }

            var rootPath = Path.GetDirectoryName(fullpath);

            using (Stream fileStream = File.Create(fullpath))
            {
                var manifest = Manifest.Create(PackageMetadata);
                if (includeFilesSection)
                {
                    var tempPath = Path.GetTempPath();

                    manifest.Files.AddRange(RootFolder.GetFiles().Select(
                                                f => new ManifestFile
                    {
                        Source = string.IsNullOrEmpty(f.OriginalPath()) || f?.OriginalPath()?.StartsWith(tempPath, StringComparison.OrdinalIgnoreCase) == true ? f.Path : PathUtility.RelativePathTo(rootPath, f.OriginalPath() !),
                        Target = f.Path
                    })
Пример #21
0
        public DeploymentViewModel(
            IDeploymentContext context,
            IOperationContext operationContext,
            IWoaDeployer deployer, UIServices uiServices, AdvancedViewModel advancedViewModel,
            WimPickViewModel wimPickViewModel, IFileSystemOperations fileSystemOperations, IRaspberryPiSettingsService raspberryPiSettingsService,
            IDiskRoot diskRoot)
        {
            this.context                    = context;
            this.deployer                   = deployer;
            this.uiServices                 = uiServices;
            this.advancedViewModel          = advancedViewModel;
            this.wimPickViewModel           = wimPickViewModel;
            this.fileSystemOperations       = fileSystemOperations;
            this.raspberryPiSettingsService = raspberryPiSettingsService;

            var isSelectedWim = wimPickViewModel.WhenAnyObservable(x => x.WimMetadata.SelectedImageObs)
                                .Select(metadata => metadata != null);

            FullInstallWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                 ReactiveCommand.CreateFromTask(Deploy, isSelectedWim), uiServices.ContextDialog, operationContext);
            IsBusyObservable = FullInstallWrapper.Command.IsExecuting;
            isBusyHelper     = IsBusyObservable.ToProperty(this, model => model.IsBusy);

            RefreshDisksCommandWrapper = new CommandWrapper <Unit, IList <IDisk> >(this,
                                                                                   ReactiveCommand.CreateFromTask(diskRoot.GetDisks), uiServices.ContextDialog, operationContext);
            disks = RefreshDisksCommandWrapper.Command
                    .Select(x => x.Select(disk => new DiskViewModel(disk)))
                    .ToProperty(this, x => x.Disks);

            this.WhenAnyValue(x => x.SelectedDisk).Where(x => x != null).Subscribe(x => context.Device = new RaspberryPi(x.IDisk));
        }
Пример #22
0
        private void Decrypt(object obj)
        {
            _isProcessInProgress = true;
            UIServices.SetBusyState();

            _logger.Info("start decryption");
            _logger.Info("source: " + SourceFilepath);
            _logger.Info("destination: " + TargetFilepath);
            _logger.Info("sender: " + ContactName);

            if (CheckSoureAndTargetPath())
            {
                if (IsVaildFile())
                {
                    MasterLogin login = _database.GetAll <MasterLogin>().FirstOrDefault();

                    if (login != null)
                    {
                        bool isDecryped = _cryptographyService.DecryptFile(_sourceFilepath, _targetFilepath,
                                                                           login.PrivateKey);

                        if (isDecryped)
                        {
                            _messenger.Send(new DecryptionSuccsessMsg());
                        }
                        else
                        {
                            _logger.Error("file can not decrypt!");
                            _messenger.Send(new DecryptionFailedMsg());
                        }

                        _logger.Info("check if source file in temp directory and when it is, then delete");
                        CheckSourceFileInTempDirectory();

                        //reset inputs
                        SourceFilepath = string.Empty;
                        TargetFilepath = string.Empty;
                        ContactName    = string.Empty;
                    }
                    else
                    {
                        _logger.Error("login is null!");
                    }
                }
                else
                {
                    _logger.Error("file is not vaild for encryption! maybe encrpytion?");
                    _messenger.Send(new DecryptionFailedMsg());
                }
            }
            else
            {
                _logger.Error("source and/or target path are not vaild!");
                _messenger.Send(new SourceTargetInvaildMsg());
            }

            _disableForEncryption = true;
            _isProcessInProgress  = false;
        }
Пример #23
0
        public static object GetMainViewModel(IObservable <LogEvent> logEvents)
        {
            ServiceFactory.Current = new DefaultServiceFactory();

            var deployer   = new RaspberryPiDeployer(new ImageFlasher(), new RaspberryPiWindowsDeployer(ServiceFactory.Current.ImageService, new DeploymentPaths(@"Files")));
            var uiServices = new UIServices(new FilePicker(), new ViewService(), new DialogService(DialogCoordinator.Instance));

            return(new MainViewModel(logEvents, deployer, new PackageImporterFactory(), ServiceFactory.Current.DiskService, uiServices, new SettingsService()));
        }
Пример #24
0
        private void Encrypt(object obj)
        {
            _isProcessInProgress = true;
            UIServices.SetBusyState();

            _logger.Info("start encryption");
            _logger.Info("source: " + _sourceFilepath);
            _logger.Info("destination: " + _targetFilepath);
            _logger.Info("receipient: " + _contactName);

            if (CheckSoureAndTargetPath())
            {
                if (string.IsNullOrEmpty(ContactName))
                {
                    MasterLogin login = _database.GetAll <MasterLogin>().FirstOrDefault();

                    if (login != null)
                    {
                        _logger.Info("encrpyt file for myself");

                        _cryptographyService.EncryptFile(_sourceFilepath, _targetFilepath, login.PublicKey);
                        _messenger.Send(new EncryptionSuccsessMsg {
                            TargetPath = _targetFilepath + ".sfs"
                        });
                    }
                    else
                    {
                        _logger.Error("login is null!");
                    }
                }
                else
                {
                    _logger.Info("encrpyt file for: " + ContactName);

                    _cryptographyService.EncryptFile(_sourceFilepath, _targetFilepath, PublicKey);
                    _messenger.Send(new EncryptionSuccsessMsg {
                        TargetPath = _targetFilepath
                    });
                }

                _logger.Info("check if source file in temp directory and when it is, then delete");
                CheckSourceFileInTempDirectory();

                //reset inputs
                SourceFilepath = string.Empty;
                TargetFilepath = string.Empty;
                ContactName    = string.Empty;
            }
            else
            {
                _logger.Error("source and/or target path are not vaild!");
                _messenger.Send(new SourceTargetInvaildMsg());
            }

            _disableForEncryption = true;
            _isProcessInProgress  = false;
        }
Пример #25
0
        private void AddNewFolderExecute(object parameter)
        {
            PackageFolder folder     = (parameter ?? SelectedItem) as PackageFolder;
            string        folderName = "NewFolder";
            bool          result     = UIServices.OpenRenameDialog(folderName, out folderName);

            if (result)
            {
                folder.AddFolder(folderName);
            }
        }
Пример #26
0
        public void Copy(String targetLocation
                         , String overwrite
                         , CancellationToken cancellationToken)
        {
            TargetLocation    = targetLocation;
            Overwrite         = overwrite;
            CancellationToken = cancellationToken;

            ProgressValue = 0;

            List <SourceTarget> fileInfos = new List <SourceTarget>();

            foreach (String entry in Entries)
            {
                if (IOServices.Folder.Exists(entry))
                {
                    IEnumerable <String> files = IOServices.Folder.GetFiles(entry, searchOption: System.IO.SearchOption.AllDirectories);

                    fileInfos.AddRange(files.Select(file => new SourceTarget(IOServices.GetFileInfo(file))));
                }
                else if (IOServices.File.Exists(entry))
                {
                    fileInfos.Add(new SourceTarget(IOServices.GetFileInfo(entry)));
                }
                else
                {
                    UIServices.ShowMessageBox("Something is weird about\n" + entry, "?!?", Buttons.OK, Icon.Error);

                    return;
                }
            }

            ResetSize();

            IDriveInfo driveInfo = IOServices.GetDriveInfo(IOServices.GetFolderInfo(TargetLocation).Root.Name.Substring(0, 1));

            if (driveInfo.AvailableFreeSpace <= Size)
            {
                FileSize spaceSize = new FileSize(driveInfo.AvailableFreeSpace);

                FileSize bytesSize = new FileSize(Size);

                UIServices.ShowMessageBox($"Target is Full!{Environment.NewLine}Available: {spaceSize}{Environment.NewLine}Needed: {bytesSize}", "Target Full", Buttons.OK, Icon.Warning);

                return;
            }

            Copy(fileInfos);

            ProgressValue = 0;

            App.WasCopied = true;
        }
Пример #27
0
 private void AddContentFileExecute(object parameter)
 {
     try
     {
         var folder = (parameter ?? SelectedItem) as PackageFolder;
         AddExistingFileToFolder(folder ?? RootFolder);
     }
     catch (Exception e)
     {
         UIServices.Show(e.Message, MessageLevel.Error);
     }
 }
Пример #28
0
        private void AddNewFolderExecute(object parameter)
        {
            parameter ??= SelectedItem ?? RootFolder;
            var folder     = parameter as PackageFolder;
            var folderName = "NewFolder";
            var result     = UIServices.OpenRenameDialog(folderName, "Provide name for the new folder.", out folderName);

            if (result)
            {
                folder?.AddFolder(folderName);
            }
        }
Пример #29
0
        public MainViewModel(IObservable <LogEvent> events, IDeployer <RaspberryPi> deployer, IPackageImporterFactory importerFactory, DiskService diskService,
                             UIServices uiServices, ISettingsService settingsService)
        {
            this.deployer               = deployer;
            this.importerFactory        = importerFactory;
            this.uiServices             = uiServices;
            this.settingsService        = settingsService;
            RefreshDisksCommmandWrapper = new CommandWrapper <Unit, ICollection <Disk> >(this,
                                                                                         ReactiveCommand.CreateFromTask(diskService.GetDisks), uiServices.DialogService);
            disksHelper = RefreshDisksCommmandWrapper.Command
                          .Select(x => x
                                  .Where(y => !y.IsBoot && !y.IsSystem && !y.IsOffline)
                                  .Select(disk => new DiskViewModel(disk)))
                          .ToProperty(this, x => x.Disks);

            ShowWarningCommand = ReactiveCommand.CreateFromTask(() => uiServices.DialogService.ShowAlert(this, Resources.TermsOfUseTitle,
                                                                                                         Resources.WarningNotice));

            ImportDriverPackageWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                         ReactiveCommand.CreateFromTask(ImportDriverPackage), uiServices.DialogService);

            SetupPickWimCommand();

            var whenAnyValue = this.WhenAnyValue(x => x.SelectedDisk, (DiskViewModel disk) => disk != null);

            var canDeploy = this.WhenAnyObservable(x => x.WimMetadata.SelectedImageObs)
                            .Select(metadata => metadata != null)
                            .CombineLatest(whenAnyValue, (isWimSelected, isDiskSelected) => isDiskSelected && isWimSelected);

            FullInstallWrapper = new CommandWrapper <Unit, Unit>(this,
                                                                 ReactiveCommand.CreateFromTask(DeployUefiAndWindows, canDeploy), uiServices.DialogService);

            var isBusyObs = FullInstallWrapper.Command.IsExecuting;

            isBusyHelper = isBusyObs.ToProperty(this, model => model.IsBusy);

            progressHelper = progressSubject
                             .Where(d => !double.IsNaN(d))
                             .ObserveOn(SynchronizationContext.Current)
                             .ToProperty(this, model => model.Progress);

            isProgressVisibleHelper = progressSubject
                                      .Select(d => !double.IsNaN(d))
                                      .ToProperty(this, x => x.IsProgressVisible);

            SetupLogging(events);

            hasWimHelper = this.WhenAnyValue(model => model.WimMetadata, (WimMetadataViewModel x) => x != null)
                           .ToProperty(this, x => x.HasWim);

            DonateCommand = ReactiveCommand.Create(() => { Process.Start(DonationLink); });
        }
Пример #30
0
        private void SaveContentExecute(PackageFile file)
        {
            string selectedFileName;
            string title  = "Save " + file.Name;
            string filter = "All files (*.*)|*.*";

            if (UIServices.OpenSaveFileDialog(title, file.Name, filter, out selectedFileName))
            {
                using (FileStream fileStream = File.OpenWrite(selectedFileName)) {
                    file.GetStream().CopyTo(fileStream);
                }
            }
        }
        public AjaxResponse LoadQuoteFromHorizon(QuoteHeader quoteHeader)
        {
            ErrorMessage = string.Empty;
            InfoMessage = string.Empty;

            var response = new AjaxResponse { quoteHeader = quoteHeader };

            InitializeSessionHeaderForRetrieve(quoteHeader);

            this.QHeader.QualityGroup = QuoteServices.GetQualityGroup(qHeader, this.BusinessLogic().PropertyAddress.PostalCode);

            var quoteStatus = GetCompanysPolicyNumber(quoteHeader);

            //ITR#9394 - When Credit Card Authorization Failed, the user should be able to retrieve the quote
            // to continue to purchase the quote despite having a policy number assigned.
            if (DirectWebDAC.AllowRetrieveAfterDeclinedTransaction(qHeader.QuoteNumber))
            {
                quoteStatus = 0;
            }

            Step nextPageIndex;

            var retrieveStatus = ServiceInterface.CallRetrieveIQuoteService();
            if (quoteStatus != -1 && (retrieveStatus == 0 || retrieveStatus == -8))
            {
                DataBinder.RefreshDataObjects();

                nextPageIndex = InterpretCompleteQuoteFlag(quoteHeader);

                UpdateAgeOfClaimForRetrieve();

                SetCompleteQuoteFlagForRetrieve(quoteHeader);

                this.BusinessLogic().Quote.CompleteQuoteFlag = (short)quoteHeader.CompleteQuoteFlag;

                response.quoteHeader.TrackingId = DirectWebDAC.GetTrackingId(quoteHeader.QuoteNumber);

                DataBinder.SaveDataObjects();

                ServiceInterface.CallValidateAddressServiceForRetrieve();

                // check address dnqs again & make sure horizon didn't dnq this quote
                if (!RetrieveDNQ() && this.BusinessLogic().Quote.CompleteQuoteFlag != 2)
                {
                    RestoreQuoteHeader(response);
                    //ITR#8945 - Check Contact Customer Care Logic & Redirect to Page for complete quote flag.
                    if (!RetrieveContactCustomerCare())
                    {
                        DataBinder.SaveDefaultAddress();

                        ServiceInterface.CallCreditService();
                        ServiceInterface.CallDefaultService();
                        if(PartnerConfiguration != null)
                        {
                            DataBinder.SaveMarketingInfo(null, PartnerConfiguration);

                        }
                        else
                        {
                            DataBinder.SaveMarketingInfo();
                        }

                        DataBinder.SaveDataObjects();

                        this.BusinessLogic().Quote.PartnerId = qHeader.PartnerId;
                        this.BusinessLogic().Quote.RetrieveFlag = true;
                        this.BusinessLogic().Quote.AddressValidatedFlag = true;
                        this.BusinessLogic().Quote.PolicyEffectiveDate = Convert.ToDateTime(response.quoteHeader.PolicyEffectiveDate);
                        this.BusinessLogic().Quote.Save();

                        CheckExpiredQuote(quoteHeader, ref nextPageIndex);

                        //ITR#9651 Good Driver
                        //Set the AutoClaimsRequestID null in order to make a new call to auto claims service
                        if (quoteHeader.ExpiredQuote)
                        {
                            this.BusinessLogic().PrimaryPerson.AutoClaimsRequestID = null;
                            this.BusinessLogic().PrimaryPerson.Save();
                        }

                        GetUpdatedTRSInfoOnRetrieve();

                        ServiceInterface.CallRatingService();

                        ServiceInterface.FixIPropPhone();

                        if (ControlData.Count > 0)
                        {
                            foreach (var t in ControlData)
                            {
                                response.DataSource.Add(t);
                            }
                        }

                        ControlData.Clear();

                    }
                    else
                    {
                        response.NextPanel = AjaxPanel.ContactCustomerCare;
                        response.RedirectURL = "ContactCustomerCare.aspx";
                    }

                }
                else
                {
                    response.NextPanel = AjaxPanel.DNQ;
                }
            }
            else if (quoteStatus == -1 || retrieveStatus == 1)
            {
                var uiSvc = new UIServices();
                var partnerPhoneNumber = uiSvc.GetPartnerPhoneNumber(quoteHeader.PartnerId);

                nextPageIndex = Step.InitialQuestions1;
                ErrorMessage = "This quote cannot be retrieved at this time.  Please call " + partnerPhoneNumber + " to talk to a licensed " +
                               "Customer Service Person and mention your Quote Number " + this.BusinessLogic().Quote.CompanysQuoteNumber + ".  We look forward to serving you.";
            }
            else // horizon returned a random error code.
            {
                nextPageIndex = Step.InitialQuestions1;
                ErrorMessage = "There was a problem processing your request.  Please try again later.";
            }

            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                if (nextPageIndex == Step.InitialQuestions2)
                {
                    response.NextPanel = AjaxPanel.Your_Address;
                    response.quoteHeader.LandingStep = "Your_Address";
                    response.RedirectURL = "BeginQuote.aspx";
                }
                else if (nextPageIndex == Step.InitialQuestions1)
                {
                    response.RedirectURL = "Welcome.aspx";
                }
                else
                {
                    response.RedirectURL = "BeginQuote.aspx";
                }

                response.errorMessage = ErrorMessage;
                response.errorOccured = true;
            }
            else
            {
                AjaxPanel nextPanel;

                switch (nextPageIndex)
                {
                    case Step.PremiumCustomization:
                        //ITR#8945 - Is ContactCustomerCare
                        if (quoteHeader.FormCode == 3 && IsContactCustomerCare)
                        {
                            nextPanel = AjaxPanel.ContactCustomerCare;
                        }
                        else
                        {
                            nextPanel = AjaxPanel.Coverage;
                        }
                        break;
                    case Step.DNQ:
                        nextPanel = AjaxPanel.DNQ;
                        break;
                    default:
                        if (quoteHeader.FormCode == 3)
                        {
                            nextPanel = AjaxPanel.Your_Address;
                        }
                        else if (quoteHeader.FormCode == 4)
                        {
                            nextPanel = AjaxPanel.About_You;
                        }
                        else if (quoteHeader.H06Ui_V2)
                        {
                            nextPanel = AjaxPanel.Condo_Information;
                        }
                        else if (quoteHeader.H04Ui_V2)
                        {
                            nextPanel = AjaxPanel.About_You;
                        }
                        else
                        {
                            throw new BusinessLogicException("Unknown starting point.");
                        }

                        break;
                }

                response.NextPanel = nextPanel;

            }

            response.quoteHeader.LandingStep = response.NextPanel.ToString();
            return response;
        }
        private Step InterpretCompleteQuoteFlag(QuoteHeader quoteHeader)
        {
            Step nextPageIndex;

            switch (quoteHeader.CompleteQuoteFlag)
            {
                case 1:
                    /* we are currently legally required to force all CA retrieves
                     * which didn't see the ITV question set back thru the quote flow */
                    if (this.BusinessLogic().QHeader.State.Equals("CA") &&
                        (this.BusinessLogic().QHeader.FormCode == 3) &&
                        (this.BusinessLogic().Structure.FoundationShape == null ||
                        this.BusinessLogic().Structure.FoundationShape == 0))
                    {
                        nextPageIndex = Step.IndicativeQuote;
                    }
                    else
                    {
                        nextPageIndex = Step.PremiumCustomization;
                    }
                    break;
                case 5:
                    nextPageIndex = Step.IndicativeQuote;
                    break;
                case 2:
                    nextPageIndex = Step.DNQ;
                    break;
                default:
                    {
                        UIServices uiSvc = new UIServices();
                        string partnerPhoneNumber = uiSvc.GetPartnerPhoneNumber(quoteHeader.PartnerId);

                        nextPageIndex = Step.InitialQuestions1;
                        this.ErrorMessage = "This quote cannot be retrieved at this time.  Please call " + partnerPhoneNumber + " to talk to a licensed " +
                                            "Customer Service Person and mention your Quote Number " + this.BusinessLogic().Quote.CompanysQuoteNumber + ".  We look forward to serving you.";
                    }
                    break;
            }

            return nextPageIndex;
        }