async Task PickPhoto() { var hasPermission = await PermissionsCheck.PhotosAsync(); if (!hasPermission) { return; } var file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions { PhotoSize = PhotoSize.Full }); if (file == null) { return; } predictionMedia = new Models.MediaDetails() { Path = file.Path, PreviewPath = file.Path, Type = MediaFileType.Image, Date = DateTime.Now }; database.SaveItem(predictionMedia); SetPageState(PredictionPageState.Uploading); await UploadMedia(predictionMedia.FullPath); }
private TaskExecutionStatus DeleteFile(string path, bool coldRun) { if (File.Exists(path)) { FileLockWait(path); } try { File.Delete(path); } catch (Exception ex) { if (coldRun) { ExecutionStatus = TaskExecutionStatus.Failed; throw new UpdateProcessFailedException($"Unable to delete file: {path}", ex); } } if (File.Exists(path)) { if (PermissionsCheck.HaveWritePermissionsForFileOrFolder(path)) { return(TaskExecutionStatus.RequiresAppRestart); } else { return(TaskExecutionStatus.RequiresPrivilegedAppRestart); } } return(TaskExecutionStatus.Successful); }
public void HaveWritePermissionsForFolderDeniedTest() { string path = Environment.GetFolderPath(Environment.SpecialFolder.System); bool expected = false; // TODO: Initialize to an appropriate value bool actual; actual = PermissionsCheck.HaveWritePermissionsForFolder(path); Assert.AreEqual(expected, actual); }
public void HaveWritePermissionsForFolderTest() { string path = Path.GetTempPath(); //Guaranteed writable (I believe) bool expected = true; // TODO: Initialize to an appropriate value bool actual; actual = PermissionsCheck.HaveWritePermissionsForFolder(path); Assert.AreEqual(expected, actual); }
internal static void Main(string[] args) { if (!AlreadyRun) { AlreadyRun = true; if (PermissionsCheck.Demand() && VersionCheck.Check()) { ProgramStarter.Run(args); } } }
public override TaskExecutionStatus Execute(bool coldRun) { if (string.IsNullOrEmpty(LocalPath)) { UpdateManager.Instance.Logger.Log(Logger.SeverityLevel.Warning, "FileUpdateTask: LocalPath is empty, task is a noop"); return (TaskExecutionStatus .Successful); // Errorneous case, but there's nothing to prepare to, and by default we prefer a noop over an error } var dirName = Path.GetDirectoryName(_destinationFile); if (!Directory.Exists(dirName)) { Utils.FileSystem.CreateDirectoryStructure(dirName, false); } // Create a backup copy if target exists if (_backupFile == null && File.Exists(_destinationFile)) { if (!Directory.Exists(Path.GetDirectoryName(Path.Combine(UpdateManager.Instance.Config.BackupFolder, LocalPath)))) { string backupPath = Path.GetDirectoryName(Path.Combine(UpdateManager.Instance.Config.BackupFolder, LocalPath)); Utils.FileSystem.CreateDirectoryStructure(backupPath, false); } _backupFile = Path.Combine(UpdateManager.Instance.Config.BackupFolder, LocalPath); File.Copy(_destinationFile, _backupFile, true); } // Only allow execution if the apply attribute was set to hot-swap, or if this is a cold run if (CanHotSwap || coldRun) { if (File.Exists(_destinationFile)) { FileLockWait(); if (!PermissionsCheck.HaveWritePermissionsForFileOrFolder(_destinationFile)) { if (coldRun) { UpdateManager.Instance.Logger.Log(Logger.SeverityLevel.Warning, "Don't have permissions to touch {0}", _destinationFile); File.Delete(_destinationFile); // get the original exception from the system } CanHotSwap = false; } } try { if (File.Exists(_destinationFile)) { FileSystem.CopyAccessControl(new FileInfo(_destinationFile), new FileInfo(_tempFile)); File.Delete(_destinationFile); } File.Move(_tempFile, _destinationFile); _tempFile = null; } catch (Exception ex) { if (coldRun) { ExecutionStatus = TaskExecutionStatus.Failed; throw new UpdateProcessFailedException("Could not replace the file", ex); } // Failed hot swap file tasks should now downgrade to cold tasks automatically CanHotSwap = false; } } if (coldRun || CanHotSwap) { // If we got thus far, we have completed execution return(TaskExecutionStatus.Successful); } // Otherwise, figure out what restart method to use if (File.Exists(_destinationFile) && !Utils.PermissionsCheck.HaveWritePermissionsForFileOrFolder(_destinationFile)) { return(TaskExecutionStatus.RequiresPrivilegedAppRestart); } return(TaskExecutionStatus.RequiresAppRestart); }
public PermissionsPage() { var titleLabel = new Label() { Text = ApplicationResource.PagePermissionsTitle, FontSize = 30, TextColor = Color.DarkSlateGray, HorizontalOptions = LayoutOptions.CenterAndExpand }; var messageLabel = new Label() { Text = ApplicationResource.PagePermissionsMessage, WidthRequest = 300, TextColor = Color.SlateGray, HorizontalOptions = LayoutOptions.Center, HorizontalTextAlignment = TextAlignment.Center }; cameraButton = new Button() { Text = ApplicationResource.PagePermissionsCameraButton, HorizontalOptions = LayoutOptions.CenterAndExpand, BackgroundColor = AppColors.HeaderColor, TextColor = Color.White, FontAttributes = FontAttributes.Bold, WidthRequest = 180, HeightRequest = 40, CornerRadius = 10, Margin = new Thickness(0, 20, 0, 5) }; cameraButton.Clicked += async(sender, e) => { var hasPermission = await PermissionsCheck.CameraAsync(); if (hasPermission) { cameraButton.IsEnabled = false; cameraButton.Text = ApplicationResource.CameraPermissionGranted; cameraButton.BackgroundColor = Color.LightGray; hasCameraPermission = true; await CheckComplete(); } }; photosButton = new Button() { Text = ApplicationResource.PagePermissionsPhotosButton, HorizontalOptions = LayoutOptions.CenterAndExpand, BackgroundColor = AppColors.HeaderColor, TextColor = Color.White, FontAttributes = FontAttributes.Bold, WidthRequest = 180, HeightRequest = 40, CornerRadius = 10 }; photosButton.Clicked += async(sender, e) => { var hasPermission = await PermissionsCheck.PhotosAsync(); if (hasPermission) { photosButton.IsEnabled = false; photosButton.Text = ApplicationResource.PhotosPermissionGranted; photosButton.BackgroundColor = Color.LightGray; hasPhotoPermission = true; await CheckComplete(); } }; var centerLayout = new StackLayout(); centerLayout.HorizontalOptions = LayoutOptions.CenterAndExpand; centerLayout.VerticalOptions = LayoutOptions.CenterAndExpand; centerLayout.Children.Add(titleLabel); centerLayout.Children.Add(messageLabel); centerLayout.Children.Add(cameraButton); centerLayout.Children.Add(photosButton); Content = centerLayout; }
/// <summary> /// Starts the updater executable and sends update data to it /// </summary> /// <param name="relaunchApplication">true if relaunching the caller application is required; false otherwise</param> /// <param name="updaterDoLogging">true if the updater writes to a log file; false otherwise</param> /// <param name="updaterShowConsole">true if the updater shows the console window; false otherwise</param> /// <returns>True if successful (unless a restart was required</returns> public void ApplyUpdates(bool relaunchApplication, bool updaterDoLogging, bool updaterShowConsole) { if (IsWorking) { throw new InvalidOperationException("Another update process is already in progress"); } lock (UpdatesToApply) { using (WorkScope.New(isWorking => IsWorking = isWorking)) { bool revertToDefaultBackupPath = true; // Set current directory the the application directory // this prevents the updater from writing to e.g. c:\windows\system32 // if the process is started by autorun on windows logon. // ReSharper disable AssignNullToNotNullAttribute Environment.CurrentDirectory = Path.GetDirectoryName(ApplicationPath); // ReSharper restore AssignNullToNotNullAttribute // Make sure the current backup folder is accessible for writing from this process string backupParentPath = Path.GetDirectoryName(Config.BackupFolder) ?? string.Empty; if (Directory.Exists(backupParentPath) && PermissionsCheck.HaveWritePermissionsForFolder(backupParentPath)) { // Remove old backup folder, in case this same folder was used previously, // and it wasn't removed for some reason try { if (Directory.Exists(Config.BackupFolder)) { FileSystem.DeleteDirectory(Config.BackupFolder); } revertToDefaultBackupPath = false; } catch (UnauthorizedAccessException) { } // Attempt to (re-)create the backup folder try { Directory.CreateDirectory(Config.BackupFolder); if (!PermissionsCheck.HaveWritePermissionsForFolder(Config.BackupFolder)) { revertToDefaultBackupPath = true; } } catch (UnauthorizedAccessException) { // We're having permissions issues with this folder, so we'll attempt // using a backup in a default location revertToDefaultBackupPath = true; } } if (revertToDefaultBackupPath) { Config._backupFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Config.UpdateProcessName + "UpdateBackups" + DateTime.UtcNow.Ticks); try { Directory.CreateDirectory(Config.BackupFolder); } catch (UnauthorizedAccessException ex) { // We can't backup, so we abort throw new UpdateProcessFailedException("Could not create backup folder " + Config.BackupFolder, ex); } } bool runPrivileged = false, hasColdUpdates = false; State = UpdateProcessState.RollbackRequired; foreach (var task in UpdatesToApply) { IUpdateTask t = task; task.ProgressDelegate += status => TaskProgressCallback(status, t); try { // Execute the task task.ExecutionStatus = task.Execute(false); } catch (Exception ex) { task.ExecutionStatus = TaskExecutionStatus.Failed; // mark the failing task before rethrowing throw new UpdateProcessFailedException("Update task execution failed: " + task.Description, ex); } if (task.ExecutionStatus == TaskExecutionStatus.RequiresAppRestart || task.ExecutionStatus == TaskExecutionStatus.RequiresPrivilegedAppRestart) { // Record that we have cold updates to run, and if required to run any of them privileged runPrivileged = runPrivileged || task.ExecutionStatus == TaskExecutionStatus.RequiresPrivilegedAppRestart; hasColdUpdates = true; continue; } // We are being quite explicit here - only Successful return values are considered // to be Ok (cold updates are already handled above) if (task.ExecutionStatus != TaskExecutionStatus.Successful) { throw new UpdateProcessFailedException("Update task execution failed: " + task.Description); } } // If an application restart is required if (hasColdUpdates) { var dto = new NauIpc.NauDto { Configs = Instance.Config, Tasks = Instance.UpdatesToApply, AppPath = ApplicationPath, WorkingDirectory = Environment.CurrentDirectory, RelaunchApplication = relaunchApplication, LogItems = Logger.LogItems, }; NauIpc.ExtractUpdaterFromResource(Config.TempFolder, Instance.Config.UpdateExecutableName); var info = new ProcessStartInfo { UseShellExecute = true, WorkingDirectory = Environment.CurrentDirectory, FileName = Path.Combine(Config.TempFolder, Instance.Config.UpdateExecutableName), Arguments = string.Format(@"""{0}"" {1} {2}", Config.UpdateProcessName, updaterShowConsole ? "-showConsole" : string.Empty, updaterDoLogging ? "-log" : string.Empty), }; if (!updaterShowConsole) { info.WindowStyle = ProcessWindowStyle.Hidden; info.CreateNoWindow = true; } // If we can't write to the destination folder, then lets try elevating priviledges. if (runPrivileged || !PermissionsCheck.HaveWritePermissionsForFolder(Environment.CurrentDirectory)) { info.Verb = "runas"; } bool createdNew; _shutdownMutex = new Mutex(true, Config.UpdateProcessName + "Mutex", out createdNew); try { NauIpc.LaunchProcessAndSendDto(dto, info, Config.UpdateProcessName); } catch (Exception ex) { throw new UpdateProcessFailedException("Could not launch cold update process", ex); } Environment.Exit(0); } State = UpdateProcessState.AppliedSuccessfully; UpdatesToApply.Clear(); } } }