Beispiel #1
0
        public static async Task <IStorageItemWithPath> ToStorageItemWithPath(this string path, StorageFolderWithPath parentFolder = null)
        {
            StorageFolderWithPath rootFolder = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            FilesystemResult <StorageFileWithPath> fsFileWithPathResult = await FilesystemTasks.Wrap(() =>
            {
                return(StorageFileExtensions.DangerousGetFileWithPathFromPathAsync(path, rootFolder, parentFolder));
            });

            if (fsFileWithPathResult)
            {
                return(fsFileWithPathResult.Result);
            }

            FilesystemResult <StorageFolderWithPath> fsFolderWithPathResult = await FilesystemTasks.Wrap(() =>
            {
                return(StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path, rootFolder));
            });

            if (fsFolderWithPathResult)
            {
                return(fsFolderWithPathResult.Result);
            }

            return(null);
        }
Beispiel #2
0
        public async void GetSystemFileProperties()
        {
            StorageFile file = await FilesystemTasks.Wrap(() => StorageFile.GetFileFromPathAsync(Item.ItemPath).AsTask());

            if (file == null)
            {
                // Could not access file, can't show any other property
                return;
            }

            var list = await FileProperty.RetrieveAndInitializePropertiesAsync(file);

            list.Find(x => x.ID == "address").Value = await GetAddressFromCoordinatesAsync((double?)list.Find(x => x.Property == "System.GPS.LatitudeDecimal").Value,
                                                                                           (double?)list.Find(x => x.Property == "System.GPS.LongitudeDecimal").Value);

            var query = list
                        .Where(fileProp => !(fileProp.Value == null && fileProp.IsReadOnly))
                        .GroupBy(fileProp => fileProp.SectionResource)
                        .Select(group => new FilePropertySection(group)
            {
                Key = group.Key
            })
                        .OrderBy(group => group.Priority)
                        .Where(section => !section.All(fileProp => fileProp.Value == null));

            ViewModel.PropertySections = new ObservableCollection <FilePropertySection>(query);
            ViewModel.FileProperties   = new ObservableCollection <FileProperty>(list.Where(i => i.Value != null));
        }
Beispiel #3
0
        public static async Task <TOut> ToStorageItem <TOut>(string path, IShellPage associatedInstance = null) where TOut : IStorageItem
        {
            FilesystemResult <StorageFile>   file   = null;
            FilesystemResult <StorageFolder> folder = null;

            if (associatedInstance == null)
            {
                file = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(path));

                if (!file)
                {
                    folder = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path));
                }
            }
            else
            {
                file = await associatedInstance?.FilesystemViewModel?.GetFileFromPathAsync(path);

                if (!file)
                {
                    folder = await associatedInstance?.FilesystemViewModel?.GetFolderFromPathAsync(path);
                }
            }

            if (file)
            {
                return((TOut)(IStorageItem)file.Result);
            }
            else if (folder)
            {
                return((TOut)(IStorageItem)folder.Result);
            }

            return(default(TOut));
        }
Beispiel #4
0
        /// <summary>
        /// This function goes through ever read-write property saved, then syncs it
        /// </summary>
        /// <returns></returns>
        public async Task ClearPropertiesAsync()
        {
            var         failedProperties = new List <string>();
            StorageFile file             = await FilesystemTasks.Wrap(() => StorageFile.GetFileFromPathAsync(Item.ItemPath).AsTask());

            if (file == null)
            {
                return;
            }

            foreach (var group in ViewModel.PropertySections)
            {
                foreach (FileProperty prop in group)
                {
                    if (!prop.IsReadOnly)
                    {
                        var newDict = new Dictionary <string, object>();
                        newDict.Add(prop.Property, null);

                        try
                        {
                            await file.Properties.SavePropertiesAsync(newDict);
                        }
                        catch
                        {
                            failedProperties.Add(prop.Name);
                        }
                    }
                }
            }

            GetSystemFileProperties();
        }
Beispiel #5
0
        protected override async IAsyncEnumerable <ICloudProvider> GetProviders()
        {
            string configPathBoxDrive = Path.Combine(UserDataPaths.GetDefault().LocalAppData, @"Box\Box\data\shell\sync_root_folder.txt");
            string configPathBoxSync  = Path.Combine(UserDataPaths.GetDefault().LocalAppData, @"Box Sync\sync_root_folder.txt");

            StorageFile configFile = await FilesystemTasks.Wrap(() => StorageFile.GetFileFromPathAsync(configPathBoxDrive).AsTask());

            if (configFile is null)
            {
                configFile = await FilesystemTasks.Wrap(() => StorageFile.GetFileFromPathAsync(configPathBoxSync).AsTask());
            }
            if (configFile is not null)
            {
                string syncPath = await FileIO.ReadTextAsync(configFile);

                if (!string.IsNullOrEmpty(syncPath))
                {
                    yield return(new CloudProvider(CloudProviders.Box)
                    {
                        Name = "Box",
                        SyncFolder = syncPath,
                    });
                }
            }
        }
