private void BackupDataWithIntersection( IEnumerable <KeyValuePair <BackupDataLogKey, BackupDataLogValue> > intersectingLogs, BackupDataLogKey logKey, KeyValuePair <long, int> area, OnDisk.File.IFile f, string fFilename, ConcurrentIOPoolManager readPool, ConcurrentIOPoolManager writePool, RecordKey key ) { if (intersectingLogs == null) { // process conflicts with other trans... //ProcessTransactionConflicts(logKey, area.Value); // area is within an already backed up area (intersectingLogs == null), do nothing... return; } LogTracer.Verbose("BackupDataWithIntersection: Start for Thread {0}.", Thread.CurrentThread.ManagedThreadId); // get area(s) outside each intersecting segment and back it up... var newRegion = new Region(area.Key, area.Value); #region for future implements... ? //bool wasIntersected = false; //foreach (KeyValuePair<BackupDataLogKey, BackupDataLogValue> entry in intersectingLogs) //{ // // process conflicts with other trans... // ProcessTransactionConflicts(entry.Key, entry.Value.DataSize); // if (newRegion.Subtract(entry.Key.SourceDataAddress, entry.Value.DataSize)) // wasIntersected = true; //} //if (!wasIntersected) return; #endregion // copy modified blocks to the transaction backup file. foreach (KeyValuePair <long, int> newArea in newRegion) { if (readPool.AsyncThreadException != null) { throw readPool.AsyncThreadException; } if (writePool.AsyncThreadException != null) { throw writePool.AsyncThreadException; } var logKey2 = new BackupDataLogKey(); logKey2.SourceFilename = logKey.SourceFilename; logKey2.SourceDataAddress = newArea.Key; var logValue = new BackupDataLogValue(); logValue.DataSize = newArea.Value; logValue.TransactionId = Id; int newSize = newArea.Value; key.Address = newArea.Key; //if (RegisterAdd(_addBlocksStore, null, null, key, newArea.Value, false)) // return; logValue.BackupFileHandle = GetLogBackupFileHandle(DataBackupFilename); ConcurrentIOData reader = f != null ? readPool.GetInstance(f, newArea.Value) : readPool.GetInstance(fFilename, null, newArea.Value); if (reader == null) { throw new InvalidOperationException("Can't get ConcurrentIOData from ReadPool"); } string systemBackupFilename = Server.Path + DataBackupFilename; ConcurrentIOData writer = writePool.GetInstance(systemBackupFilename, ((TransactionRoot)Root)); if (writer == null) { throw new InvalidOperationException("Can't get ConcurrentIOData from WritePool"); } // return the current backup file size and grow it to make room for data to be backed up... logValue.BackupDataAddress = GrowBackupFile(newSize, writer.FileStream); // save a record of the backed up data.. LogCollection.Add(logKey2, logValue); // prepare lambda expression to log after data was backed up!! Sop.VoidFunc logBackedupData = () => { UpdateLogger.LogLine( "{0}{1}:{2} to {3}:{4} Size={5}", BackupFromToken, logKey2.SourceFilename, logKey2.SourceDataAddress, DataBackupFilename, logValue.BackupDataAddress, newSize); }; writer.FileStream.Seek(logValue.BackupDataAddress, SeekOrigin.Begin, true); reader.FileStream.Seek(newArea.Key, SeekOrigin.Begin, true); reader.FileStream.BeginRead( reader.Buffer, 0, newSize, ReadCallback, new object[] { new[] { reader, writer }, true, logKey2, logBackedupData }); } }
private async void SecureArea_Loaded(object sender, RoutedEventArgs e) { try { WholeArea.Visibility = Visibility.Collapsed; SecureGridView.AddHandler(PointerPressedEvent, PointerPressedHandler, true); ApplicationView.GetForCurrentView().IsScreenCaptureEnabled = false; if (ApplicationData.Current.LocalSettings.Values.ContainsKey("IsFirstEnterSecureArea")) { AESKeySize = Convert.ToInt32(ApplicationData.Current.LocalSettings.Values["SecureAreaAESKeySize"]); if (ApplicationData.Current.LocalSettings.Values["SecureAreaLockMode"] is not string LockMode || LockMode != nameof(CloseLockMode) || IsNewStart) { if (Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"])) { RETRY: switch (await WindowsHelloAuthenticator.VerifyUserAsync()) { case AuthenticatorState.VerifyPassed: { break; } case AuthenticatorState.UnknownError: case AuthenticatorState.VerifyFailed: { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_WinHelloAuthFail_Content"), PrimaryButtonText = Globalization.GetString("Common_Dialog_TryAgain"), SecondaryButtonText = Globalization.GetString("Common_Dialog_UsePassword"), CloseButtonText = Globalization.GetString("Common_Dialog_GoBack") }; ContentDialogResult Result = await Dialog.ShowAsync(); if (Result == ContentDialogResult.Primary) { goto RETRY; } else if (Result == ContentDialogResult.Secondary) { if (!await EnterByPassword()) { return; } } else { GoBack(); return; } break; } case AuthenticatorState.UserNotRegistered: case AuthenticatorState.CredentialNotFound: { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_WinHelloCredentialLost_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"] = false; if (!await EnterByPassword()) { return; } break; } case AuthenticatorState.WindowsHelloUnsupport: { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_WarningTitle"), Content = Globalization.GetString("QueueDialog_WinHelloDisable_Content"), PrimaryButtonText = Globalization.GetString("Common_Dialog_UsePassword"), CloseButtonText = Globalization.GetString("Common_Dialog_GoBack") }; ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"] = false; if ((await Dialog.ShowAsync()) == ContentDialogResult.Primary) { if (!await EnterByPassword()) { return; } } else { GoBack(); return; } break; } } } else { if (!await EnterByPassword()) { return; } } } } else { try { LoadingText.Text = Globalization.GetString("Progress_Tip_CheckingLicense"); CancelButton.Visibility = Visibility.Collapsed; LoadingControl.IsLoading = true; if (await MSStoreHelper.Current.CheckPurchaseStatusAsync()) { await Task.Delay(500); } else { SecureAreaIntroDialog IntroDialog = new SecureAreaIntroDialog(); if ((await IntroDialog.ShowAsync()) == ContentDialogResult.Primary) { StorePurchaseStatus Status = await MSStoreHelper.Current.PurchaseAsync(); if (Status == StorePurchaseStatus.AlreadyPurchased || Status == StorePurchaseStatus.Succeeded) { QueueContentDialog SuccessDialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_WarningTitle"), Content = Globalization.GetString("QueueDialog_SecureAreaUnlock_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await SuccessDialog.ShowAsync(); } else { GoBack(); return; } } else { GoBack(); return; } } } finally { await Task.Delay(500); LoadingControl.IsLoading = false; } SecureAreaWelcomeDialog Dialog = new SecureAreaWelcomeDialog(); if ((await Dialog.ShowAsync()) == ContentDialogResult.Primary) { AESKeySize = Dialog.AESKeySize; UnlockPassword = Dialog.Password; ApplicationData.Current.LocalSettings.Values["SecureAreaAESKeySize"] = Dialog.AESKeySize; ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"] = Dialog.IsEnableWindowsHello; ApplicationData.Current.LocalSettings.Values["IsFirstEnterSecureArea"] = false; } else { if (Dialog.IsEnableWindowsHello) { await WindowsHelloAuthenticator.DeleteUserAsync(); } GoBack(); return; } } CoreWindow.GetForCurrentThread().KeyDown += SecureArea_KeyDown; WholeArea.Visibility = Visibility.Visible; SelectionExtention = new ListViewBaseSelectionExtention(SecureGridView, DrawRectangle); await LoadSecureFile(); } catch (Exception ex) { LogTracer.LeadToBlueScreen(ex); } }
private async void PickWebLogo(object sender, RoutedEventArgs e) { try { FileOpenPicker Picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.ComputerFolder, ViewMode = PickerViewMode.List }; Picker.FileTypeFilter.Add(".ico"); Picker.FileTypeFilter.Add(".png"); Picker.FileTypeFilter.Add(".jpg"); Picker.FileTypeFilter.Add(".bmp"); if (await Picker.PickSingleFileAsync() is StorageFile ExecuteFile) { StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); if (await ExecuteFile.OpenReadAsync() is IRandomAccessStream LogoStream) { try { BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(LogoStream); LogoStream.Seek(0); using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await LogoStream.AsStreamForRead().CopyToAsync(FileStream); } } finally { LogoStream.Dispose(); } } else { Uri PageUri = AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png"); StorageFile PageFile = await StorageFile.GetFileFromApplicationUriAsync(PageUri); using (IRandomAccessStream PageStream = await PageFile.OpenAsync(FileAccessMode.Read)) { BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(PageStream); PageStream.Seek(0); using (Stream TransformStream = PageStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } ImageFile = FileThumbnail; } } catch (Exception ex) { LogTracer.Log(ex); FailureTips.IsOpen = true; } }
private async void UWPPickerTip_ActionButtonClick(Microsoft.UI.Xaml.Controls.TeachingTip sender, object args) { try { if (PackageListView.SelectedItem is InstalledApplication Package) { sender.IsOpen = false; PickAppFlyout.Hide(); DisplayName.Text = Package.AppName; Protocol.Text = Package.AppFamilyName; Icon.Source = Package.Logo; StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); if (Package.CreateStreamFromLogoData() is Stream LogoStream) { try { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(LogoStream.AsRandomAccessStream()); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream ResizeBitmapStream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ResizeBitmapStream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Source = new BitmapImage(); Icon.Source = Source; await Source.SetSourceAsync(ResizeBitmapStream); ResizeBitmapStream.Seek(0); using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await ResizeBitmapStream.AsStreamForRead().CopyToAsync(FileStream); } } } finally { LogoStream.Dispose(); } } else { Uri PageUri = AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png"); StorageFile PageFile = await StorageFile.GetFileFromApplicationUriAsync(PageUri); using (IRandomAccessStream PageStream = await PageFile.OpenAsync(FileAccessMode.Read)) { BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(PageStream); PageStream.Seek(0); using (Stream TransformStream = PageStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } ImageFile = FileThumbnail; } } catch (Exception ex) { LogTracer.Log(ex); FailureTips.IsOpen = true; } }
private async Task Initialize(SearchCategory Category, bool IngoreCase, bool IncludeRegex, bool GlobleSearch, uint MaxCount) { HasItem.Visibility = Visibility.Collapsed; LoadingControl.IsLoading = true; try { Cancellation = new CancellationTokenSource(); if (WeakToFileControl.TryGetTarget(out FileControl Control)) { string SearchTarget = Control.GlobeSearch.Text; FileSystemStorageFolder CurrentFolder = Control.CurrentPresenter.CurrentFolder; List <FileSystemStorageItemBase> SearchItems = null; switch (Category) { case SearchCategory.BuiltInEngine_Deep: { SearchItems = await CurrentFolder.SearchAsync(SearchTarget, true, SettingControl.IsDisplayHiddenItem, IncludeRegex, IngoreCase, Cancellation.Token).ToListAsync(); break; } case SearchCategory.BuiltInEngine_Shallow: { SearchItems = await CurrentFolder.SearchAsync(SearchTarget, false, SettingControl.IsDisplayHiddenItem, IncludeRegex, IngoreCase, Cancellation.Token).ToListAsync(); break; } case SearchCategory.EverythingEngine: { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { SearchItems = await Exclusive.Controller.SearchByEverythingAsync(GlobleSearch?string.Empty : CurrentFolder.Path, SearchTarget, IncludeRegex, IngoreCase, MaxCount).ConfigureAwait(true); } break; } } await Task.Delay(500).ConfigureAwait(true); LoadingControl.IsLoading = false; await Task.Delay(300).ConfigureAwait(true); if (Cancellation.IsCancellationRequested) { HasItem.Visibility = Visibility.Visible; SearchResultList.Visibility = Visibility.Collapsed; } else { if (SearchItems.Count == 0) { HasItem.Visibility = Visibility.Visible; } else { foreach (FileSystemStorageItemBase Item in SortCollectionGenerator.Current.GetSortedCollection(SearchItems)) { SearchResult.Add(Item); } } } } } catch (Exception ex) { LogTracer.Log(ex, $"An error was threw in {nameof(Initialize)}"); } finally { Cancellation.Dispose(); Cancellation = null; } }
private void App_UnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e) { LogTracer.LeadToBlueScreen(e.Exception); e.Handled = true; }
private async Task Initialize(SearchOptions Options) { HasItem.Visibility = Visibility.Collapsed; try { Cancellation = new CancellationTokenSource(); SearchStatus.Text = Globalization.GetString("SearchProcessingText"); SearchStatusBar.Visibility = Visibility.Visible; switch (Options.EngineCategory) { case SearchCategory.BuiltInEngine: { await foreach (FileSystemStorageItemBase Item in Options.SearchFolder.SearchAsync(Options.SearchText, Options.DeepSearch, SettingControl.IsDisplayHiddenItem, SettingControl.IsDisplayProtectedSystemItems, Options.UseRegexExpression, Options.IgnoreCase, Cancellation.Token)) { if (Cancellation.IsCancellationRequested) { HasItem.Visibility = Visibility.Visible; break; } else { SearchResult.Insert(SortCollectionGenerator.SearchInsertLocation(SearchResult, Item, SortTarget.Name, SortDirection.Ascending), Item); } } if (SearchResult.Count == 0) { HasItem.Visibility = Visibility.Visible; } break; } case SearchCategory.EverythingEngine: { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { IReadOnlyList <FileSystemStorageItemBase> SearchItems = await Exclusive.Controller.SearchByEverythingAsync(Options.DeepSearch?string.Empty : Options.SearchFolder.Path, Options.SearchText, Options.UseRegexExpression, Options.IgnoreCase, Options.NumLimit); if (SearchItems.Count == 0) { HasItem.Visibility = Visibility.Visible; } else { foreach (FileSystemStorageItemBase Item in SortCollectionGenerator.GetSortedCollection(SearchItems, SortTarget.Name, SortDirection.Ascending)) { SearchResult.Add(Item); } } } break; } } SearchStatus.Text = Globalization.GetString("SearchCompletedText"); SearchStatusBar.Visibility = Visibility.Collapsed; } catch (Exception ex) { LogTracer.Log(ex, $"An error was threw in {nameof(Initialize)}"); } finally { Cancellation.Dispose(); Cancellation = null; } }
private async Task LaunchSelectedItem(FileSystemStorageItemBase Item) { try { switch (Item) { case FileSystemStorageFile File: { if (!await FileSystemStorageItemBase.CheckExistAsync(File.Path)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LocateFileFailure_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); return; } switch (File.Type.ToLower()) { case ".exe": case ".bat": case ".msi": { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { if (!await Exclusive.Controller.RunAsync(File.Path, Path.GetDirectoryName(File.Path))) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LaunchFailed_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); } } break; } case ".msc": { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { if (!await Exclusive.Controller.RunAsync("powershell.exe", string.Empty, WindowState.Normal, false, true, false, "-Command", File.Path)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LaunchFailed_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); } } break; } case ".lnk": { if (File is LinkStorageFile LinkItem) { if (LinkItem.LinkType == ShellLinkType.Normal) { switch (await FileSystemStorageItemBase.OpenAsync(LinkItem.LinkTargetPath)) { case FileSystemStorageFolder: { if (WeakToFileControl.TryGetTarget(out FileControl Control)) { Frame.GoBack(); await Control.CurrentPresenter.DisplayItemsInFolder(LinkItem.LinkTargetPath); await JumpListController.Current.AddItemAsync(JumpListGroup.Recent, LinkItem.LinkTargetPath); if (Control.CurrentPresenter.FileCollection.FirstOrDefault((SItem) => SItem == LinkItem) is FileSystemStorageItemBase Target) { Control.CurrentPresenter.ItemPresenter.ScrollIntoView(Target); Control.CurrentPresenter.SelectedItem = Target; } } break; } case FileSystemStorageFile: { await LinkItem.LaunchAsync(); break; } } } else { await LinkItem.LaunchAsync(); } } break; } case ".url": { if (File is UrlStorageFile UrlItem) { await UrlItem.LaunchAsync(); } break; } default: { string AdminExecutablePath = await SQLite.Current.GetDefaultProgramPickerRecordAsync(File.Type); if (string.IsNullOrEmpty(AdminExecutablePath) || AdminExecutablePath == Package.Current.Id.FamilyName) { if (!TryOpenInternally(File)) { if (await File.GetStorageItemAsync() is StorageFile SFile) { if (!await Launcher.LaunchFileAsync(SFile)) { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { if (!await Exclusive.Controller.RunAsync(File.Path)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LaunchFailed_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); } } } } else { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { if (!await Exclusive.Controller.RunAsync(File.Path)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LaunchFailed_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); } } } } } else { if (Path.IsPathRooted(AdminExecutablePath)) { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { if (!await Exclusive.Controller.RunAsync(AdminExecutablePath, Path.GetDirectoryName(AdminExecutablePath), Parameters: File.Path)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LaunchFailed_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); } } } else { if ((await Launcher.FindFileHandlersAsync(File.Type)).FirstOrDefault((Item) => Item.PackageFamilyName == AdminExecutablePath) is AppInfo Info) { if (await File.GetStorageItemAsync() is StorageFile InnerFile) { if (!await Launcher.LaunchFileAsync(InnerFile, new LauncherOptions { TargetApplicationPackageFamilyName = Info.PackageFamilyName, DisplayApplicationPicker = false })) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LaunchFailed_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); } } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_UnableAccessFile_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); } } } } break; } } break; } case FileSystemStorageFolder Folder: { if (await FileSystemStorageItemBase.CheckExistAsync(Folder.Path)) { if (WeakToFileControl.TryGetTarget(out FileControl Control)) { Frame.GoBack(); await Control.CurrentPresenter.DisplayItemsInFolder(Folder); await JumpListController.Current.AddItemAsync(JumpListGroup.Recent, Folder.Path); if (Control.CurrentPresenter.FileCollection.FirstOrDefault((SItem) => SItem == Folder) is FileSystemStorageItemBase Target) { Control.CurrentPresenter.ItemPresenter.ScrollIntoView(Target); Control.CurrentPresenter.SelectedItem = Target; } } } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LocateFolderFailure_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); } break; } } } catch (Exception ex) { LogTracer.Log(ex, $"An error was threw in {nameof(LaunchSelectedItem)}"); QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LocateFolderFailure_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync(); } }
private async Task InitializeAsync() { try { using (IRandomAccessStream Stream = await MediaFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read)) { Source = MediaSource.CreateFromStream(Stream, MIMEDictionary[MediaFile.Type.ToLower()]); MediaPlaybackItem Item = new MediaPlaybackItem(Source); switch (MediaFile.Type.ToLower()) { case ".mp3": case ".flac": case ".wma": case ".m4a": { MusicCover.Visibility = Visibility.Visible; MediaItemDisplayProperties Props = Item.GetDisplayProperties(); Props.Type = Windows.Media.MediaPlaybackType.Music; Props.MusicProperties.Title = MediaFile.DisplayName; Props.MusicProperties.AlbumArtist = await GetArtistAsync(); Item.ApplyDisplayProperties(Props); if (await GetMusicCoverAsync() is BitmapImage Thumbnail) { Cover.Source = Thumbnail; Cover.Visibility = Visibility.Visible; } else { Cover.Visibility = Visibility.Collapsed; } Display.Text = $"{Globalization.GetString("Media_Tip_Text")} {MediaFile.DisplayName}"; MVControl.Source = Item; break; } default: { MusicCover.Visibility = Visibility.Collapsed; MediaItemDisplayProperties Props = Item.GetDisplayProperties(); Props.Type = Windows.Media.MediaPlaybackType.Video; Props.VideoProperties.Title = MediaFile.DisplayName; Item.ApplyDisplayProperties(Props); MVControl.Source = Item; break; } } } } catch (Exception ex) { LogTracer.Log(ex, "Could not load media because an exception was threw"); QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_CouldNotLoadMedia_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); Frame.GoBack(); } }
public async void Refresh_Click(object sender, RoutedEventArgs e) { if (Interlocked.Exchange(ref LockResource, 1) == 0) { try { CommonAccessCollection.HardDeviceList.Clear(); foreach (DriveInfo Drive in DriveInfo.GetDrives().Where((Drives) => Drives.DriveType == DriveType.Fixed || Drives.DriveType == DriveType.Removable) .Where((NewItem) => CommonAccessCollection.HardDeviceList.All((Item) => Item.Folder.Path != NewItem.RootDirectory.FullName))) { try { StorageFolder Device = await StorageFolder.GetFolderFromPathAsync(Drive.RootDirectory.FullName); BasicProperties Properties = await Device.GetBasicPropertiesAsync(); IDictionary <string, object> PropertiesRetrieve = await Properties.RetrievePropertiesAsync(new string[] { "System.Capacity", "System.FreeSpace", "System.Volume.FileSystem", "System.Volume.BitLockerProtection" }); CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(Device, await Device.GetThumbnailBitmapAsync().ConfigureAwait(true), PropertiesRetrieve, Drive.DriveType)); } catch (Exception ex) { LogTracer.Log(ex, $"Hide the device \"{Drive.RootDirectory.FullName}\" for error"); } } foreach (DeviceInformation Device in await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector())) { try { StorageFolder DeviceFolder = StorageDevice.FromId(Device.Id); if (CommonAccessCollection.HardDeviceList.All((Item) => (string.IsNullOrEmpty(Item.Folder.Path) || string.IsNullOrEmpty(DeviceFolder.Path)) ? Item.Folder.Name != DeviceFolder.Name : Item.Folder.Path != DeviceFolder.Path)) { BasicProperties Properties = await DeviceFolder.GetBasicPropertiesAsync(); IDictionary <string, object> PropertiesRetrieve = await Properties.RetrievePropertiesAsync(new string[] { "System.Capacity", "System.FreeSpace", "System.Volume.FileSystem", "System.Volume.BitLockerProtection" }); if (PropertiesRetrieve["System.Capacity"] is ulong && PropertiesRetrieve["System.FreeSpace"] is ulong) { CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(DeviceFolder, await DeviceFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), PropertiesRetrieve, DriveType.Removable)); } else { IReadOnlyList <IStorageItem> InnerItemList = await DeviceFolder.GetItemsAsync(0, 2); if (InnerItemList.Count == 1 && InnerItemList[0] is StorageFolder InnerFolder) { BasicProperties InnerProperties = await InnerFolder.GetBasicPropertiesAsync(); IDictionary <string, object> InnerPropertiesRetrieve = await InnerProperties.RetrievePropertiesAsync(new string[] { "System.Capacity", "System.FreeSpace", "System.Volume.FileSystem", "System.Volume.BitLockerProtection" }); if (InnerPropertiesRetrieve["System.Capacity"] is ulong && InnerPropertiesRetrieve["System.FreeSpace"] is ulong) { CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(DeviceFolder, await DeviceFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), InnerPropertiesRetrieve, DriveType.Removable)); } else { CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(DeviceFolder, await DeviceFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), PropertiesRetrieve, DriveType.Removable)); } } else { CommonAccessCollection.HardDeviceList.Add(new HardDeviceInfo(DeviceFolder, await DeviceFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), PropertiesRetrieve, DriveType.Removable)); } } } } catch (Exception ex) { LogTracer.Log(ex, $"Hide the device \"{Device.Name}\" for error"); } } } finally { _ = Interlocked.Exchange(ref LockResource, 0); } } }
private async void SecureArea_Loaded(object sender, RoutedEventArgs e) { try { if (ApplicationData.Current.LocalSettings.Values.ContainsKey("IsFirstEnterSecureArea")) { UnlockPassword = CredentialProtector.GetPasswordFromProtector("SecureAreaPrimaryPassword"); FileEncryptionAesKey = KeyGenerator.GetMD5FromKey(UnlockPassword, 16); AESKeySize = Convert.ToInt32(ApplicationData.Current.LocalSettings.Values["SecureAreaAESKeySize"]); if (!(ApplicationData.Current.LocalSettings.Values["SecureAreaLockMode"] is string LockMode) || LockMode != nameof(CloseLockMode) || IsNewStart) { if (Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"])) { RETRY: switch (await WindowsHelloAuthenticator.VerifyUserAsync().ConfigureAwait(true)) { case AuthenticatorState.VerifyPassed: { break; } case AuthenticatorState.UnknownError: case AuthenticatorState.VerifyFailed: { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_WinHelloAuthFail_Content"), PrimaryButtonText = Globalization.GetString("Common_Dialog_TryAgain"), SecondaryButtonText = Globalization.GetString("Common_Dialog_UsePassword"), CloseButtonText = Globalization.GetString("Common_Dialog_GoBack") }; ContentDialogResult Result = await Dialog.ShowAsync().ConfigureAwait(true); if (Result == ContentDialogResult.Primary) { goto RETRY; } else if (Result == ContentDialogResult.Secondary) { if (!await EnterByPassword().ConfigureAwait(true)) { return; } } else { GoBack(); return; } break; } case AuthenticatorState.UserNotRegistered: case AuthenticatorState.CredentialNotFound: { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_WinHelloCredentialLost_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"] = false; if (!await EnterByPassword().ConfigureAwait(true)) { return; } break; } case AuthenticatorState.WindowsHelloUnsupport: { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_WarningTitle"), Content = Globalization.GetString("QueueDialog_WinHelloDisable_Content"), PrimaryButtonText = Globalization.GetString("Common_Dialog_UsePassword"), CloseButtonText = Globalization.GetString("Common_Dialog_GoBack") }; ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"] = false; if ((await Dialog.ShowAsync().ConfigureAwait(true)) == ContentDialogResult.Primary) { if (!await EnterByPassword().ConfigureAwait(true)) { return; } } else { GoBack(); return; } break; } } } else { if (!await EnterByPassword().ConfigureAwait(true)) { return; } } } } else { if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("SecureAreaUsePermission")) { try { LoadingText.Text = Globalization.GetString("Progress_Tip_CheckingLicense"); CancelButton.Visibility = Visibility.Collapsed; LoadingControl.IsLoading = true; MainPage.ThisPage.IsAnyTaskRunning = true; if (await CheckPurchaseStatusAsync().ConfigureAwait(true)) { if (MainPage.ThisPage.Nav.CurrentSourcePageType.Name != nameof(SecureArea)) { GoBack(); return; } ApplicationData.Current.LocalSettings.Values["SecureAreaUsePermission"] = true; await Task.Delay(500).ConfigureAwait(true); } else { if (MainPage.ThisPage.Nav.CurrentSourcePageType.Name != nameof(SecureArea)) { GoBack(); return; } SecureAreaIntroDialog IntroDialog = new SecureAreaIntroDialog(); if ((await IntroDialog.ShowAsync().ConfigureAwait(true)) == ContentDialogResult.Primary) { if (await PurchaseAsync().ConfigureAwait(true)) { ApplicationData.Current.LocalSettings.Values["SecureAreaUsePermission"] = true; QueueContentDialog SuccessDialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_WarningTitle"), Content = Globalization.GetString("QueueDialog_SecureAreaUnlock_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await SuccessDialog.ShowAsync().ConfigureAwait(true); } else { GoBack(); return; } } else { GoBack(); return; } } } catch (NetworkException) { QueueContentDialog ErrorDialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_SecureAreaNetworkUnavailable_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_GoBack") }; _ = await ErrorDialog.ShowAsync().ConfigureAwait(true); GoBack(); return; } finally { await Task.Delay(500).ConfigureAwait(true); LoadingControl.IsLoading = false; MainPage.ThisPage.IsAnyTaskRunning = false; } } SecureAreaWelcomeDialog Dialog = new SecureAreaWelcomeDialog(); if ((await Dialog.ShowAsync().ConfigureAwait(true)) == ContentDialogResult.Primary) { AESKeySize = Dialog.AESKeySize; UnlockPassword = Dialog.Password; FileEncryptionAesKey = KeyGenerator.GetMD5FromKey(UnlockPassword, 16); CredentialProtector.RequestProtectPassword("SecureAreaPrimaryPassword", UnlockPassword); ApplicationData.Current.LocalSettings.Values["SecureAreaAESKeySize"] = Dialog.AESKeySize; ApplicationData.Current.LocalSettings.Values["SecureAreaEnableWindowsHello"] = Dialog.IsEnableWindowsHello; ApplicationData.Current.LocalSettings.Values["IsFirstEnterSecureArea"] = false; } else { if (Dialog.IsEnableWindowsHello) { await WindowsHelloAuthenticator.DeleteUserAsync().ConfigureAwait(true); } GoBack(); return; } } await StartLoadFile().ConfigureAwait(false); } catch (Exception ex) { LogTracer.LeadToBlueScreen(ex); } }
private async void Grid_Drop(object sender, DragEventArgs e) { IReadOnlyList <IStorageItem> Items = await e.DataView.GetStorageItemsAsync(); if (Items.Any((Item) => Item.IsOfType(StorageItemTypes.Folder))) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_TipTitle"), Content = Globalization.GetString("QueueDialog_SecureAreaImportFiliter_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); } if (Items.Any((Item) => Item.IsOfType(StorageItemTypes.File))) { ActivateLoading(true, true); Cancellation = new CancellationTokenSource(); try { foreach (StorageFile Item in Items.OfType <StorageFile>()) { if ((await Item.EncryptAsync(SecureFolder, FileEncryptionAesKey, AESKeySize, Cancellation.Token).ConfigureAwait(true)) is StorageFile EncryptedFile) { SecureCollection.Add(new FileSystemStorageItemBase(EncryptedFile, await EncryptedFile.GetSizeRawDataAsync().ConfigureAwait(true), new BitmapImage(new Uri("ms-appx:///Assets/LockFile.png")), await EncryptedFile.GetModifiedTimeAsync().ConfigureAwait(true))); try { await Item.DeleteAsync(StorageDeleteOption.Default); } catch { } } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_EncryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); break; } } } catch (TaskCanceledException cancelException) { LogTracer.Log(cancelException, "Import items to SecureArea have been cancelled"); } catch (Exception ex) { LogTracer.Log(ex, "An error was threw when importing file"); } finally { Cancellation.Dispose(); Cancellation = null; await Task.Delay(1500).ConfigureAwait(true); ActivateLoading(false); } } }
private async void AddFile_Click(object sender, RoutedEventArgs e) { FileOpenPicker Picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.ComputerFolder, ViewMode = PickerViewMode.Thumbnail }; Picker.FileTypeFilter.Add("*"); IReadOnlyList <StorageFile> FileList = await Picker.PickMultipleFilesAsync(); if (FileList.Count > 0) { ActivateLoading(true, true); Cancellation = new CancellationTokenSource(); try { foreach (StorageFile File in FileList) { if ((await File.EncryptAsync(SecureFolder, FileEncryptionAesKey, AESKeySize, Cancellation.Token).ConfigureAwait(true)) is StorageFile EncryptedFile) { SecureCollection.Add(new FileSystemStorageItemBase(EncryptedFile, await EncryptedFile.GetSizeRawDataAsync().ConfigureAwait(true), new BitmapImage(new Uri("ms-appx:///Assets/LockFile.png")), await EncryptedFile.GetModifiedTimeAsync().ConfigureAwait(true))); try { await File.DeleteAsync(StorageDeleteOption.Default); } catch { } } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_EncryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); break; } } } catch (TaskCanceledException cancelException) { LogTracer.Log(cancelException, "Import items to SecureArea have been cancelled"); } catch (Exception ex) { LogTracer.Log(ex, "An error was threw when importing file"); } finally { Cancellation.Dispose(); Cancellation = null; await Task.Delay(1500).ConfigureAwait(true); ActivateLoading(false); } } }
public FooLogger(Stream stream, byte[] buffer, LogTracer tracer = null) : base(LoggerId.Foo, stream, buffer, tracer) { }
private async void Grid_Drop(object sender, DragEventArgs e) { if (e.DataView.Contains(StandardDataFormats.StorageItems)) { IReadOnlyList <IStorageItem> Items = await e.DataView.GetStorageItemsAsync(); if (Items.Any((Item) => Item.IsOfType(StorageItemTypes.Folder))) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_TipTitle"), Content = Globalization.GetString("QueueDialog_SecureAreaImportFiliter_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); } if (Items.Any((Item) => Item.IsOfType(StorageItemTypes.File))) { ActivateLoading(true, true); Cancellation = new CancellationTokenSource(); try { foreach (string OriginFilePath in Items.Select((Item) => Item.Path)) { if (FileSystemStorageItemBase.Open(OriginFilePath, ItemFilters.File) is FileSystemStorageItemBase Item) { if (await Item.EncryptAsync(SecureFolder.Path, EncryptionAESKey, AESKeySize, Cancellation.Token).ConfigureAwait(true) is SecureAreaStorageItem EncryptedFile) { SecureCollection.Add(EncryptedFile); if (!Item.PermanentDelete()) { LogTracer.Log(new Win32Exception(Marshal.GetLastWin32Error()), "Delete origin file failed after importing to SecureArea"); } } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_EncryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); } } } } catch (TaskCanceledException cancelException) { LogTracer.Log(cancelException, "Import items to SecureArea have been cancelled"); } catch (Exception ex) { LogTracer.Log(ex, "An error was threw when importing file"); QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_EncryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); } finally { Cancellation.Dispose(); Cancellation = null; await Task.Delay(1000).ConfigureAwait(true); ActivateLoading(false); } } } }
private async void ProgramPickerDialog_Loading(FrameworkElement sender, object args) { LoadingText.Text = Globalization.GetString("Progress_Tip_Loading"); LoadingText.Visibility = Visibility.Visible; WholeArea.Visibility = Visibility.Collapsed; List <ProgramPickerItem> RecommandList = new List <ProgramPickerItem>(); try { List <AssociationPackage> AssocList = await FullTrustProcessController.Current.GetAssociateFromPathAsync(OpenFile.Path).ConfigureAwait(true); List <AppInfo> AppInfoList = (await Launcher.FindFileHandlersAsync(OpenFile.Type)).ToList(); await SQLite.Current.UpdateProgramPickerRecordAsync(OpenFile.Type, AssocList.Concat(AppInfoList.Select((Info) => new AssociationPackage(OpenFile.Type, Info.PackageFamilyName, true)))).ConfigureAwait(true); foreach (AppInfo Info in AppInfoList) { try { using (IRandomAccessStreamWithContentType LogoStream = await Info.DisplayInfo.GetLogo(new Windows.Foundation.Size(128, 128)).OpenReadAsync()) { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(LogoStream); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream Stream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Stream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Image = new BitmapImage(); await Image.SetSourceAsync(Stream); RecommandList.Add(new ProgramPickerItem(Image, Info.DisplayInfo.DisplayName, Info.DisplayInfo.Description, Info.PackageFamilyName)); } } } catch (Exception ex) { LogTracer.Log(ex, "An exception was threw when getting or processing App Logo"); } } } catch (Exception ex) { LogTracer.Log(ex, "An exception was threw when fetching association data"); } foreach (AssociationPackage Package in await SQLite.Current.GetProgramPickerRecordAsync(OpenFile.Type, false).ConfigureAwait(true)) { try { if (WIN_Native_API.CheckExist(Package.ExecutablePath)) { StorageFile ExecuteFile = await StorageFile.GetFileFromPathAsync(Package.ExecutablePath); IDictionary <string, object> PropertiesDictionary = await ExecuteFile.Properties.RetrievePropertiesAsync(new string[] { "System.FileDescription" }); string ExtraAppName = string.Empty; if (PropertiesDictionary.TryGetValue("System.FileDescription", out object DescriptionRaw)) { ExtraAppName = Convert.ToString(DescriptionRaw); } if (await ExecuteFile.GetThumbnailRawStreamAsync().ConfigureAwait(true) is IRandomAccessStream ThumbnailStream) { using (ThumbnailStream) { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(ThumbnailStream); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream ResizeBitmapStream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ResizeBitmapStream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage ThumbnailBitmap = new BitmapImage(); await ThumbnailBitmap.SetSourceAsync(ResizeBitmapStream); if (Package.IsRecommanded) { RecommandList.Add(new ProgramPickerItem(ThumbnailBitmap, string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path)); } else { NotRecommandList.Add(new ProgramPickerItem(ThumbnailBitmap, string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path)); } } } } else { if (Package.IsRecommanded) { RecommandList.Add(new ProgramPickerItem(new BitmapImage(AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png")), string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path)); } else { NotRecommandList.Add(new ProgramPickerItem(new BitmapImage(AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png")), string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path)); } } } else { await SQLite.Current.DeleteProgramPickerRecordAsync(Package).ConfigureAwait(true); } } catch (Exception ex) { LogTracer.Log(ex, "An exception was threw trying add to ApplicationList"); } } string AdminExecutablePath = await SQLite.Current.GetDefaultProgramPickerRecordAsync(OpenFile.Type).ConfigureAwait(true); if (!string.IsNullOrEmpty(AdminExecutablePath)) { if (RecommandList.FirstOrDefault((Item) => Item.Path.Equals(AdminExecutablePath, StringComparison.OrdinalIgnoreCase)) is ProgramPickerItem RecommandItem) { CurrentUseProgramList.Items.Add(RecommandItem); CurrentUseProgramList.SelectedIndex = 0; RecommandList.Remove(RecommandItem); } else if (NotRecommandList.FirstOrDefault((Item) => Item.Path.Equals(AdminExecutablePath, StringComparison.OrdinalIgnoreCase)) is ProgramPickerItem NotRecommandItem) { CurrentUseProgramList.Items.Add(NotRecommandItem); CurrentUseProgramList.SelectedIndex = 0; NotRecommandList.Remove(NotRecommandItem); } } if (CurrentUseProgramList.Items.Count == 0) { switch (OpenFile.Type.ToLower()) { case ".jpg": case ".png": case ".bmp": case ".heic": case ".gif": case ".tiff": case ".mkv": case ".mp4": case ".mp3": case ".flac": case ".wma": case ".wmv": case ".m4a": case ".mov": case ".alac": case ".txt": case ".pdf": case ".exe": { Area1.Visibility = Visibility.Visible; CurrentUseProgramList.Visibility = Visibility.Visible; Title1.Text = Globalization.GetString("ProgramPicker_Dialog_Title_1"); Title2.Text = Globalization.GetString("ProgramPicker_Dialog_Title_2"); CurrentUseProgramList.Items.Add(new ProgramPickerItem(new BitmapImage(new Uri("ms-appx:///Assets/RX-icon.png")), Globalization.GetString("ProgramPicker_Dialog_BuiltInViewer"), Globalization.GetString("ProgramPicker_Dialog_BuiltInViewer_Description"), Package.Current.Id.FamilyName)); CurrentUseProgramList.SelectedIndex = 0; break; } default: { Area1.Visibility = Visibility.Collapsed; CurrentUseProgramList.Visibility = Visibility.Collapsed; Title2.Text = Globalization.GetString("ProgramPicker_Dialog_Title_2"); break; } } } else { Area1.Visibility = Visibility.Visible; CurrentUseProgramList.Visibility = Visibility.Visible; Title1.Text = Globalization.GetString("ProgramPicker_Dialog_Title_1"); Title2.Text = Globalization.GetString("ProgramPicker_Dialog_Title_2"); switch (OpenFile.Type.ToLower()) { case ".jpg": case ".png": case ".bmp": case ".heic": case ".gif": case ".tiff": case ".mkv": case ".mp4": case ".mp3": case ".flac": case ".wma": case ".wmv": case ".m4a": case ".mov": case ".alac": case ".txt": case ".pdf": case ".exe": { ProgramCollection.Add(new ProgramPickerItem(new BitmapImage(new Uri("ms-appx:///Assets/RX-icon.png")), Globalization.GetString("ProgramPicker_Dialog_BuiltInViewer"), Globalization.GetString("ProgramPicker_Dialog_BuiltInViewer_Description"), Package.Current.Id.FamilyName)); break; } } } if (RecommandList.Count == 0) { ShowMore.Visibility = Visibility.Collapsed; foreach (ProgramPickerItem Item in NotRecommandList) { ProgramCollection.Add(Item); } OtherProgramList.MaxHeight = 300; } else { foreach (ProgramPickerItem Item in RecommandList) { ProgramCollection.Add(Item); } } if (CurrentUseProgramList.SelectedIndex == -1) { OtherProgramList.SelectedIndex = 0; } LoadingText.Visibility = Visibility.Collapsed; WholeArea.Visibility = Visibility.Visible; }
private async void ExportFile_Click(object sender, RoutedEventArgs e) { FolderPicker Picker = new FolderPicker { SuggestedStartLocation = PickerLocationId.Desktop, ViewMode = PickerViewMode.Thumbnail }; Picker.FileTypeFilter.Add("*"); if ((await Picker.PickSingleFolderAsync()) is StorageFolder Folder) { Cancellation = new CancellationTokenSource(); try { ActivateLoading(true, false); foreach (SecureAreaStorageItem Item in SecureGridView.SelectedItems.ToArray()) { if (await Item.DecryptAsync(Folder.Path, EncryptionAESKey, Cancellation.Token).ConfigureAwait(true) is FileSystemStorageItemBase) { SecureCollection.Remove(Item); if (!Item.PermanentDelete()) { LogTracer.Log(new Win32Exception(Marshal.GetLastWin32Error()), "Delete encrypted file failed after exporting to SecureArea"); } } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_DecryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); } } _ = await Launcher.LaunchFolderAsync(Folder); } catch (PasswordErrorException) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_DecryptPasswordError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); } catch (FileDamagedException) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_FileDamageError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); } catch (TaskCanceledException cancelException) { LogTracer.Log(cancelException, "Import items to SecureArea have been cancelled"); } catch (Exception ex) { LogTracer.Log(ex); QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_DecryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); } finally { Cancellation.Dispose(); Cancellation = null; await Task.Delay(1000).ConfigureAwait(true); ActivateLoading(false); } } }
private async Task Initialize(SearchCategory Category, bool IngoreCase, bool IncludeRegex, bool GlobleSearch, uint MaxCount) { HasItem.Visibility = Visibility.Collapsed; try { Cancellation = new CancellationTokenSource(); if (WeakToFileControl.TryGetTarget(out FileControl Control)) { string SearchTarget = Control.GlobeSearch.Text; FileSystemStorageFolder CurrentFolder = Control.CurrentPresenter.CurrentFolder; SearchStatus.Text = Globalization.GetString("SearchProcessingText"); SearchStatusBar.Visibility = Visibility.Visible; switch (Category) { case SearchCategory.BuiltInEngine_Deep: case SearchCategory.BuiltInEngine_Shallow: { await foreach (FileSystemStorageItemBase Item in CurrentFolder.SearchAsync(SearchTarget, Category == SearchCategory.BuiltInEngine_Deep, SettingControl.IsDisplayHiddenItem, SettingControl.IsDisplayProtectedSystemItems, IncludeRegex, IngoreCase, Cancellation.Token)) { if (Cancellation.IsCancellationRequested) { HasItem.Visibility = Visibility.Visible; break; } else { SearchResult.Insert(SortCollectionGenerator.SearchInsertLocation(SearchResult, Item, SortTarget.Name, SortDirection.Ascending), Item); } } if (SearchResult.Count == 0) { HasItem.Visibility = Visibility.Visible; } break; } case SearchCategory.EverythingEngine: { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { IReadOnlyList <FileSystemStorageItemBase> SearchItems = await Exclusive.Controller.SearchByEverythingAsync(GlobleSearch?string.Empty : CurrentFolder.Path, SearchTarget, IncludeRegex, IngoreCase, MaxCount); if (SearchItems.Count == 0) { HasItem.Visibility = Visibility.Visible; } else { foreach (FileSystemStorageItemBase Item in SortCollectionGenerator.GetSortedCollection(SearchItems, SortTarget.Name, SortDirection.Ascending)) { SearchResult.Add(Item); } } } break; } } SearchStatus.Text = Globalization.GetString("SearchCompletedText"); SearchStatusBar.Visibility = Visibility.Collapsed; } } catch (Exception ex) { LogTracer.Log(ex, $"An error was threw in {nameof(Initialize)}"); } finally { Cancellation.Dispose(); Cancellation = null; } }
private async Task Initialize() { try { ExitLocker = new ManualResetEvent(false); Cancellation = new CancellationTokenSource(); LoadQueue = new Queue <int>(); Behavior.Attach(Flip); if (await FileSystemStorageItemBase.OpenAsync(Path.GetDirectoryName(SelectedPhotoFile.Path)) is FileSystemStorageFolder Item) { FileSystemStorageFile[] PictureFileList = (await Item.GetChildItemsAsync(SettingControl.IsDisplayHiddenItem, SettingControl.IsDisplayProtectedSystemItems, Filter: ItemFilters.File)).OfType <FileSystemStorageFile>().Where((Item) => Item.Type.Equals(".png", StringComparison.OrdinalIgnoreCase) || Item.Type.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || Item.Type.Equals(".bmp", StringComparison.OrdinalIgnoreCase)).ToArray(); if (PictureFileList.Length == 0) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("Queue_Dialog_ImageReadError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_GoBack") }; _ = await Dialog.ShowAsync(); Frame.GoBack(); } else { int LastSelectIndex = Array.FindIndex(PictureFileList, (Photo) => Photo.Path.Equals(SelectedPhotoFile.Path, StringComparison.OrdinalIgnoreCase)); if (LastSelectIndex < 0 || LastSelectIndex >= PictureFileList.Length) { LastSelectIndex = 0; } PhotoCollection = new ObservableCollection <PhotoDisplaySupport>(PictureFileList.Select((Item) => new PhotoDisplaySupport(Item))); Flip.ItemsSource = PhotoCollection; if (!await PhotoCollection[LastSelectIndex].ReplaceThumbnailBitmapAsync()) { CouldnotLoadTip.Visibility = Visibility.Visible; } for (int i = LastSelectIndex - 5 > 0 ? LastSelectIndex - 5 : 0; i <= (LastSelectIndex + 5 < PhotoCollection.Count - 1 ? LastSelectIndex + 5 : PhotoCollection.Count - 1) && !Cancellation.IsCancellationRequested; i++) { await PhotoCollection[i].GenerateThumbnailAsync(); } if (!Cancellation.IsCancellationRequested) { Flip.SelectedIndex = LastSelectIndex; Flip.SelectionChanged += Flip_SelectionChanged; Flip.SelectionChanged += Flip_SelectionChanged1; EnterAnimation.Begin(); } } } else { throw new FileNotFoundException(); } } catch (Exception ex) { CouldnotLoadTip.Visibility = Visibility.Visible; LogTracer.Log(ex, "An error was threw when initialize PhotoViewer"); } finally { ExitLocker.Set(); } }
private async void QuickStartGridView_ItemClick(object sender, ItemClickEventArgs e) { if (e.ClickedItem is QuickStartItem Item) { if ((sender as GridView).Name == nameof(QuickStartGridView)) { if (Uri.TryCreate(Item.Protocol, UriKind.Absolute, out Uri Ur)) { if (Ur.IsFile) { if (await FileSystemStorageItemBase.CheckExistAsync(Item.Protocol)) { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { try { if (Path.GetExtension(Item.Protocol).ToLower() == ".msc") { if (!await Exclusive.Controller.RunAsync("powershell.exe", string.Empty, WindowState.Normal, false, true, false, "-Command", Item.Protocol)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LaunchFailed_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); } } else { if (!await Exclusive.Controller.RunAsync(Item.Protocol, Path.GetDirectoryName(Item.Protocol))) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LaunchFailed_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; await Dialog.ShowAsync(); } } } catch (Exception ex) { LogTracer.Log(ex, "Could not execute program in quick start"); } } } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_ApplicationNotFound_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); } } else { await Launcher.LaunchUriAsync(Ur); } } else { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { if (!await Exclusive.Controller.LaunchUWPLnkAsync(Item.Protocol)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_LaunchFailed_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); } } } } else { await Launcher.LaunchUriAsync(new Uri(Item.Protocol)); } } }
private static async Task LeadToBlueScreen(Exception Ex, [CallerMemberName] string MemberName = "", [CallerFilePath] string SourceFilePath = "", [CallerLineNumber] int SourceLineNumber = 0) { if (Ex == null) { throw new ArgumentNullException(nameof(Ex), "Exception could not be null"); } await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { string[] MessageSplit; try { if (string.IsNullOrWhiteSpace(Ex.Message)) { MessageSplit = Array.Empty <string>(); } else { MessageSplit = Ex.Message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).Select((Line) => $" {Line.Trim()}").ToArray(); } } catch { MessageSplit = Array.Empty <string>(); } string[] StackTraceSplit; try { if (string.IsNullOrWhiteSpace(Ex.StackTrace)) { StackTraceSplit = Array.Empty <string>(); } else { StackTraceSplit = Ex.StackTrace.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).Select((Line) => $" {Line.Trim()}").ToArray(); } } catch { StackTraceSplit = Array.Empty <string>(); } StringBuilder Builder = new StringBuilder() .AppendLine($"Version: {string.Join('.', Package.Current.Id.Version.Major, Package.Current.Id.Version.Minor, Package.Current.Id.Version.Build, Package.Current.Id.Version.Revision)}") .AppendLine() .AppendLine("The following is the error message:") .AppendLine("------------------------------------") .AppendLine($"Exception: {Ex}") .AppendLine() .AppendLine("Message:") .AppendLine(MessageSplit.Length == 0 ? " Unknown" : string.Join(Environment.NewLine, MessageSplit)) .AppendLine() .AppendLine("StackTrace:") .AppendLine(StackTraceSplit.Length == 0 ? " Unknown" : string.Join(Environment.NewLine, StackTraceSplit)) .AppendLine() .AppendLine("Extra info: ") .AppendLine($" CallerMemberName: {MemberName}") .AppendLine($" CallerFilePath: {SourceFilePath}") .AppendLine($" CallerLineNumber: {SourceLineNumber}") .AppendLine("------------------------------------") .AppendLine(); if (Window.Current.Content is Frame rootFrame) { rootFrame.Navigate(typeof(BlueScreen), Builder.ToString()); } else { Frame Frame = new Frame(); Window.Current.Content = Frame; Frame.Navigate(typeof(BlueScreen), Builder.ToString()); } }); LogTracer.Log(Ex, "UnhandleException"); }
private async void Screen_Dismissed(SplashScreen sender, object args) { try { if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("QuickStartInitialFinished1")) { await SQLite.Current.ClearTableAsync("QuickStart").ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_1"), "ms-appx:///QuickStartImage/MicrosoftStore.png", "ms-windows-store://home", QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_2"), "ms-appx:///QuickStartImage/Calculator.png", "calculator:", QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_3"), "ms-appx:///QuickStartImage/Setting.png", "ms-settings:", QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_4"), "ms-appx:///QuickStartImage/Email.png", "mailto:", QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_5"), "ms-appx:///QuickStartImage/Calendar.png", "outlookcal:", QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_6"), "ms-appx:///QuickStartImage/Photos.png", "ms-photos:", QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_7"), "ms-appx:///QuickStartImage/Weather.png", "msnweather:", QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_9"), "ms-appx:///HotWebImage/Facebook.png", "https://www.facebook.com/", QuickStartType.WebSite).ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_10"), "ms-appx:///HotWebImage/Instagram.png", "https://www.instagram.com/", QuickStartType.WebSite).ConfigureAwait(false); await SQLite.Current.SetQuickStartItemAsync(Globalization.GetString("ExtendedSplash_QuickStartItem_Name_11"), "ms-appx:///HotWebImage/Twitter.png", "https://twitter.com", QuickStartType.WebSite).ConfigureAwait(false); ApplicationData.Current.LocalSettings.Values["QuickStartInitialFinished1"] = true; } if (ApplicationData.Current.LocalSettings.Values.ContainsKey("RefreshQuickStart")) { await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///QuickStartImage/MicrosoftStore.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_1"), QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///QuickStartImage/Calculator.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_2"), QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///QuickStartImage/Setting.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_3"), QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///QuickStartImage/Email.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_4"), QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///QuickStartImage/Calendar.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_5"), QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///QuickStartImage/Photos.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_6"), QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///QuickStartImage/Weather.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_7"), QuickStartType.Application).ConfigureAwait(false); await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///HotWebImage/Facebook.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_9"), QuickStartType.WebSite).ConfigureAwait(false); await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///HotWebImage/Instagram.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_10"), QuickStartType.WebSite).ConfigureAwait(false); await SQLite.Current.UpdateQuickStartItemAsync("ms-appx:///HotWebImage/Twitter.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_11"), QuickStartType.WebSite).ConfigureAwait(false); ApplicationData.Current.LocalSettings.Values.Remove("RefreshQuickStart"); } bool IsFileAccessible = await CheckAccessAuthority().ConfigureAwait(false); if (IsFileAccessible) { await DismissExtendedSplashAsync().ConfigureAwait(false); } else { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Display.Text = Globalization.GetString("ExtendedSplash_Access_Tips"); PermissionArea.Visibility = Visibility.Visible; LoadingBingArea.Visibility = Visibility.Collapsed; }); } } catch (Exception ex) { LogTracer.Log(ex, "An error was threw when dismissing extendedsplash "); } }
private async void AddFile_Click(object sender, RoutedEventArgs e) { FileOpenPicker Picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.ComputerFolder, ViewMode = PickerViewMode.Thumbnail }; Picker.FileTypeFilter.Add("*"); IReadOnlyList <StorageFile> FileList = await Picker.PickMultipleFilesAsync(); if (FileList.Count > 0) { ActivateLoading(true, true); Cancellation = new CancellationTokenSource(); try { foreach (string OriginFilePath in FileList.Select((Item) => Item.Path)) { if (await FileSystemStorageItemBase.OpenAsync(OriginFilePath) is FileSystemStorageFile File) { if (await File.EncryptAsync(SecureFolder.Path, EncryptionAESKey, AESKeySize, Cancellation.Token) is FileSystemStorageFile EncryptedFile) { SecureCollection.Add(EncryptedFile); await File.DeleteAsync(false); } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_EncryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); } } } } catch (TaskCanceledException cancelException) { LogTracer.Log(cancelException, "Import items to SecureArea have been cancelled"); } catch (Exception ex) { LogTracer.Log(ex, "An exception was threw when importing file"); QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_EncryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); } finally { Cancellation.Dispose(); Cancellation = null; await Task.Delay(1500); ActivateLoading(false); } } }
private async void PickWin32_Click(object sender, RoutedEventArgs e) { try { FileOpenPicker Picker = new FileOpenPicker { SuggestedStartLocation = PickerLocationId.ComputerFolder, ViewMode = PickerViewMode.List }; Picker.FileTypeFilter.Add(".exe"); Picker.FileTypeFilter.Add(".lnk"); Picker.FileTypeFilter.Add(".msc"); if (await Picker.PickSingleFileAsync() is StorageFile ExecuteFile) { IDictionary <string, object> PropertiesDictionary = await ExecuteFile.Properties.RetrievePropertiesAsync(new string[] { "System.FileDescription" }); string ExtraAppName = string.Empty; if (PropertiesDictionary.TryGetValue("System.FileDescription", out object DescriptionRaw)) { ExtraAppName = Convert.ToString(DescriptionRaw); } DisplayName.Text = string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName; Protocol.Text = ExecuteFile.Path; StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting); if (await ExecuteFile.GetThumbnailRawStreamAsync() is IRandomAccessStream ThumbnailStream) { try { BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(ThumbnailStream); using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied)) using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap)) using (InMemoryRandomAccessStream ResizeBitmapStream = new InMemoryRandomAccessStream()) { BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ResizeBitmapStream); Encoder.SetSoftwareBitmap(ResizeBitmap); await Encoder.FlushAsync(); BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(ResizeBitmapStream); ResizeBitmapStream.Seek(0); using (Stream TransformStream = ResizeBitmapStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } finally { ThumbnailStream.Dispose(); } } else { Uri PageUri = AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png"); StorageFile PageFile = await StorageFile.GetFileFromApplicationUriAsync(PageUri); using (IRandomAccessStream PageStream = await PageFile.OpenAsync(FileAccessMode.Read)) { BitmapImage Image = new BitmapImage(); Icon.Source = Image; await Image.SetSourceAsync(PageStream); PageStream.Seek(0); using (Stream TransformStream = PageStream.AsStreamForRead()) using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync()) { await TransformStream.CopyToAsync(FileStream); } } } ImageFile = FileThumbnail; } } catch (Exception ex) { LogTracer.Log(ex); FailureTips.IsOpen = true; } }
private async void Grid_Drop(object sender, DragEventArgs e) { try { if (e.DataView.Contains(StandardDataFormats.StorageItems)) { IReadOnlyList <IStorageItem> Items = await e.DataView.GetStorageItemsAsync(); if (Items.Any((Item) => Item.IsOfType(StorageItemTypes.Folder))) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_TipTitle"), Content = Globalization.GetString("QueueDialog_SecureAreaImportFiliter_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); } if (Items.Any((Item) => Item.IsOfType(StorageItemTypes.File))) { ActivateLoading(true, true); Cancellation = new CancellationTokenSource(); try { foreach (string OriginFilePath in Items.Select((Item) => Item.Path)) { if (await FileSystemStorageItemBase.OpenAsync(OriginFilePath) is FileSystemStorageFile File) { if (await File.EncryptAsync(SecureFolder.Path, EncryptionAESKey, AESKeySize, Cancellation.Token) is FileSystemStorageFile EncryptedFile) { SecureCollection.Add(EncryptedFile); await File.DeleteAsync(false); } else { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_EncryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); } } } } catch (TaskCanceledException cancelException) { LogTracer.Log(cancelException, "Import items to SecureArea have been cancelled"); } catch (Exception ex) { LogTracer.Log(ex, "An error was threw when importing file"); QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_EncryptError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync(); } finally { Cancellation.Dispose(); Cancellation = null; await Task.Delay(1000); ActivateLoading(false); } } } } catch (Exception ex) when(ex.HResult is unchecked ((int)0x80040064)or unchecked ((int)0x8004006A)) { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_CopyFromUnsupportedArea_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync(); } catch { QueueContentDialog dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_FailToGetClipboardError_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await dialog.ShowAsync(); } }
private async void QueueContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { ContentDialogButtonClickDeferral Deferral = args.GetDeferral(); try { if ((Type == QuickStartType.Application && CommonAccessCollection.QuickStartList.Any((Item) => Item.DisplayName == DisplayName.Text)) || (Type == QuickStartType.WebSite && CommonAccessCollection.WebLinkList.Any((Item) => Item.DisplayName == DisplayName.Text))) { ExistTip.IsOpen = true; args.Cancel = true; } else if (Icon.Source == null || (Icon.Source as BitmapImage)?.UriSource?.OriginalString == "ms-appx:///Assets/AddImage.png") { EmptyTip.Target = Icon; EmptyTip.IsOpen = true; args.Cancel = true; } else if (string.IsNullOrWhiteSpace(Protocol.Text)) { EmptyTip.Target = Protocol; EmptyTip.IsOpen = true; args.Cancel = true; } else if (string.IsNullOrWhiteSpace(DisplayName.Text)) { EmptyTip.Target = DisplayName; EmptyTip.IsOpen = true; args.Cancel = true; } else { switch (Type) { case QuickStartType.Application: { if (Uri.TryCreate(Protocol.Text, UriKind.Absolute, out _)) { if (!FileSystemItemNameChecker.IsValid(DisplayName.Text)) { args.Cancel = true; InvalidCharTip.IsOpen = true; Deferral.Complete(); return; } if (IsUpdate) { if (ImageFile == null) { await SQLite.Current.UpdateQuickStartItemAsync(QuickItem.DisplayName, DisplayName.Text, null, Protocol.Text, QuickStartType.Application); QuickItem.Update(Icon.Source as BitmapImage, Protocol.Text, null, DisplayName.Text); } else { StorageFile NewFile = await ImageFile.CopyAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("QuickStartImage", CreationCollisionOption.OpenIfExists), DisplayName.Text + Path.GetExtension(ImageFile.Path), NameCollisionOption.GenerateUniqueName); await SQLite.Current.UpdateQuickStartItemAsync(QuickItem.DisplayName, DisplayName.Text, $"QuickStartImage\\{NewFile.Name}", Protocol.Text, QuickStartType.Application); QuickItem.Update(Icon.Source as BitmapImage, Protocol.Text, $"QuickStartImage\\{NewFile.Name}", DisplayName.Text); } } else { StorageFile NewFile = await ImageFile.CopyAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("QuickStartImage", CreationCollisionOption.OpenIfExists), DisplayName.Text + Path.GetExtension(ImageFile.Path), NameCollisionOption.GenerateUniqueName); CommonAccessCollection.QuickStartList.Insert(CommonAccessCollection.QuickStartList.Count - 1, new QuickStartItem(Icon.Source as BitmapImage, Protocol.Text, QuickStartType.Application, $"QuickStartImage\\{NewFile.Name}", DisplayName.Text)); await SQLite.Current.SetQuickStartItemAsync(DisplayName.Text, $"QuickStartImage\\{NewFile.Name}", Protocol.Text, QuickStartType.Application); } } else { using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController()) { if (await Exclusive.Controller.CheckIfPackageFamilyNameExist(Protocol.Text)) { if (IsUpdate) { if (ImageFile == null) { await SQLite.Current.UpdateQuickStartItemAsync(QuickItem.DisplayName, DisplayName.Text, null, Protocol.Text, QuickStartType.Application); QuickItem.Update(Icon.Source as BitmapImage, Protocol.Text, null, DisplayName.Text); } else { StorageFile NewFile = await ImageFile.CopyAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("QuickStartImage", CreationCollisionOption.OpenIfExists), DisplayName.Text + Path.GetExtension(ImageFile.Path), NameCollisionOption.GenerateUniqueName); await SQLite.Current.UpdateQuickStartItemAsync(QuickItem.DisplayName, DisplayName.Text, $"QuickStartImage\\{NewFile.Name}", Protocol.Text, QuickStartType.Application); QuickItem.Update(Icon.Source as BitmapImage, Protocol.Text, $"QuickStartImage\\{NewFile.Name}", DisplayName.Text); } } else { StorageFile NewFile = await ImageFile.CopyAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("QuickStartImage", CreationCollisionOption.OpenIfExists), DisplayName.Text + Path.GetExtension(ImageFile.Path), NameCollisionOption.GenerateUniqueName); CommonAccessCollection.QuickStartList.Insert(CommonAccessCollection.QuickStartList.Count - 1, new QuickStartItem(Icon.Source as BitmapImage, Protocol.Text, QuickStartType.Application, $"QuickStartImage\\{NewFile.Name}", DisplayName.Text)); await SQLite.Current.SetQuickStartItemAsync(DisplayName.Text, $"QuickStartImage\\{NewFile.Name}", Protocol.Text, QuickStartType.Application); } } else { FormatErrorTip.IsOpen = true; args.Cancel = true; } } } break; } case QuickStartType.WebSite: { if (Uri.TryCreate(Protocol.Text, UriKind.Absolute, out _)) { if (!FileSystemItemNameChecker.IsValid(DisplayName.Text)) { args.Cancel = true; InvalidCharTip.IsOpen = true; Deferral.Complete(); return; } if (IsUpdate) { if (ImageFile == null) { await SQLite.Current.UpdateQuickStartItemAsync(QuickItem.DisplayName, DisplayName.Text, null, Protocol.Text, QuickStartType.WebSite); QuickItem.Update(Icon.Source as BitmapImage, Protocol.Text, null, DisplayName.Text); } else { StorageFile NewFile = await ImageFile.CopyAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("HotWebImage", CreationCollisionOption.OpenIfExists), DisplayName.Text + Path.GetExtension(ImageFile.Path), NameCollisionOption.GenerateUniqueName); await SQLite.Current.UpdateQuickStartItemAsync(QuickItem.DisplayName, DisplayName.Text, $"HotWebImage\\{NewFile.Name}", Protocol.Text, QuickStartType.WebSite); QuickItem.Update(Icon.Source as BitmapImage, Protocol.Text, $"HotWebImage\\{NewFile.Name}", DisplayName.Text); } } else { StorageFile NewFile = await ImageFile.CopyAsync(await ApplicationData.Current.LocalFolder.CreateFolderAsync("HotWebImage", CreationCollisionOption.OpenIfExists), DisplayName.Text + Path.GetExtension(ImageFile.Path), NameCollisionOption.GenerateUniqueName); CommonAccessCollection.WebLinkList.Insert(CommonAccessCollection.WebLinkList.Count - 1, new QuickStartItem(Icon.Source as BitmapImage, Protocol.Text, QuickStartType.WebSite, $"HotWebImage\\{NewFile.Name}", DisplayName.Text)); await SQLite.Current.SetQuickStartItemAsync(DisplayName.Text, $"HotWebImage\\{NewFile.Name}", Protocol.Text, QuickStartType.WebSite); } } else { FormatErrorTip.IsOpen = true; args.Cancel = true; } break; } } } } catch (Exception ex) { LogTracer.Log(ex); } finally { Deferral.Complete(); } }
public async Task CreateNewTabAndOpenTargetFolder(string Path, int?InsertIndex = null) { int Index = InsertIndex ?? (TabViewControl?.TabItems.Count ?? 0); try { if (string.IsNullOrWhiteSpace(Path)) { if (CreateNewTab() is TabViewItem Item) { //预览版TabView在没有子Item时会崩溃,此方案作为临时解决方案 if (TabViewControl == null) { _ = FindName(nameof(TabViewControl)); } TabViewControl.TabItems.Insert(Index, Item); TabViewControl.UpdateLayout(); TabViewControl.SelectedItem = Item; } } else { if (WIN_Native_API.CheckIfHidden(Path)) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_ItemHidden_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); //预览版TabView在没有子Item时会崩溃,此方案作为临时解决方案 if (TabViewControl == null) { _ = FindName(nameof(TabViewControl)); if (CreateNewTab() is TabViewItem EmptyItem) { TabViewControl.TabItems.Insert(Index, EmptyItem); TabViewControl.UpdateLayout(); TabViewControl.SelectedItem = EmptyItem; } } } else { if (!SettingControl.IsDetachTreeViewAndPresenter && !SettingControl.IsDisplayHiddenItem) { PathAnalysis Analysis = new PathAnalysis(Path, string.Empty); while (Analysis.HasNextLevel) { if (WIN_Native_API.CheckIfHidden(Analysis.NextFullPath())) { QueueContentDialog Dialog = new QueueContentDialog { Title = Globalization.GetString("Common_Dialog_ErrorTitle"), Content = Globalization.GetString("QueueDialog_NeedOpenHiddenSwitch_Content"), CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton") }; _ = await Dialog.ShowAsync().ConfigureAwait(true); if (CreateNewTab() is TabViewItem EmptyItem) { //预览版TabView在没有子Item时会崩溃,此方案作为临时解决方案 if (TabViewControl == null) { _ = FindName(nameof(TabViewControl)); } TabViewControl.TabItems.Insert(Index, EmptyItem); TabViewControl.UpdateLayout(); TabViewControl.SelectedItem = EmptyItem; } return; } } } StorageFolder TargetFolder = await StorageFolder.GetFolderFromPathAsync(Path); if (CreateNewTab(TargetFolder) is TabViewItem Item) { //预览版TabView在没有子Item时会崩溃,此方案作为临时解决方案 if (TabViewControl == null) { _ = FindName(nameof(TabViewControl)); } TabViewControl.TabItems.Insert(Index, Item); TabViewControl.UpdateLayout(); TabViewControl.SelectedItem = Item; } } } } catch (Exception ex) { if (CreateNewTab() is TabViewItem Item) { //预览版TabView在没有子Item时会崩溃,此方案作为临时解决方案 if (TabViewControl == null) { _ = FindName(nameof(TabViewControl)); } TabViewControl.TabItems.Insert(Index, Item); TabViewControl.UpdateLayout(); TabViewControl.SelectedItem = Item; } LogTracer.Log(ex, "Error happened when try to create a new tab"); } }