Beispiel #6
0
        public async Task <FilesystemResult <StorageFile> > Create(StorageFolder parentFolder, string fileName)
        {
            FilesystemResult <StorageFile> createdFile = null;

            if (!fileName.EndsWith(this.Extension))
            {
                fileName += this.Extension;
            }
            if (Template == null)
            {
                createdFile = await FilesystemTasks.Wrap(() => parentFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask());
            }
            else
            {
                createdFile = await FilesystemTasks.Wrap(() => StorageFile.GetFileFromPathAsync(Template).AsTask())
                              .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask());
            }
            if (createdFile)
            {
                if (this.Data != null)
                {
                    await FileIO.WriteBytesAsync(createdFile.Result, this.Data);
                }
            }
            return(createdFile);
        }
Beispiel #7
0
        public async Task DetectAsync(List <CloudProvider> cloudProviders)
        {
            try
            {
                var infoPathBoxDrive   = @"Box\Box\data\shell\sync_root_folder.txt";
                var configPathBoxDrive = Path.Combine(UserDataPaths.GetDefault().LocalAppData, infoPathBoxDrive);
                var infoPathBoxSync    = @"Box Sync\sync_root_folder.txt";
                var configPathBoxSync  = Path.Combine(UserDataPaths.GetDefault().LocalAppData, infoPathBoxSync);

                StorageFile configFile = await FilesystemTasks.Wrap(() => StorageFile.GetFileFromPathAsync(configPathBoxDrive).AsTask());

                if (configFile == null)
                {
                    configFile = await FilesystemTasks.Wrap(() => StorageFile.GetFileFromPathAsync(configPathBoxSync).AsTask());
                }
                if (configFile != null)
                {
                    var syncPath = await FileIO.ReadTextAsync(configFile);

                    if (!string.IsNullOrEmpty(syncPath))
                    {
                        cloudProviders.Add(new CloudProvider()
                        {
                            ID         = CloudProviders.Box,
                            Name       = "Box",
                            SyncFolder = syncPath
                        });
                    }
                }
            }
            catch
            {
                // Not detected
            }
        }
Beispiel #8
0
        public static async Task <FilesystemResult <BaseStorageFile> > Create(this ShellNewEntry shellEntry, BaseStorageFolder parentFolder, string fileName)
        {
            FilesystemResult <BaseStorageFile> createdFile = null;

            if (!fileName.EndsWith(shellEntry.Extension))
            {
                fileName += shellEntry.Extension;
            }
            if (shellEntry.Template == null)
            {
                createdFile = await FilesystemTasks.Wrap(() => parentFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask());
            }
            else
            {
                createdFile = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(shellEntry.Template))
                              .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask());
            }
            if (createdFile)
            {
                if (shellEntry.Data != null)
                {
                    //await FileIO.WriteBytesAsync(createdFile.Result, this.Data); // Calls unsupported OpenTransactedWriteAsync
                    using (var fileStream = await createdFile.Result.OpenStreamForWriteAsync())
                    {
                        await fileStream.WriteAsync(shellEntry.Data, 0, shellEntry.Data.Length);

                        await fileStream.FlushAsync();
                    }
                }
            }
            return(createdFile);
        }
Beispiel #9
0
        /// <summary>
        /// Adds the item do the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            if (res || (FilesystemResult)ItemViewModel.CheckFolderAccessWithWin32(path))
            {
                int insertIndex = MainPage.SideBarItems.IndexOf(MainPage.SideBarItems.Last(x => x.ItemType == NavigationControlItemType.Location &&
                                                                                           !x.Path.Equals(App.AppSettings.RecycleBinPath))) + 1;
                var locationItem = new LocationItem
                {
                    Font              = App.Current.Resources["FluentUIGlyphs"] as FontFamily,
                    Path              = path,
                    Glyph             = GetItemIcon(path),
                    IsDefaultLocation = false,
                    Text              = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
                };

                if (!MainPage.SideBarItems.Contains(locationItem))
                {
                    MainPage.SideBarItems.Insert(insertIndex, locationItem);
                }
            }
            else
            {
                Debug.WriteLine($"Pinned item was invalid and will be removed from the file lines list soon: {res.ErrorCode}");
                RemoveItem(path);
            }
        }
        /// <summary>
        /// Adds the item do the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
            {
                var lastItem    = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(App.AppSettings.RecycleBinPath));
                int insertIndex = lastItem != null?favoriteSection.ChildItems.IndexOf(lastItem) + 1 : 0;

                var locationItem = new LocationItem
                {
                    Font              = InteractionViewModel.FontName,
                    Path              = path,
                    Section           = SectionType.Favorites,
                    Icon              = GlyphHelper.GetIconUri(path),
                    IsDefaultLocation = false,
                    Text              = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
                };

                if (!favoriteSection.ChildItems.Contains(locationItem))
                {
                    favoriteSection.ChildItems.Insert(insertIndex, locationItem);
                }
            }
            else
            {
                Debug.WriteLine($"Pinned item was invalid and will be removed from the file lines list soon: {res.ErrorCode}");
                RemoveItem(path);
            }
        }
Beispiel #11
0
        public static async Task <IStorageItem> CreateFileFromDialogResultTypeForResult(AddItemType itemType, ShellNewEntry itemInfo, IShellPage associatedInstance)
        {
            string currentPath = null;

            if (associatedInstance.SlimContentPage != null)
            {
                currentPath = associatedInstance.FilesystemViewModel.WorkingDirectory;
            }

            // Show rename dialog
            DynamicDialog dialog = DynamicDialogFactory.GetFor_RenameDialog();
            await dialog.ShowAsync();

            if (dialog.DynamicResult != DynamicDialogResult.Primary)
            {
                return(null);
            }

            // Create file based on dialog result
            string userInput = dialog.ViewModel.AdditionalData as string;
            var    folderRes = await associatedInstance.FilesystemViewModel.GetFolderWithPathFromPathAsync(currentPath);

            FilesystemResult <(ReturnResult, IStorageItem)> created = null;

            if (folderRes)
            {
                switch (itemType)
                {
                case AddItemType.Folder:
                    userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : "NewFolder".GetLocalized();
                    created   = await FilesystemTasks.Wrap(async() =>
                    {
                        return(await associatedInstance.FilesystemHelpers.CreateAsync(
                                   StorageItemHelpers.FromPathAndType(System.IO.Path.Combine(folderRes.Result.Path, userInput), FilesystemItemType.Directory),
                                   true));
                    });

                    break;

                case AddItemType.File:
                    userInput = !string.IsNullOrWhiteSpace(userInput) ? userInput : itemInfo?.Name ?? "NewFile".GetLocalized();
                    created   = await FilesystemTasks.Wrap(async() =>
                    {
                        return(await associatedInstance.FilesystemHelpers.CreateAsync(
                                   StorageItemHelpers.FromPathAndType(System.IO.Path.Combine(folderRes.Result.Path, userInput + itemInfo?.Extension), FilesystemItemType.File),
                                   true));
                    });

                    break;
                }
            }

            if (created == FileSystemStatusCode.Unauthorized)
            {
                await DialogDisplayHelper.ShowDialogAsync("AccessDeniedCreateDialog/Title".GetLocalized(), "AccessDeniedCreateDialog/Text".GetLocalized());
            }

            return(created.Result.Item2);
        }
Beispiel #12
0
        private async Task <string> GetHashForFileAsync(ListedItem fileItem, string nameOfAlg, CancellationToken token, ProgressBar progress, IShellPage associatedInstance)
        {
            HashAlgorithmProvider algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(nameOfAlg);
            StorageFile           file = await StorageItemHelpers.ToStorageItem <StorageFile>((fileItem as ShortcutItem)?.TargetPath ?? fileItem.ItemPath, associatedInstance);

            if (file == null)
            {
                return("");
            }

            Stream stream = await FilesystemTasks.Wrap(() => file.OpenStreamForReadAsync());

            if (stream == null)
            {
                return("");
            }

            var  inputStream = stream.AsInputStream();
            var  str         = inputStream.AsStreamForRead();
            var  cap         = (long)(0.5 * str.Length) / 100;
            uint capacity;

            if (cap >= uint.MaxValue)
            {
                capacity = uint.MaxValue;
            }
            else
            {
                capacity = Convert.ToUInt32(cap);
            }

            Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity);
            var hash = algorithmProvider.CreateHash();

            while (!token.IsCancellationRequested)
            {
                await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None);

                if (buffer.Length > 0)
                {
                    hash.Append(buffer);
                }
                else
                {
                    break;
                }
                if (progress != null)
                {
                    progress.Value = (double)str.Position / str.Length * 100;
                }
            }
            inputStream.Dispose();
            stream.Dispose();
            if (token.IsCancellationRequested)
            {
                return("");
            }
            return(CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset()).ToLower());
        }
Beispiel #13
0
 private async void TryGetOneDriveFolder()
 {
     if (!await FilesystemTasks.Wrap(() => StorageFolder.GetFolderFromPathAsync(AppSettings.OneDrivePath).AsTask()))
     {
         AppSettings.PinOneDriveToSideBar = false;
         OneDrivePin.IsEnabled            = false;
     }
 }
Beispiel #14
0
        /// <summary>
        /// Adds the item (from a path) to the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            var locationItem = new LocationItem
            {
                Font        = MainViewModel.FontName,
                Path        = path,
                Section     = SectionType.Favorites,
                MenuOptions = new ContextMenuOptions
                {
                    IsLocationItem      = true,
                    ShowProperties      = true,
                    ShowUnpinItem       = true,
                    ShowShellItems      = true,
                    ShowEmptyRecycleBin = path == CommonPaths.RecycleBinPath,
                },
                IsDefaultLocation = false,
                Text = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
            };

            if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
            {
                locationItem.IsInvalid = false;
                if (res)
                {
                    var iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(res.Result, 24u, Windows.Storage.FileProperties.ThumbnailMode.ListView);

                    if (iconData == null)
                    {
                        iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(res.Result, 24u, Windows.Storage.FileProperties.ThumbnailMode.SingleItem);
                    }
                    locationItem.IconData = iconData;
                    locationItem.Icon     = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => locationItem.IconData.ToBitmapAsync());
                }
                if (locationItem.IconData == null)
                {
                    locationItem.IconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(path, 24u);

                    if (locationItem.IconData != null)
                    {
                        locationItem.Icon = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => locationItem.IconData.ToBitmapAsync());
                    }
                }
            }
            else
            {
                locationItem.Icon = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => UIHelpers.GetIconResource(Constants.ImageRes.Folder));

                locationItem.IsInvalid = true;
                Debug.WriteLine($"Pinned item was invalid {res.ErrorCode}, item: {path}");
            }

            AddLocationItemToSidebar(locationItem);
        }
Beispiel #15
0
        // TODO: If the TODO of IStorageItemWithPath is implemented, change return type to IStorageItem
        public static async Task <IStorageItem> ToStorageItem(this string path, StorageFolderWithPath parentFolder = null)
        {
            FilesystemResult <StorageFolderWithPath> fsRootFolderResult = await FilesystemTasks.Wrap(async() =>
            {
                return((StorageFolderWithPath)await Path.GetPathRoot(path).ToStorageItemWithPath());
            });

            FilesystemResult <StorageFile> fsFileResult = await FilesystemTasks.Wrap(() =>
            {
                return(StorageFileExtensions.DangerousGetFileFromPathAsync(path, fsRootFolderResult.Result, parentFolder));
            });

            if (fsFileResult)
            {
                if (!string.IsNullOrWhiteSpace(fsFileResult.Result.Path))
                {
                    return(fsFileResult.Result);
                }
                else
                {
                    FilesystemResult <StorageFileWithPath> fsFileWithPathResult = await FilesystemTasks.Wrap(() =>
                    {
                        return(StorageFileExtensions.DangerousGetFileWithPathFromPathAsync(path, fsRootFolderResult));
                    });

                    if (fsFileWithPathResult)
                    {
                        return(null); /* fsFileWithPathResult.Result */ // Could be done if IStorageItemWithPath implemented IStorageItem
                    }
                }
            }

            FilesystemResult <StorageFolder> fsFolderResult = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path));

            if (fsFolderResult)
            {
                if (!string.IsNullOrWhiteSpace(fsFolderResult.Result.Path))
                {
                    return(fsFolderResult.Result);
                }
                else
                {
                    FilesystemResult <StorageFolderWithPath> fsFolderWithPathResult = await FilesystemTasks.Wrap(() =>
                    {
                        return(StorageFileExtensions.DangerousGetFolderWithPathFromPathAsync(path, fsRootFolderResult));
                    });

                    if (fsFolderWithPathResult)
                    {
                        return(null); /* fsFolderWithPathResult.Result; */ // Could be done if IStorageItemWithPath implemented IStorageItem
                    }
                }
            }

            return(null);
        }
Beispiel #16
0
        private async Task LoadPreviewAndDetailsAsync()
        {
            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
            string returnformat = Enum.Parse <TimeStyle>(localSettings.Values[Constants.LocalSettings.DateTimeFormat].ToString()) == TimeStyle.Application ? "D" : "g";

            var rootItem = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(Item.ItemPath));

            Folder = await StorageFileExtensions.DangerousGetFolderFromPathAsync(Item.ItemPath, rootItem);

            var items = await Folder.GetItemsAsync();

            var iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(Folder, 400, ThumbnailMode.SingleItem);

            iconData ??= await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Item.ItemPath, 400);

            if (iconData != null)
            {
                Thumbnail = await iconData.ToBitmapAsync();
            }

            var info = await Folder.GetBasicPropertiesAsync();

            Item.FileDetails = new ObservableCollection <FileProperty>()
            {
                new FileProperty()
                {
                    NameResource = "PropertyItemCount",
                    Value        = items.Count,
                },
                new FileProperty()
                {
                    NameResource = "PropertyDateModified",
                    Value        = Extensions.DateTimeExtensions.GetFriendlyDateFromFormat(info.DateModified, returnformat, true)
                },
                new FileProperty()
                {
                    NameResource = "PropertyDateCreated",
                    Value        = Extensions.DateTimeExtensions.GetFriendlyDateFromFormat(info.ItemDate, returnformat, true)
                },
                new FileProperty()
                {
                    NameResource = "PropertyItemPathDisplay",
                    Value        = Folder.Path,
                }
            };

            if (UserSettingsService.PreferencesSettingsService.AreFileTagsEnabled)
            {
                Item.FileDetails.Add(new FileProperty()
                {
                    NameResource = "DetailsViewHeaderFlyout_ShowFileTag/Text",
                    Value        = Item.FileTagUI?.TagName
                });
            }
        }
Beispiel #17
0
        /// <summary>
        /// Adds the item do the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            var lastItem    = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(CommonPaths.RecycleBinPath));
            int insertIndex = lastItem != null?favoriteSection.ChildItems.IndexOf(lastItem) + 1 : 0;

            var locationItem = new LocationItem
            {
                Font              = MainViewModel.FontName,
                Path              = path,
                Section           = SectionType.Favorites,
                IsDefaultLocation = false,
                Text              = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
            };

            if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
            {
                locationItem.IsInvalid = false;
                if (res)
                {
                    var iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(res.Result, 24u, Windows.Storage.FileProperties.ThumbnailMode.ListView);

                    if (iconData == null)
                    {
                        iconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(res.Result, 24u, Windows.Storage.FileProperties.ThumbnailMode.SingleItem);
                    }
                    locationItem.IconData = iconData;
                    locationItem.Icon     = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => locationItem.IconData.ToBitmapAsync());
                }
                if (locationItem.IconData == null)
                {
                    locationItem.IconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(path, 24u);

                    if (locationItem.IconData != null)
                    {
                        locationItem.Icon = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => locationItem.IconData.ToBitmapAsync());
                    }
                }
            }
            else
            {
                locationItem.Icon = await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => UIHelpers.GetIconResource(Constants.ImageRes.Folder));

                locationItem.IsInvalid = true;
                Debug.WriteLine($"Pinned item was invalid {res.ErrorCode}, item: {path}");
            }

            if (!favoriteSection.ChildItems.Any(x => x.Path == locationItem.Path))
            {
                await CoreApplication.MainView.DispatcherQueue.EnqueueAsync(() => favoriteSection.ChildItems.Insert(insertIndex, locationItem));
            }
        }
Beispiel #18
0
        private async Task PopulateRecentItems(MenuFlyoutSubItemViewModel menu)
        {
            bool hasRecents = false;

            menu.Items.Add(new MenuFlyoutSeparatorViewModel());

            try
            {
                var mostRecentlyUsed = StorageApplicationPermissions.MostRecentlyUsedList;

                foreach (AccessListEntry entry in mostRecentlyUsed.Entries)
                {
                    string mruToken = entry.Token;
                    var    added    = await FilesystemTasks.Wrap(async() =>
                    {
                        IStorageItem item = await mostRecentlyUsed.GetItemAsync(mruToken, AccessCacheOptions.FastLocationsOnly);
                        if (item.IsOfType(StorageItemTypes.Folder))
                        {
                            menu.Items.Add(new MenuFlyoutItemViewModel(item.Name, string.IsNullOrEmpty(item.Path) ? entry.Metadata : item.Path, AddPageCommand));
                            hasRecents = true;
                        }
                    });

                    if (added == FileSystemStatusCode.Unauthorized)
                    {
                        // Skip item until consent is provided
                    }
                    // Exceptions include but are not limited to:
                    // COMException, FileNotFoundException, ArgumentException, DirectoryNotFoundException
                    // 0x8007016A -> The cloud file provider is not running
                    // 0x8000000A -> The data necessary to complete this operation is not yet available
                    // 0x80004005 -> Unspecified error
                    // 0x80270301 -> ?
                    else if (!added)
                    {
                        await FilesystemTasks.Wrap(() =>
                        {
                            mostRecentlyUsed.Remove(mruToken);
                            return(Task.CompletedTask);
                        });

                        System.Diagnostics.Debug.WriteLine(added.ErrorCode);
                    }
                }
            }
            catch (Exception ex)
            {
                App.Logger.Info(ex, "Could not fetch recent items");
            }

            if (!hasRecents)
            {
                menu.Items.RemoveAt(menu.Items.Count - 1);
            }
        }
Beispiel #19
0
        public static async Task PasteItemAsync(string destinationPath, IShellPage associatedInstance)
        {
            FilesystemResult <DataPackageView> packageView = await FilesystemTasks.Wrap(() => Task.FromResult(Clipboard.GetContent()));

            if (packageView && packageView.Result != null)
            {
                await associatedInstance.FilesystemHelpers.PerformOperationTypeAsync(packageView.Result.RequestedOperation, packageView, destinationPath, false, true);

                associatedInstance?.SlimContentPage?.ItemManipulationModel?.RefreshItemsOpacity();
            }
        }
Beispiel #20
0
        public static async Task PasteItemAsync(string destinationPath, IShellPage associatedInstance)
        {
            DataPackageView packageView = await FilesystemTasks.Wrap(() => Task.FromResult(Clipboard.GetContent()));

            if (packageView != null)
            {
                await associatedInstance.FilesystemHelpers.PerformOperationTypeAsync(packageView.RequestedOperation, packageView, destinationPath, true);

                associatedInstance.SlimContentPage.ResetItemOpacity();
            }
        }
Beispiel #21
0
        private static async Task <ShellNewEntry> ParseShellNewRegistryEntry(RegistryKey key, RegistryKey root)
        {
            if (!key.GetValueNames().Contains("NullFile") &&
                !key.GetValueNames().Contains("ItemName") &&
                !key.GetValueNames().Contains("FileName"))
            {
                return(null);
            }

            var extension = root.Name.Substring(root.Name.LastIndexOf('\\') + 1);
            var fileName  = (string)key.GetValue("FileName");

            if (!string.IsNullOrEmpty(fileName) && Path.GetExtension(fileName) != extension)
            {
                return(null);
            }

            byte[] data    = null;
            var    dataObj = key.GetValue("Data");

            if (dataObj != null)
            {
                switch (key.GetValueKind("Data"))
                {
                case RegistryValueKind.Binary:
                    data = (byte[])dataObj;
                    break;

                case RegistryValueKind.String:
                    data = UTF8Encoding.UTF8.GetBytes((string)dataObj);
                    break;
                }
            }

            var sampleFile = await FilesystemTasks.Wrap(() => ApplicationData.Current.LocalFolder.CreateFolderAsync("extensions", CreationCollisionOption.OpenIfExists).AsTask())
                             .OnSuccess(t => t.CreateFileAsync("file" + extension, CreationCollisionOption.OpenIfExists).AsTask());

            var displayType = sampleFile ? sampleFile.Result.DisplayType : string.Format("{0} {1}", "file", extension);
            var thumbnail   = sampleFile ? await FilesystemTasks.Wrap(() => sampleFile.Result.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.ListView, 24, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale).AsTask()) : null;

            var entry = new ShellNewEntry()
            {
                Extension = extension,
                Template  = fileName,
                Name      = displayType,
                Command   = (string)key.GetValue("Command"),
                //Name = (string)key.GetValue("ItemName"),
                //IconPath = (string)key.GetValue("IconPath"),
                Icon = thumbnail?.Result,
                Data = data
            };

            return(entry);
        }
        private async Task LoadAsync()
        {
            StorageFolder Folder = await FilesystemTasks.Wrap(() => ApplicationData.Current.LocalFolder.CreateFolderAsync("settings", CreationCollisionOption.OpenIfExists).AsTask());

            if (Folder == null)
            {
                Model = await GetDefaultTerminalFileModel();

                return;
            }

            var JsonFile = await FilesystemTasks.Wrap(() => Folder.GetFileAsync(JsonFileName).AsTask());

            if (!JsonFile)
            {
                if (JsonFile == FileSystemStatusCode.NotFound)
                {
                    Model = await GetDefaultTerminalFileModel();

                    SaveModel();
                    return;
                }
                else
                {
                    Model = await GetDefaultTerminalFileModel();

                    return;
                }
            }

            try
            {
                var content = await FileIO.ReadTextAsync(JsonFile.Result);

                configContent = content;
                Model         = JsonConvert.DeserializeObject <TerminalFileModel>(content);
                if (Model == null)
                {
                    throw new JsonParsingNullException(JsonFileName);
                }
            }
            catch (JsonParsingNullException)
            {
                Model = await GetDefaultTerminalFileModel();

                SaveModel();
            }
            catch (Exception)
            {
                Model = await GetDefaultTerminalFileModel();
            }
        }
        public async void DecompressArchiveToChildFolder()
        {
            var selectedItem = associatedInstance?.SlimContentPage?.SelectedItem;

            if (selectedItem == null)
            {
                return;
            }

            BaseStorageFile archive = await StorageHelpers.ToStorageItem <BaseStorageFile>(selectedItem.ItemPath);

            BaseStorageFolder currentFolder = await StorageHelpers.ToStorageItem <BaseStorageFolder>(associatedInstance.FilesystemViewModel.CurrentFolder.ItemPath);

            BaseStorageFolder destinationFolder = null;

            if (currentFolder != null)
            {
                destinationFolder = await FilesystemTasks.Wrap(() => currentFolder.CreateFolderAsync(Path.GetFileNameWithoutExtension(archive.Path), CreationCollisionOption.OpenIfExists).AsTask());
            }

            if (archive != null && destinationFolder != null)
            {
                CancellationTokenSource extractCancellation = new CancellationTokenSource();
                PostedStatusBanner      banner = App.OngoingTasksViewModel.PostOperationBanner(
                    string.Empty,
                    "ExtractingArchiveText".GetLocalized(),
                    0,
                    ReturnResult.InProgress,
                    FileOperationType.Extract,
                    extractCancellation);

                Stopwatch sw = new Stopwatch();
                sw.Start();

                await ZipHelpers.ExtractArchive(archive, destinationFolder, banner.Progress, extractCancellation.Token);

                sw.Stop();
                banner.Remove();

                if (sw.Elapsed.TotalSeconds >= 6)
                {
                    App.OngoingTasksViewModel.PostBanner(
                        "ExtractingCompleteText".GetLocalized(),
                        "ArchiveExtractionCompletedSuccessfullyText".GetLocalized(),
                        0,
                        ReturnResult.Success,
                        FileOperationType.Extract);
                }
            }
        }
Beispiel #24
0
        private async Task SavePropertiesAsync(StorageFile file)
        {
            foreach (KeyValuePair <string, object> valuePair in ViewModel.SystemFileProperties_RW)
            {
                var newDict = new Dictionary <string, object>();
                newDict.Add(valuePair.Key, valuePair.Value);
                var res = await FilesystemTasks.Wrap(() => file.Properties.SavePropertiesAsync(newDict).AsTask());

                if (!res)
                {
                    Debug.WriteLine(string.Format("{0}\n{1}", valuePair.Key, res.ErrorCode.ToString()));
                }
            }
        }
        private async void PopulateRecentsList()
        {
            Empty.Visibility = Visibility.Collapsed;

            try
            {
                var mostRecentlyUsed = StorageApplicationPermissions.MostRecentlyUsedList;

                foreach (AccessListEntry entry in mostRecentlyUsed.Entries)
                {
                    string mruToken = entry.Token;
                    var    added    = await FilesystemTasks.Wrap(async() =>
                    {
                        IStorageItem item = await mostRecentlyUsed.GetItemAsync(mruToken, AccessCacheOptions.FastLocationsOnly);
                        await AddItemToRecentListAsync(item, entry);
                    });

                    if (added == FileSystemStatusCode.Unauthorized)
                    {
                        // Skip item until consent is provided
                    }
                    // Exceptions include but are not limited to:
                    // COMException, FileNotFoundException, ArgumentException, DirectoryNotFoundException
                    // 0x8007016A -> The cloud file provider is not running
                    // 0x8000000A -> The data necessary to complete this operation is not yet available
                    // 0x80004005 -> Unspecified error
                    // 0x80270301 -> ?
                    else if (!added)
                    {
                        await FilesystemTasks.Wrap(() =>
                        {
                            mostRecentlyUsed.Remove(mruToken);
                            return(Task.CompletedTask);
                        });

                        System.Diagnostics.Debug.WriteLine(added.ErrorCode);
                    }
                }
            }
            catch (Exception ex)
            {
                App.Logger.Info(ex, "Could not fetch recent items");
            }

            if (recentItemsCollection.Count == 0)
            {
                Empty.Visibility = Visibility.Visible;
            }
        }
Beispiel #26
0
        public async override void GetSpecialProperties()
        {
            ViewModel.ItemAttributesVisibility = Visibility.Collapsed;
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(Drive.Path));

            StorageFolder diskRoot = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(Drive.Path, item));

            if (ViewModel.LoadFileIcon)
            {
                if (diskRoot != null)
                {
                    using var thumbnail = await diskRoot.GetThumbnailAsync(ThumbnailMode.SingleItem, 80, ThumbnailOptions.UseCurrentScale);

                    ViewModel.IconData = await thumbnail.ToByteArrayAsync();
                }
                else
                {
                    var fileIconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Drive.Path, 80);

                    ViewModel.IconData = fileIconData;
                }
            }

            if (diskRoot == null)
            {
                ViewModel.LastSeparatorVisibility = Visibility.Collapsed;
                return;
            }

            try
            {
                string freeSpace  = "System.FreeSpace";
                string capacity   = "System.Capacity";
                string fileSystem = "System.Volume.FileSystem";

                var properties = await diskRoot.Properties.RetrievePropertiesAsync(new[] { freeSpace, capacity, fileSystem });

                ViewModel.DriveCapacityValue  = (ulong)properties[capacity];
                ViewModel.DriveFreeSpaceValue = (ulong)properties[freeSpace];
                ViewModel.DriveUsedSpaceValue = ViewModel.DriveCapacityValue - ViewModel.DriveFreeSpaceValue;
                ViewModel.DriveFileSystem     = (string)properties[fileSystem];
            }
            catch (Exception e)
            {
                ViewModel.LastSeparatorVisibility = Visibility.Collapsed;
                App.Logger.Warn(e, e.Message);
            }
        }
        public static async Task <FilesystemResult <BaseStorageFile> > Create(this ShellNewEntry shellEntry, BaseStorageFolder parentFolder, string filePath)
        {
            FilesystemResult <BaseStorageFile> createdFile = null;
            var fileName = Path.GetFileName(filePath);

            if (!fileName.EndsWith(shellEntry.Extension, StringComparison.Ordinal))
            {
                fileName += shellEntry.Extension;
            }
            if (shellEntry.Command != null)
            {
                var args = CommandLine.CommandLineParser.SplitArguments(shellEntry.Command);
                if (args.Any())
                {
                    var connection = await AppServiceConnectionHelper.Instance;
                    if (connection != null)
                    {
                        _ = await connection.SendMessageForResponseAsync(new ValueSet()
                        {
                            { "Arguments", "LaunchApp" },
                            { "WorkingDirectory", PathNormalization.GetParentDir(filePath) },
                            { "Application", args[0].Replace("\"", "", StringComparison.Ordinal) },
                            { "Parameters", string.Join(" ", args.Skip(1)).Replace("%1", filePath) }
                        });
                    }
                }
                createdFile = new FilesystemResult <BaseStorageFile>(null, Shared.Enums.FileSystemStatusCode.Success);
            }
            else if (shellEntry.Template == null)
            {
                createdFile = await FilesystemTasks.Wrap(() => parentFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName).AsTask());
            }
            else
            {
                createdFile = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFileFromPathAsync(shellEntry.Template))
                              .OnSuccess(t => t.CopyAsync(parentFolder, fileName, NameCollisionOption.GenerateUniqueName).AsTask());
            }
            if (createdFile)
            {
                if (shellEntry.Data != null)
                {
                    //await FileIO.WriteBytesAsync(createdFile.Result, shellEntry.Data); // Calls unsupported OpenTransactedWriteAsync
                    await createdFile.Result.WriteBytesAsync(shellEntry.Data);
                }
            }
            return(createdFile);
        }
Beispiel #28
0
        /// <summary>
        /// Adds the item do the navigation sidebar
        /// </summary>
        /// <param name="path">The path which to save</param>
        /// <returns>Task</returns>
        public async Task AddItemToSidebarAsync(string path)
        {
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(path));

            var res = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(path, item));

            if (res || (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path))
            {
                var lastItem    = favoriteSection.ChildItems.LastOrDefault(x => x.ItemType == NavigationControlItemType.Location && !x.Path.Equals(App.AppSettings.RecycleBinPath));
                int insertIndex = lastItem != null?favoriteSection.ChildItems.IndexOf(lastItem) + 1 : 0;

                var locationItem = new LocationItem
                {
                    Font              = MainViewModel.FontName,
                    Path              = path,
                    Section           = SectionType.Favorites,
                    IsDefaultLocation = false,
                    Text              = res.Result?.DisplayName ?? Path.GetFileName(path.TrimEnd('\\'))
                };

                if (res)
                {
                    var thumbnail = await res.Result.GetThumbnailAsync(
                        Windows.Storage.FileProperties.ThumbnailMode.ListView,
                        24,
                        Windows.Storage.FileProperties.ThumbnailOptions.ResizeThumbnail);

                    if (thumbnail != null)
                    {
                        locationItem.IconData = await thumbnail.ToByteArrayAsync();

                        locationItem.Icon = await locationItem.IconData.ToBitmapAsync();
                    }
                }

                if (!favoriteSection.ChildItems.Contains(locationItem))
                {
                    favoriteSection.ChildItems.Insert(insertIndex, locationItem);
                }
            }
            else
            {
                Debug.WriteLine($"Pinned item was invalid and will be removed from the file lines list soon: {res.ErrorCode}");
                RemoveItem(path);
            }
        }
Beispiel #29
0
        public async override void GetSpecialProperties()
        {
            ViewModel.ItemAttributesVisibility = false;
            var item = await FilesystemTasks.Wrap(() => DrivesManager.GetRootFromPathAsync(Drive.Path));

            BaseStorageFolder diskRoot = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(Drive.Path, item));

            if (ViewModel.LoadFileIcon)
            {
                if (diskRoot != null)
                {
                    ViewModel.IconData = await FileThumbnailHelper.LoadIconFromStorageItemAsync(diskRoot, 80, ThumbnailMode.SingleItem);
                }
                else
                {
                    ViewModel.IconData = await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Drive.Path, 80);
                }
                ViewModel.IconData ??= await FileThumbnailHelper.LoadIconWithoutOverlayAsync(Drive.DeviceID, 80); // For network shortcuts
            }

            if (diskRoot == null || diskRoot.Properties == null)
            {
                ViewModel.LastSeparatorVisibility = false;
                return;
            }

            try
            {
                string freeSpace  = "System.FreeSpace";
                string capacity   = "System.Capacity";
                string fileSystem = "System.Volume.FileSystem";

                var properties = await diskRoot.Properties.RetrievePropertiesAsync(new[] { freeSpace, capacity, fileSystem });

                ViewModel.DriveCapacityValue  = (ulong)properties[capacity];
                ViewModel.DriveFreeSpaceValue = (ulong)properties[freeSpace];
                ViewModel.DriveUsedSpaceValue = ViewModel.DriveCapacityValue - ViewModel.DriveFreeSpaceValue;
                ViewModel.DriveFileSystem     = (string)properties[fileSystem];
            }
            catch (Exception e)
            {
                ViewModel.LastSeparatorVisibility = false;
                App.Logger.Warn(e, e.Message);
            }
        }
Beispiel #30
0
        /// <summary>
        /// This function goes through ever read-write property saved, then syncs it
        /// </summary>
        /// <returns></returns>
        public async Task ClearPersonalInformationAsync()
        {
            StorageFile file = await AppInstance.FilesystemViewModel.GetFileFromPathAsync(Item.ItemPath);

            if (file != null)
            {
                var dict = new Dictionary <string, object>();

                foreach (string str in PersonalProperties)
                {
                    dict.Add(str, null);
                }

                await FilesystemTasks.Wrap(() => file.Properties.SavePropertiesAsync(dict).AsTask());

                GetSpecialProperties();
            }
        }