private static void ShowMergeCompleteNotification()
        {
            try
            {
                ToastNotificationManager.History.Remove("MergeVideoNotification");

                ToastContent Content = new ToastContent()
                {
                    Scenario = ToastScenario.Default,
                    Launch   = "Transcode",
                    Visual   = new ToastVisual()
                    {
                        BindingGeneric = new ToastBindingGeneric()
                        {
                            Children =
                            {
                                new AdaptiveText()
                                {
                                    Text = Globalization.GetString("Merge_Toast_Complete_Text")
                                },

                                new AdaptiveText()
                                {
                                    Text = Globalization.GetString("Toast_ClickToClear_Text")
                                }
                            }
                        }
                    },
                };

                ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(Content.GetXml()));
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "Toast notification could not be sent");
            }
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is SyncStatus Status)
            {
                switch (Status)
                {
                case SyncStatus.AvailableOffline:
                {
                    return(Globalization.GetString("OfflineAvailabilityText3"));
                }

                case SyncStatus.AvailableOnline:
                {
                    return(Globalization.GetString("OfflineAvailabilityText1"));
                }

                case SyncStatus.Excluded:
                {
                    return(Globalization.GetString("OfflineAvailabilityStatusText5"));
                }

                case SyncStatus.Sync:
                {
                    return(Globalization.GetString("OfflineAvailabilityStatusText7"));
                }

                default:
                {
                    return(null);
                }
                }
            }
            else
            {
                return(null);
            }
        }
        public static IEnumerable <FileSystemStorageGroupItem> GetGroupedCollection <T>(IEnumerable <T> InputCollection, GroupTarget Target, GroupDirection Direction) where T : FileSystemStorageItemBase
        {
            List <FileSystemStorageGroupItem> Result = new List <FileSystemStorageGroupItem>();

            switch (Target)
            {
            case GroupTarget.Name:
            {
                Result.Add(new FileSystemStorageGroupItem("A - G", InputCollection.Where((Item) => (Item.Name.FirstOrDefault() >= 65 && Item.Name.FirstOrDefault() <= 71) || (Item.Name.FirstOrDefault() >= 97 && Item.Name.FirstOrDefault() <= 103))));

                Result.Add(new FileSystemStorageGroupItem("H - N", InputCollection.Where((Item) => (Item.Name.FirstOrDefault() >= 72 && Item.Name.FirstOrDefault() <= 78) || (Item.Name.FirstOrDefault() >= 104 && Item.Name.FirstOrDefault() <= 110))));


                Result.Add(new FileSystemStorageGroupItem("O - T", InputCollection.Where((Item) => (Item.Name.FirstOrDefault() >= 79 && Item.Name.FirstOrDefault() <= 84) || (Item.Name.FirstOrDefault() >= 111 && Item.Name.FirstOrDefault() <= 116))));


                Result.Add(new FileSystemStorageGroupItem("U - Z", InputCollection.Where((Item) => (Item.Name.FirstOrDefault() >= 85 && Item.Name.FirstOrDefault() <= 90) || (Item.Name.FirstOrDefault() >= 117 && Item.Name.FirstOrDefault() <= 112))));


                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_Others"), InputCollection.Where((Item) => Item.Name.FirstOrDefault() < 65 || (Item.Name.FirstOrDefault() > 90 && Item.Name.FirstOrDefault() < 97) || Item.Name.FirstOrDefault() > 122)));

                break;
            }

            case GroupTarget.Type:
            {
                IEnumerable <IGrouping <string, T> > GroupResult = InputCollection.GroupBy((Source) => Source.DisplayType);

                foreach (IGrouping <string, T> Group in GroupResult)
                {
                    Result.Add(new FileSystemStorageGroupItem(Group.Key, Group));
                }

                break;
            }

            case GroupTarget.ModifiedTime:
            {
                DateTimeOffset TodayTime            = DateTimeOffset.Now.Date;
                DateTimeOffset YesterdayTime        = DateTimeOffset.Now.AddDays(-1).Date;
                DateTimeOffset EarlierThisWeekTime  = DateTimeOffset.Now.AddDays(-(int)DateTimeOffset.Now.DayOfWeek).Date;
                DateTimeOffset LastWeekTime         = DateTimeOffset.Now.AddDays(-((int)DateTimeOffset.Now.DayOfWeek + 7)).Date;
                DateTimeOffset EarlierThisMonthTime = DateTimeOffset.Now.AddDays(-DateTimeOffset.Now.Day).Date;
                DateTimeOffset LastMonth            = DateTimeOffset.Now.AddDays(-DateTimeOffset.Now.Day).AddMonths(-1).Date;
                DateTimeOffset EarlierThisYearTime  = DateTimeOffset.Now.AddMonths(-DateTimeOffset.Now.Month).Date;

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_Today"), InputCollection.Where((Item) => Item.ModifiedTimeRaw >= TodayTime)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_Yesterday"), InputCollection.Where((Item) => Item.ModifiedTimeRaw >= YesterdayTime && Item.ModifiedTimeRaw < TodayTime)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_EarlierThisWeek"), InputCollection.Where((Item) => Item.ModifiedTimeRaw >= EarlierThisWeekTime && Item.ModifiedTimeRaw < YesterdayTime)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_LastWeek"), InputCollection.Where((Item) => Item.ModifiedTimeRaw >= LastWeekTime && Item.ModifiedTimeRaw < EarlierThisWeekTime)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_EarlierThisMonth"), InputCollection.Where((Item) => Item.ModifiedTimeRaw >= EarlierThisMonthTime && Item.ModifiedTimeRaw < LastWeekTime)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_LastMonth"), InputCollection.Where((Item) => Item.ModifiedTimeRaw >= LastMonth && Item.ModifiedTimeRaw < EarlierThisMonthTime)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_EarlierThisYear"), InputCollection.Where((Item) => Item.ModifiedTimeRaw >= EarlierThisYearTime && Item.ModifiedTimeRaw < LastMonth)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_LongTimeAgo"), InputCollection.Where((Item) => Item.ModifiedTimeRaw < EarlierThisYearTime)));

                break;
            }

            case GroupTarget.Size:
            {
                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_Unspecified"), InputCollection.OfType <FileSystemStorageFolder>()));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_Smaller"), InputCollection.OfType <FileSystemStorageFile>().Where((Item) => Item.SizeRaw >> 10 < 1024)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_Medium"), InputCollection.OfType <FileSystemStorageFile>().Where((Item) => Item.SizeRaw >> 10 >= 1024 && Item.SizeRaw >> 20 < 128)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_Larger"), InputCollection.OfType <FileSystemStorageFile>().Where((Item) => Item.SizeRaw >> 20 >= 128 && Item.SizeRaw >> 20 < 1024)));

                Result.Add(new FileSystemStorageGroupItem(Globalization.GetString("GroupHeader_Huge"), InputCollection.OfType <FileSystemStorageFile>().Where((Item) => Item.SizeRaw >> 30 >= 1)));

                break;
            }

            default:
            {
                return(new List <FileSystemStorageGroupItem>(0));
            }
            }

            if (Direction == GroupDirection.Descending)
            {
                Result.Reverse();
            }

            return(Result);
        }
示例#4
0
        /// <summary>
        /// 更新支持或反对的信息
        /// </summary>
        /// <param name="Type">更新类型</param>
        private async void UpdateSupportInfo(FeedBackUpdateType Type)
        {
            switch (Type)
            {
            case FeedBackUpdateType.AddLike:
            {
                if (UserVoteAction == "-")
                {
                    DislikeNum = (Convert.ToInt16(DislikeNum) - 1).ToString();
                }

                LikeNum        = (Convert.ToInt16(LikeNum) + 1).ToString();
                UserVoteAction = "+";
                break;
            }

            case FeedBackUpdateType.DelLike:
            {
                LikeNum        = (Convert.ToInt16(LikeNum) - 1).ToString();
                UserVoteAction = "=";
                break;
            }

            case FeedBackUpdateType.AddDislike:
            {
                if (UserVoteAction == "+")
                {
                    LikeNum = (Convert.ToInt16(LikeNum) - 1).ToString();
                }

                DislikeNum     = (Convert.ToInt16(DislikeNum) + 1).ToString();
                UserVoteAction = "-";
                break;
            }

            case FeedBackUpdateType.DelDislike:
            {
                DislikeNum     = (Convert.ToInt16(DislikeNum) - 1).ToString();
                UserVoteAction = "=";
                break;
            }
            }

            SupportDescription = $"({LikeNum} {Globalization.GetString("FeedBackItem_SupportDescription_Positive")} , {DislikeNum} {Globalization.GetString("FeedBackItem_SupportDescription_Negative")})";

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SupportDescription)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsLike)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsDislike)));

            await Task.Run(() =>
            {
                Locker.WaitOne();
            }).ConfigureAwait(true);

            try
            {
                if (!await MySQL.Current.UpdateFeedBackVoteAsync(this).ConfigureAwait(true))
                {
                    QueueContentDialog dialog = new QueueContentDialog
                    {
                        Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                        Content         = Globalization.GetString("Network_Error_Dialog_Content"),
                        CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                    };
                    _ = await dialog.ShowAsync().ConfigureAwait(true);
                }
            }
            finally
            {
                Locker.Set();
            }
        }
示例#5
0
 protected override DataTemplate SelectTemplateCore(object Item)
 {
     if (Item is KeyValuePair <string, object> Pair && Pair.Key == Globalization.GetString("Properties_Details_Rating"))
     {
         return(Rating);
     }
示例#6
0
        /// <summary>
        /// 提供图片转码
        /// </summary>
        /// <param name="SourceFile">源文件</param>
        /// <param name="DestinationFile">目标文件</param>
        /// <param name="IsEnableScale">是否启用缩放</param>
        /// <param name="ScaleWidth">缩放宽度</param>
        /// <param name="ScaleHeight">缩放高度</param>
        /// <param name="InterpolationMode">插值模式</param>
        /// <returns></returns>
        public static Task TranscodeFromImageAsync(StorageFile SourceFile, StorageFile DestinationFile, bool IsEnableScale = false, uint ScaleWidth = default, uint ScaleHeight = default, BitmapInterpolationMode InterpolationMode = default)
        {
            return Task.Run(() =>
            {
                IsAnyTransformTaskRunning = true;

                using (IRandomAccessStream OriginStream = SourceFile.OpenAsync(FileAccessMode.Read).AsTask().Result)
                {
                    BitmapDecoder Decoder = BitmapDecoder.CreateAsync(OriginStream).AsTask().Result;
                    using (IRandomAccessStream TargetStream = DestinationFile.OpenAsync(FileAccessMode.ReadWrite).AsTask().Result)
                    using (SoftwareBitmap TranscodeImage = Decoder.GetSoftwareBitmapAsync().AsTask().Result)
                    {
                        BitmapEncoder Encoder = DestinationFile.FileType switch
                        {
                            ".png" => BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, TargetStream).AsTask().Result,
                            ".jpg" => BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, TargetStream).AsTask().Result,
                            ".bmp" => BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, TargetStream).AsTask().Result,
                            ".heic" => BitmapEncoder.CreateAsync(BitmapEncoder.HeifEncoderId, TargetStream).AsTask().Result,
                            ".tiff" => BitmapEncoder.CreateAsync(BitmapEncoder.TiffEncoderId, TargetStream).AsTask().Result,
                            _ => throw new InvalidOperationException("Unsupport image format"),
                        };

                        if (IsEnableScale)
                        {
                            Encoder.BitmapTransform.ScaledWidth = ScaleWidth;
                            Encoder.BitmapTransform.ScaledHeight = ScaleHeight;
                            Encoder.BitmapTransform.InterpolationMode = InterpolationMode;
                        }

                        Encoder.SetSoftwareBitmap(TranscodeImage);
                        Encoder.IsThumbnailGenerated = true;
                        try
                        {
                            Encoder.FlushAsync().AsTask().Wait();
                        }
                        catch (Exception err)
                        {
                            if (err.HResult == unchecked((int)0x88982F81))
                            {
                                Encoder.IsThumbnailGenerated = false;
                                Encoder.FlushAsync().AsTask().Wait();
                            }
                            else
                            {
                                try
                                {
                                    DestinationFile.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait();
                                }
                                catch
                                {

                                }

                                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                                {
                                    QueueContentDialog dialog = new QueueContentDialog
                                    {
                                        Title = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                        Content = Globalization.GetString("EnDecode_Dialog_Content"),
                                        CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                    };
                                    _ = await dialog.ShowAsync().ConfigureAwait(true);
                                }).AsTask().Wait();
                            }
                        }
                    }
                }

                IsAnyTransformTaskRunning = false;
            });
        }
示例#7
0
        public static async Task SetCommandBarFlyoutWithExtraContextMenuItems(this ListViewBase ListControl, CommandBarFlyout Flyout, Point ShowAt)
        {
            if (Flyout == null)
            {
                throw new ArgumentNullException(nameof(Flyout), "Argument could not be null");
            }

            if (Interlocked.Exchange(ref ContextMenuLockResource, 1) == 0)
            {
                try
                {
                    if (ApplicationData.Current.LocalSettings.Values["ContextMenuExtSwitch"] is bool IsExt && !IsExt)
                    {
                        foreach (AppBarButton ExtraButton in Flyout.SecondaryCommands.OfType <AppBarButton>().Where((Btn) => Btn.Name == "ExtraButton").ToArray())
                        {
                            Flyout.SecondaryCommands.Remove(ExtraButton);
                        }

                        foreach (AppBarSeparator Separator in Flyout.SecondaryCommands.OfType <AppBarSeparator>().Where((Sep) => Sep.Name == "CustomSep").ToArray())
                        {
                            Flyout.SecondaryCommands.Remove(Separator);
                        }
                    }
                    else
                    {
                        string[] SelectedPathArray = null;

                        if (ListControl.SelectedItems.Count <= 1)
                        {
                            if (ListControl.SelectedItem is FileSystemStorageItemBase Selected)
                            {
                                SelectedPathArray = new string[] { Selected.Path };
                            }
                            else if (ListControl.FindParentOfType <FileControl>() is FileControl Control && !string.IsNullOrEmpty(Control.CurrentPresenter.CurrentFolder?.Path))
                            {
                                SelectedPathArray = new string[] { Control.CurrentPresenter.CurrentFolder.Path };
                            }
                        }
                        else
                        {
                            SelectedPathArray = ListControl.SelectedItems.OfType <FileSystemStorageItemBase>().Select((Item) => Item.Path).ToArray();
                        }

                        if (SelectedPathArray != null)
                        {
                            using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController())
                            {
                                List <ContextMenuItem> ExtraMenuItems = await Exclusive.Controller.GetContextMenuItemsAsync(SelectedPathArray, Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down)).ConfigureAwait(true);

                                foreach (AppBarButton ExtraButton in Flyout.SecondaryCommands.OfType <AppBarButton>().Where((Btn) => Btn.Name == "ExtraButton").ToArray())
                                {
                                    Flyout.SecondaryCommands.Remove(ExtraButton);
                                }

                                foreach (AppBarSeparator Separator in Flyout.SecondaryCommands.OfType <AppBarSeparator>().Where((Sep) => Sep.Name == "CustomSep").ToArray())
                                {
                                    Flyout.SecondaryCommands.Remove(Separator);
                                }

                                if (ExtraMenuItems.Count > 0)
                                {
                                    async void ClickHandler(object sender, RoutedEventArgs args)
                                    {
                                        if (sender is FrameworkElement Btn)
                                        {
                                            if (Btn.Tag is ContextMenuItem MenuItem)
                                            {
                                                Flyout.Hide();

                                                if (!await MenuItem.InvokeAsync().ConfigureAwait(true))
                                                {
                                                    QueueContentDialog Dialog = new QueueContentDialog
                                                    {
                                                        Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                                        Content         = Globalization.GetString("QueueDialog_InvokeContextMenuError_Content"),
                                                        CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                                    };

                                                    await Dialog.ShowAsync().ConfigureAwait(true);
                                                }
                                            }
                                        }
                                    }

                                    short ShowExtNum = Convert.ToInt16(Math.Max(9 - Flyout.SecondaryCommands.Count((Item) => Item is AppBarButton), 0));

                                    int Index = Flyout.SecondaryCommands.IndexOf(Flyout.SecondaryCommands.OfType <AppBarSeparator>().FirstOrDefault()) + 1;

                                    if (ExtraMenuItems.Count > ShowExtNum + 1)
                                    {
                                        Flyout.SecondaryCommands.Insert(Index, new AppBarSeparator {
                                            Name = "CustomSep"
                                        });

                                        foreach (ContextMenuItem AddItem in ExtraMenuItems.Take(ShowExtNum))
                                        {
                                            Flyout.SecondaryCommands.Insert(Index, await AddItem.GenerateUIButtonAsync(ClickHandler).ConfigureAwait(true));
                                        }

                                        AppBarButton MoreItem = new AppBarButton
                                        {
                                            Label    = Globalization.GetString("CommandBarFlyout_More_Item"),
                                            Icon     = new SymbolIcon(Symbol.More),
                                            Name     = "ExtraButton",
                                            MinWidth = 250
                                        };

                                        MenuFlyout MoreFlyout = new MenuFlyout();

                                        await ContextMenuItem.GenerateSubMenuItemsAsync(MoreFlyout.Items, ExtraMenuItems.Skip(ShowExtNum).ToArray(), ClickHandler).ConfigureAwait(true);

                                        MoreItem.Flyout = MoreFlyout;

                                        Flyout.SecondaryCommands.Insert(Index + ShowExtNum, MoreItem);
                                    }
                                    else
                                    {
                                        foreach (ContextMenuItem AddItem in ExtraMenuItems)
                                        {
                                            Flyout.SecondaryCommands.Insert(Index, await AddItem.GenerateUIButtonAsync(ClickHandler).ConfigureAwait(true));
                                        }

                                        Flyout.SecondaryCommands.Insert(Index + ExtraMenuItems.Count, new AppBarSeparator {
                                            Name = "CustomSep"
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
        /// <summary>
        /// 提供图片转码
        /// </summary>
        /// <param name="SourceFile">源文件</param>
        /// <param name="DestinationFile">目标文件</param>
        /// <param name="IsEnableScale">是否启用缩放</param>
        /// <param name="ScaleWidth">缩放宽度</param>
        /// <param name="ScaleHeight">缩放高度</param>
        /// <param name="InterpolationMode">插值模式</param>
        /// <returns></returns>
        public static async Task TranscodeFromImageAsync(FileSystemStorageFile SourceFile, FileSystemStorageFile DestinationFile, bool IsEnableScale = false, uint ScaleWidth = default, uint ScaleHeight = default, BitmapInterpolationMode InterpolationMode = default)
        {
            try
            {
                IsAnyTransformTaskRunning = true;

                using (ExtendedExecutionController ExtExecution = await ExtendedExecutionController.TryCreateExtendedExecution())
                    using (IRandomAccessStream OriginStream = await SourceFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read).ConfigureAwait(false))
                    {
                        try
                        {
                            BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(OriginStream);

                            using (SoftwareBitmap TranscodeImage = await Decoder.GetSoftwareBitmapAsync())
                                using (IRandomAccessStream TargetStream = await DestinationFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.ReadWrite).ConfigureAwait(false))
                                {
                                    BitmapEncoder Encoder = DestinationFile.Type.ToLower() switch
                                    {
                                        ".png" => await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, TargetStream),
                                        ".jpg" => await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, TargetStream),
                                        ".bmp" => await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, TargetStream),
                                        ".heic" => await BitmapEncoder.CreateAsync(BitmapEncoder.HeifEncoderId, TargetStream),
                                        ".tiff" => await BitmapEncoder.CreateAsync(BitmapEncoder.TiffEncoderId, TargetStream),
                                        _ => throw new InvalidOperationException("Unsupport image format"),
                                    };

                                    if (IsEnableScale)
                                    {
                                        Encoder.BitmapTransform.ScaledWidth       = ScaleWidth;
                                        Encoder.BitmapTransform.ScaledHeight      = ScaleHeight;
                                        Encoder.BitmapTransform.InterpolationMode = InterpolationMode;
                                    }

                                    Encoder.SetSoftwareBitmap(TranscodeImage);

                                    await Encoder.FlushAsync();
                                }
                        }
                        catch (Exception)
                        {
                            await DestinationFile.DeleteAsync(true);

                            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                            {
                                QueueContentDialog dialog = new QueueContentDialog
                                {
                                    Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                    Content         = Globalization.GetString("EnDecode_Dialog_Content"),
                                    CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                };

                                _ = await dialog.ShowAsync();
                            });
                        }
                    }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex);
            }
            finally
            {
                IsAnyTransformTaskRunning = false;
            }
        }
示例#9
0
        private static void ExecuteSubTaskCore(OperationListBaseModel Model)
        {
            Interlocked.Increment(ref RunningTaskCounter);

            try
            {
                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    Model.UpdateStatus(OperationStatus.Preparing);
                }).AsTask().Wait();

                Model.PrepareSizeDataAsync().Wait();

                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    Model.UpdateStatus(OperationStatus.Processing);
                    Model.UpdateProgress(0);
                }).AsTask().Wait();

                switch (Model)
                {
                case OperationListRemoteModel:
                {
                    using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                    {
                        if (!Exclusive.Controller.PasteRemoteFile(Model.ToPath).Result)
                        {
                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                {
                                    Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CopyFailUnexpectError_Content"));
                                }).AsTask().Wait();
                        }
                    }

                    break;
                }

                case OperationListCopyModel:
                {
                    try
                    {
                        CollisionOptions Option = CollisionOptions.None;

                        if (Model.FromPath.All((Item) => Path.GetDirectoryName(Item).Equals(Model.ToPath, StringComparison.OrdinalIgnoreCase)))
                        {
                            Option = CollisionOptions.RenameOnCollision;
                        }
                        else if (Model.FromPath.Select((SourcePath) => Path.Combine(Model.ToPath, Path.GetFileName(SourcePath)))
                                 .Any((DestPath) => FileSystemStorageItemBase.CheckExistAsync(DestPath).Result))
                        {
                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                {
                                    Model.UpdateStatus(OperationStatus.NeedAttention, Globalization.GetString("NameCollision"));
                                }).AsTask().Wait();

                            switch (Model.WaitForButtonAction())
                            {
                            case 0:
                            {
                                Option = CollisionOptions.OverrideOnCollision;
                                break;
                            }

                            case 1:
                            {
                                Option = CollisionOptions.RenameOnCollision;
                                break;
                            }
                            }
                        }

                        if (Model.Status == OperationStatus.Cancelled)
                        {
                            return;
                        }

                        using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                        {
                            Exclusive.Controller.CopyAsync(Model.FromPath, Model.ToPath, Option, ProgressHandler: (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CopyFailForNotExist_Content"));
                            }).AsTask().Wait();
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is InvalidOperationException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedPaste_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Copy failed for unexpected error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CopyFailUnexpectError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListMoveModel:
                {
                    try
                    {
                        CollisionOptions Option = CollisionOptions.None;

                        if (Model.FromPath.Select((SourcePath) => Path.Combine(Model.ToPath, Path.GetFileName(SourcePath)))
                            .Any((DestPath) => FileSystemStorageItemBase.CheckExistAsync(DestPath).Result))
                        {
                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                {
                                    Model.UpdateStatus(OperationStatus.NeedAttention, Globalization.GetString("NameCollision"));
                                }).AsTask().Wait();

                            switch (Model.WaitForButtonAction())
                            {
                            case 0:
                            {
                                Option = CollisionOptions.OverrideOnCollision;
                                break;
                            }

                            case 1:
                            {
                                Option = CollisionOptions.RenameOnCollision;
                                break;
                            }
                            }
                        }

                        if (Model.Status == OperationStatus.Cancelled)
                        {
                            return;
                        }

                        using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                        {
                            Exclusive.Controller.MoveAsync(Model.FromPath, Model.ToPath, Option, ProgressHandler: (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_MoveFailForNotExist_Content"));
                            }).AsTask().Wait();
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is FileCaputureException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_Item_Captured_Content"));
                            }).AsTask().Wait();
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is InvalidOperationException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedPaste_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Move failed for unexpected error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_MoveFailUnexpectError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListDeleteModel DeleteModel:
                {
                    try
                    {
                        using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                        {
                            Exclusive.Controller.DeleteAsync(DeleteModel.FromPath, DeleteModel.IsPermanentDelete, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_DeleteItemError_Content"));
                            }).AsTask().Wait();
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is FileCaputureException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_Item_Captured_Content"));
                            }).AsTask().Wait();
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is InvalidOperationException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedDelete_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Delete failed for unexpected error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_DeleteFailUnexpectError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListUndoModel UndoModel:
                {
                    try
                    {
                        using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                        {
                            switch (UndoModel.UndoOperationKind)
                            {
                            case OperationKind.Copy:
                            {
                                Exclusive.Controller.DeleteAsync(Model.FromPath, true, (s, e) =>
                                        {
                                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                            {
                                                Model.UpdateProgress(e.ProgressPercentage);
                                            }).AsTask().Wait();
                                        }).Wait();

                                break;
                            }

                            case OperationKind.Move:
                            {
                                Exclusive.Controller.MoveAsync(Model.FromPath, Model.ToPath, IsUndoOperation: true, ProgressHandler: (s, e) =>
                                        {
                                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                            {
                                                Model.UpdateProgress(e.ProgressPercentage);
                                            }).AsTask().Wait();
                                        }).Wait();

                                break;
                            }

                            case OperationKind.Delete:
                            {
                                if (!Exclusive.Controller.RestoreItemInRecycleBinAsync(Model.FromPath).Result)
                                {
                                    throw new Exception();
                                }

                                break;
                            }
                            }
                        }
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UndoFailForNotExist_Content"));
                            }).AsTask().Wait();
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is FileCaputureException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_Item_Captured_Content"));
                            }).AsTask().Wait();
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is InvalidOperationException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedUndo_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Undo failed for unexpected error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UndoFailure_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListCompressionModel CModel:
                {
                    try
                    {
                        CompressionUtil.SetEncoding(Encoding.Default);

                        switch (CModel.Type)
                        {
                        case CompressionType.Zip:
                        {
                            CompressionUtil.CreateZipAsync(CModel.FromPath, CModel.ToPath, CModel.Level, CModel.Algorithm, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();

                            break;
                        }

                        case CompressionType.Tar:
                        {
                            CompressionUtil.CreateTarAsync(CModel.FromPath, CModel.ToPath, CModel.Level, CModel.Algorithm, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();

                            break;
                        }

                        case CompressionType.Gzip:
                        {
                            if (CModel.FromPath.Length == 1)
                            {
                                CompressionUtil.CreateGzipAsync(CModel.FromPath.First(), CModel.ToPath, CModel.Level, (s, e) =>
                                        {
                                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                            {
                                                Model.UpdateProgress(e.ProgressPercentage);
                                            }).AsTask().Wait();
                                        }).Wait();
                            }
                            else
                            {
                                throw new ArgumentException("Gzip could not contains more than one item");
                            }

                            break;
                        }

                        case CompressionType.BZip2:
                        {
                            if (CModel.FromPath.Length == 1)
                            {
                                CompressionUtil.CreateBZip2Async(CModel.FromPath.First(), CModel.ToPath, (s, e) =>
                                        {
                                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                            {
                                                Model.UpdateProgress(e.ProgressPercentage);
                                            }).AsTask().Wait();
                                        }).Wait();
                            }
                            else
                            {
                                throw new ArgumentException("Gzip could not contains more than one item");
                            }

                            break;
                        }
                        }
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is UnauthorizedAccessException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedCompression_Content"));
                            }).AsTask().Wait();
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_LocateFileFailure_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Compression error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CompressionError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListDecompressionModel DModel:
                {
                    try
                    {
                        CompressionUtil.SetEncoding(DModel.Encoding);

                        if (Model.FromPath.All((Item) => Item.EndsWith(".zip", StringComparison.OrdinalIgnoreCase) ||
                                               Item.EndsWith(".tar", StringComparison.OrdinalIgnoreCase) ||
                                               Item.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase) ||
                                               Item.EndsWith(".tgz", StringComparison.OrdinalIgnoreCase) ||
                                               Item.EndsWith(".tar.bz2", StringComparison.OrdinalIgnoreCase) ||
                                               Item.EndsWith(".bz2", StringComparison.OrdinalIgnoreCase) ||
                                               Item.EndsWith(".gz", StringComparison.OrdinalIgnoreCase) ||
                                               Item.EndsWith(".rar", StringComparison.OrdinalIgnoreCase)))
                        {
                            CompressionUtil.ExtractAllAsync(Model.FromPath, Model.ToPath, DModel.ShouldCreateFolder, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                        else
                        {
                            throw new Exception(Globalization.GetString("QueueDialog_FileTypeIncorrect_Content"));
                        }
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is UnauthorizedAccessException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedDecompression_Content"));
                            }).AsTask().Wait();
                    }
                    catch (AggregateException Ae) when(Ae.InnerException is FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_LocateFileFailure_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Decompression error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_DecompressionError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }
                }

                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    if (Model.Status != OperationStatus.Error)
                    {
                        Model.UpdateProgress(100);
                        Model.UpdateStatus(OperationStatus.Completed);
                    }
                }).AsTask().Wait();
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "A subthread in Task List threw an exception");
            }
            finally
            {
                Interlocked.Decrement(ref RunningTaskCounter);
            }
        }
示例#10
0
        private static void ExecuteTaskCore(FullTrustProcessController.ExclusiveUsage Exclusive, OperationListBaseModel Model)
        {
            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                Model.UpdateStatus(OperationStatus.Processing);
            }).AsTask().Wait();

            switch (Model)
            {
            case OperationListRemoteModel:
            {
                if (!Exclusive.Controller.PasteRemoteFile(Model.ToPath).Result)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CopyFailUnexpectError_Content"));
                        }).AsTask().Wait();
                }

                break;
            }

            case OperationListCopyModel:
            {
                try
                {
                    Exclusive.Controller.CopyAsync(Model.FromPath, Model.ToPath, ProgressHandler: (s, e) =>
                        {
                            Model.UpdateProgress(e.ProgressPercentage);
                        }).Wait();
                }
                catch (FileNotFoundException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CopyFailForNotExist_Content"));
                        }).AsTask().Wait();
                }
                catch (InvalidOperationException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedPaste_Content"));
                        }).AsTask().Wait();
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Copy failed for unexpected error");

                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CopyFailUnexpectError_Content"));
                        }).AsTask().Wait();
                }

                break;
            }

            case OperationListMoveModel:
            {
                try
                {
                    Exclusive.Controller.MoveAsync(Model.FromPath, Model.ToPath, ProgressHandler: (s, e) =>
                        {
                            Model.UpdateProgress(e.ProgressPercentage);
                        }).Wait();
                }
                catch (FileNotFoundException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_MoveFailForNotExist_Content"));
                        }).AsTask().Wait();
                }
                catch (FileCaputureException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_Item_Captured_Content"));
                        }).AsTask().Wait();
                }
                catch (InvalidOperationException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedPaste_Content"));
                        }).AsTask().Wait();
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Move failed for unexpected error");

                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_MoveFailUnexpectError_Content"));
                        }).AsTask().Wait();
                }

                break;
            }

            case OperationListDeleteModel DeleteModel:
            {
                try
                {
                    Exclusive.Controller.DeleteAsync(DeleteModel.FromPath, DeleteModel.IsPermanentDelete, ProgressHandler: (s, e) =>
                        {
                            Model.UpdateProgress(e.ProgressPercentage);
                        }).Wait();
                }
                catch (FileNotFoundException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_DeleteItemError_Content"));
                        }).AsTask().Wait();
                }
                catch (FileCaputureException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_Item_Captured_Content"));
                        }).AsTask().Wait();
                }
                catch (InvalidOperationException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedDelete_Content"));
                        }).AsTask().Wait();
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Delete failed for unexpected error");

                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_DeleteFailUnexpectError_Content"));
                        }).AsTask().Wait();
                }

                break;
            }

            case OperationListUndoModel UndoModel:
            {
                try
                {
                    switch (UndoModel.UndoOperationKind)
                    {
                    case OperationKind.Copy:
                    {
                        Exclusive.Controller.DeleteAsync(Model.FromPath, true, true, (s, e) =>
                                {
                                    Model.UpdateProgress(e.ProgressPercentage);
                                }).Wait();

                        break;
                    }

                    case OperationKind.Move:
                    {
                        Exclusive.Controller.MoveAsync(Model.FromPath, Model.ToPath, true, (s, e) =>
                                {
                                    Model.UpdateProgress(e.ProgressPercentage);
                                }).Wait();

                        break;
                    }

                    case OperationKind.Delete:
                    {
                        if (!Exclusive.Controller.RestoreItemInRecycleBinAsync(Model.FromPath).Result)
                        {
                            throw new Exception();
                        }

                        break;
                    }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Undo failed for unexpected error");

                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UndoFailure_Content"));
                        }).AsTask().Wait();
                }

                break;
            }
            }

            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                if (Model.Status != OperationStatus.Error)
                {
                    Model.UpdateProgress(100);
                    Model.UpdateStatus(OperationStatus.Complete);
                }
            }).AsTask().Wait();
        }
示例#11
0
        private static void ExecuteTaskCore(OperationListBaseModel Model)
        {
            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                Model.UpdateStatus(OperationStatus.Processing);
            }).AsTask().Wait();

            switch (Model)
            {
            case OperationListCompressionModel CModel:
            {
                try
                {
                    switch (CModel.Type)
                    {
                    case CompressionType.Zip:
                    {
                        CompressionUtil.CreateZipAsync(CModel.FromPath, CModel.ToPath, (int)CModel.Level, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();

                        break;
                    }

                    case CompressionType.Tar:
                    {
                        CompressionUtil.CreateTarAsync(CModel.FromPath, CModel.ToPath, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();

                        break;
                    }

                    case CompressionType.Gzip:
                    {
                        if (CModel.FromPath.Length == 1)
                        {
                            CompressionUtil.CreateGzipAsync(CModel.FromPath.First(), CModel.ToPath, (int)CModel.Level, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();
                        }
                        else
                        {
                            throw new ArgumentException("Gzip could not contains more than one item");
                        }

                        break;
                    }
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedCompression_Content"));
                        }).AsTask().Wait();
                }
                catch (FileNotFoundException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_LocateFileFailure_Content"));
                        }).AsTask().Wait();
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Compression error");

                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CompressionError_Content"));
                        }).AsTask().Wait();
                }

                break;
            }

            case OperationListDecompressionModel DModel:
            {
                try
                {
                    CompressionUtil.SetEncoding(DModel.Encoding);

                    if (Model.FromPath.All((Item) => Path.GetExtension(Item).Equals(".zip", StringComparison.OrdinalIgnoreCase)))
                    {
                        if (string.IsNullOrEmpty(Model.ToPath))
                        {
                            CompressionUtil.ExtractZipAsync(Model.FromPath, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                        else
                        {
                            CompressionUtil.ExtractZipAsync(Model.FromPath, Model.ToPath, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                    }
                    else if (Model.FromPath.All((Item) => Path.GetExtension(Item).Equals(".tar", StringComparison.OrdinalIgnoreCase)))
                    {
                        if (string.IsNullOrEmpty(Model.ToPath))
                        {
                            CompressionUtil.ExtractTarAsync(Model.FromPath, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                        else
                        {
                            CompressionUtil.ExtractTarAsync(Model.FromPath, Model.ToPath, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                    }
                    else if (Model.FromPath.All((Item) => Path.GetExtension(Item).Equals(".gz", StringComparison.OrdinalIgnoreCase)))
                    {
                        if (string.IsNullOrEmpty(Model.ToPath))
                        {
                            CompressionUtil.ExtractGZipAsync(Model.FromPath, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                        else
                        {
                            CompressionUtil.ExtractGZipAsync(Model.FromPath, Model.ToPath, (s, e) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).Wait();
                        }
                    }
                    else
                    {
                        throw new Exception(Globalization.GetString("QueueDialog_FileTypeIncorrect_Content"));
                    }
                }
                catch (UnauthorizedAccessException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedDecompression_Content"));
                        }).AsTask().Wait();
                }
                catch (NotImplementedException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CanNotDecompressEncrypted_Content"));
                        }).AsTask().Wait();
                }
                catch (FileNotFoundException)
                {
                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_LocateFileFailure_Content"));
                        }).AsTask().Wait();
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Decompression error");

                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                        {
                            Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_DecompressionError_Content"));
                        }).AsTask().Wait();
                }

                break;
            }
            }

            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                if (Model.Status != OperationStatus.Error)
                {
                    Model.UpdateProgress(100);
                    Model.UpdateStatus(OperationStatus.Complete);
                }
            }).AsTask().Wait();
        }
        public async Task MoveAsync(IEnumerable <string> Source, string DestinationPath, ProgressChangedEventHandler ProgressHandler = null, bool IsUndoOperation = false)
        {
            if (Source == null)
            {
                throw new ArgumentNullException(nameof(Source), "Parameter could not be null");
            }

            try
            {
                IsNowHasAnyActionExcuting = true;

                if (await TryConnectToFullTrustExutor().ConfigureAwait(true))
                {
                    List <KeyValuePair <string, string> > MessageList = new List <KeyValuePair <string, string> >();

                    foreach (string SourcePath in Source)
                    {
                        try
                        {
                            _ = await StorageFile.GetFileFromPathAsync(SourcePath);

                            MessageList.Add(new KeyValuePair <string, string>(SourcePath, string.Empty));
                        }
                        catch
                        {
                            try
                            {
                                StorageFolder TargetFolder = await StorageFolder.GetFolderFromPathAsync(DestinationPath);

                                if (await TargetFolder.TryGetItemAsync(Path.GetFileName(SourcePath)) is StorageFolder ExistFolder)
                                {
                                    QueueContentDialog Dialog = new QueueContentDialog
                                    {
                                        Title             = Globalization.GetString("Common_Dialog_WarningTitle"),
                                        Content           = $"{Globalization.GetString("QueueDialog_FolderRepeat_Content")} {ExistFolder.Name}",
                                        PrimaryButtonText = Globalization.GetString("QueueDialog_FolderRepeat_PrimaryButton"),
                                        CloseButtonText   = Globalization.GetString("QueueDialog_FolderRepeat_CloseButton")
                                    };

                                    if (await Dialog.ShowAsync().ConfigureAwait(false) != ContentDialogResult.Primary)
                                    {
                                        StorageFolder NewFolder = await TargetFolder.CreateFolderAsync(Path.GetFileName(SourcePath), CreationCollisionOption.GenerateUniqueName);

                                        MessageList.Add(new KeyValuePair <string, string>(SourcePath, NewFolder.Name));
                                    }
                                    else
                                    {
                                        MessageList.Add(new KeyValuePair <string, string>(SourcePath, string.Empty));
                                    }
                                }
                                else
                                {
                                    MessageList.Add(new KeyValuePair <string, string>(SourcePath, string.Empty));
                                }
                            }
                            catch
                            {
                                throw new FileNotFoundException();
                            }
                        }
                    }

                    Task ProgressTask;

                    if (await PipeLineController.Current.CreateNewNamedPipe().ConfigureAwait(true))
                    {
                        ProgressTask = PipeLineController.Current.ListenPipeMessage(ProgressHandler);
                    }
                    else
                    {
                        ProgressTask = Task.CompletedTask;
                    }

                    ValueSet Value = new ValueSet
                    {
                        { "ExcuteType", ExcuteType_Move },
                        { "SourcePath", JsonConvert.SerializeObject(MessageList) },
                        { "DestinationPath", DestinationPath },
                        { "Guid", PipeLineController.Current.GUID.ToString() },
                        { "Undo", IsUndoOperation }
                    };

                    Task <AppServiceResponse> MessageTask = Connection.SendMessageAsync(Value).AsTask();

                    await Task.WhenAll(MessageTask, ProgressTask).ConfigureAwait(true);

                    if (MessageTask.Result.Status == AppServiceResponseStatus.Success)
                    {
                        if (MessageTask.Result.Message.ContainsKey("Success"))
                        {
                            if (MessageTask.Result.Message.TryGetValue("OperationRecord", out object value))
                            {
                                OperationRecorder.Current.Value.Push(JsonConvert.DeserializeObject <List <string> >(Convert.ToString(value)));
                            }
                        }
                        else if (MessageTask.Result.Message.ContainsKey("Error_NotFound"))
                        {
                            throw new FileNotFoundException();
                        }
                        else if (MessageTask.Result.Message.ContainsKey("Error_Failure"))
                        {
                            throw new InvalidOperationException("Fail to move item");
                        }
                        else if (MessageTask.Result.Message.ContainsKey("Error_Capture"))
                        {
                            throw new FileCaputureException();
                        }
                        else
                        {
                            throw new Exception("Unknown reason");
                        }
                    }
                    else
                    {
                        throw new NoResponseException();
                    }
                }
                else
                {
                    throw new NoResponseException();
                }
            }
            finally
            {
                IsNowHasAnyActionExcuting = false;
            }
        }
示例#13
0
        private static void ExecuteSubTaskCore(OperationListBaseModel Model)
        {
            Interlocked.Increment(ref RunningTaskCounter);

            try
            {
                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    Model.UpdateStatus(OperationStatus.Preparing);
                }).AsTask().Wait();

                Model.PrepareSizeDataAsync().Wait();

                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    Model.UpdateStatus(OperationStatus.Processing);
                    Model.UpdateProgress(0);
                }).AsTask().Wait();

                switch (Model)
                {
                case OperationListRemoteModel:
                {
                    using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                    {
                        if (!Exclusive.Controller.PasteRemoteFile(Model.ToPath).Result)
                        {
                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                {
                                    Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CopyFailUnexpectError_Content"));
                                }).AsTask().Wait();
                        }
                    }

                    break;
                }

                case OperationListCopyModel:
                {
                    try
                    {
                        using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                        {
                            Exclusive.Controller.CopyAsync(Model.FromPath, Model.ToPath, ProgressHandler: (s, e) =>
                                {
                                    Model.UpdateProgress(e.ProgressPercentage);
                                }).Wait();
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CopyFailForNotExist_Content"));
                            }).AsTask().Wait();
                    }
                    catch (InvalidOperationException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedPaste_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Copy failed for unexpected error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CopyFailUnexpectError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListMoveModel:
                {
                    try
                    {
                        using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                        {
                            Exclusive.Controller.MoveAsync(Model.FromPath, Model.ToPath, ProgressHandler: (s, e) =>
                                {
                                    Model.UpdateProgress(e.ProgressPercentage);
                                }).Wait();
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_MoveFailForNotExist_Content"));
                            }).AsTask().Wait();
                    }
                    catch (FileCaputureException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_Item_Captured_Content"));
                            }).AsTask().Wait();
                    }
                    catch (InvalidOperationException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedPaste_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Move failed for unexpected error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_MoveFailUnexpectError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListDeleteModel DeleteModel:
                {
                    try
                    {
                        using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                        {
                            Exclusive.Controller.DeleteAsync(DeleteModel.FromPath, DeleteModel.IsPermanentDelete, ProgressHandler: (s, e) =>
                                {
                                    Model.UpdateProgress(e.ProgressPercentage);
                                }).Wait();
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_DeleteItemError_Content"));
                            }).AsTask().Wait();
                    }
                    catch (FileCaputureException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_Item_Captured_Content"));
                            }).AsTask().Wait();
                    }
                    catch (InvalidOperationException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedDelete_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Delete failed for unexpected error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_DeleteFailUnexpectError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListUndoModel UndoModel:
                {
                    try
                    {
                        using (FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result)
                        {
                            switch (UndoModel.UndoOperationKind)
                            {
                            case OperationKind.Copy:
                            {
                                Exclusive.Controller.DeleteAsync(Model.FromPath, true, true, (s, e) =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).Wait();

                                break;
                            }

                            case OperationKind.Move:
                            {
                                Exclusive.Controller.MoveAsync(Model.FromPath, Model.ToPath, true, (s, e) =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).Wait();

                                break;
                            }

                            case OperationKind.Delete:
                            {
                                if (!Exclusive.Controller.RestoreItemInRecycleBinAsync(Model.FromPath).Result)
                                {
                                    throw new Exception();
                                }

                                break;
                            }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Undo failed for unexpected error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UndoFailure_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListCompressionModel CModel:
                {
                    try
                    {
                        switch (CModel.Type)
                        {
                        case CompressionType.Zip:
                        {
                            CompressionUtil.CreateZipAsync(CModel.FromPath, CModel.ToPath, (int)CModel.Level, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();

                            break;
                        }

                        case CompressionType.Tar:
                        {
                            CompressionUtil.CreateTarAsync(CModel.FromPath, CModel.ToPath, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();

                            break;
                        }

                        case CompressionType.Gzip:
                        {
                            if (CModel.FromPath.Length == 1)
                            {
                                CompressionUtil.CreateGzipAsync(CModel.FromPath.First(), CModel.ToPath, (int)CModel.Level, (s, e) =>
                                        {
                                            CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                            {
                                                Model.UpdateProgress(e.ProgressPercentage);
                                            }).AsTask().Wait();
                                        }).Wait();
                            }
                            else
                            {
                                throw new ArgumentException("Gzip could not contains more than one item");
                            }

                            break;
                        }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedCompression_Content"));
                            }).AsTask().Wait();
                    }
                    catch (FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_LocateFileFailure_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Compression error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CompressionError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }

                case OperationListDecompressionModel DModel:
                {
                    try
                    {
                        CompressionUtil.SetEncoding(DModel.Encoding);

                        if (Model.FromPath.All((Item) => Path.GetExtension(Item).Equals(".zip", StringComparison.OrdinalIgnoreCase)))
                        {
                            if (string.IsNullOrEmpty(Model.ToPath))
                            {
                                CompressionUtil.ExtractZipAsync(Model.FromPath, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();
                            }
                            else
                            {
                                CompressionUtil.ExtractZipAsync(Model.FromPath, Model.ToPath, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();
                            }
                        }
                        else if (Model.FromPath.All((Item) => Path.GetExtension(Item).Equals(".tar", StringComparison.OrdinalIgnoreCase)))
                        {
                            if (string.IsNullOrEmpty(Model.ToPath))
                            {
                                CompressionUtil.ExtractTarAsync(Model.FromPath, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();
                            }
                            else
                            {
                                CompressionUtil.ExtractTarAsync(Model.FromPath, Model.ToPath, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();
                            }
                        }
                        else if (Model.FromPath.All((Item) => Path.GetExtension(Item).Equals(".gz", StringComparison.OrdinalIgnoreCase)))
                        {
                            if (string.IsNullOrEmpty(Model.ToPath))
                            {
                                CompressionUtil.ExtractGZipAsync(Model.FromPath, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();
                            }
                            else
                            {
                                CompressionUtil.ExtractGZipAsync(Model.FromPath, Model.ToPath, (s, e) =>
                                    {
                                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                        {
                                            Model.UpdateProgress(e.ProgressPercentage);
                                        }).AsTask().Wait();
                                    }).Wait();
                            }
                        }
                        else
                        {
                            throw new Exception(Globalization.GetString("QueueDialog_FileTypeIncorrect_Content"));
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedDecompression_Content"));
                            }).AsTask().Wait();
                    }
                    catch (NotImplementedException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_CanNotDecompressEncrypted_Content"));
                            }).AsTask().Wait();
                    }
                    catch (FileNotFoundException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_LocateFileFailure_Content"));
                            }).AsTask().Wait();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Decompression error");

                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_DecompressionError_Content"));
                            }).AsTask().Wait();
                    }

                    break;
                }
                }

                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    if (Model.Status != OperationStatus.Error)
                    {
                        Model.UpdateProgress(100);
                        Model.UpdateStatus(OperationStatus.Complete);
                    }
                }).AsTask().Wait();
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "A subthread in Task List threw an exception");
            }
            finally
            {
                Interlocked.Decrement(ref RunningTaskCounter);
            }
        }
        public static string SearchGroupBelonging <T>(T Item, GroupTarget Target) where T : FileSystemStorageItemBase
        {
            switch (Target)
            {
            case GroupTarget.Name:
            {
                if ((Item.Name.FirstOrDefault() >= 65 && Item.Name.FirstOrDefault() <= 71) || (Item.Name.FirstOrDefault() >= 97 && Item.Name.FirstOrDefault() <= 103))
                {
                    return("A - G");
                }
                else if ((Item.Name.FirstOrDefault() >= 72 && Item.Name.FirstOrDefault() <= 78) || (Item.Name.FirstOrDefault() >= 104 && Item.Name.FirstOrDefault() <= 110))
                {
                    return("H - N");
                }
                else if ((Item.Name.FirstOrDefault() >= 79 && Item.Name.FirstOrDefault() <= 84) || (Item.Name.FirstOrDefault() >= 111 && Item.Name.FirstOrDefault() <= 116))
                {
                    return("O - T");
                }
                else if ((Item.Name.FirstOrDefault() >= 85 && Item.Name.FirstOrDefault() <= 90) || (Item.Name.FirstOrDefault() >= 117 && Item.Name.FirstOrDefault() <= 112))
                {
                    return("U - Z");
                }
                else if (Item.Name.FirstOrDefault() < 65 || (Item.Name.FirstOrDefault() > 90 && Item.Name.FirstOrDefault() < 97) || Item.Name.FirstOrDefault() > 122)
                {
                    return(Globalization.GetString("GroupHeader_Others"));
                }
                else
                {
                    return(string.Empty);
                }
            }

            case GroupTarget.Type:
            {
                return(Item.DisplayType);
            }

            case GroupTarget.ModifiedTime:
            {
                DateTimeOffset TodayTime            = DateTimeOffset.Now.Date;
                DateTimeOffset YesterdayTime        = DateTimeOffset.Now.AddDays(-1).Date;
                DateTimeOffset EarlierThisWeekTime  = DateTimeOffset.Now.AddDays(-(int)DateTimeOffset.Now.DayOfWeek).Date;
                DateTimeOffset LastWeekTime         = DateTimeOffset.Now.AddDays(-((int)DateTimeOffset.Now.DayOfWeek + 7)).Date;
                DateTimeOffset EarlierThisMonthTime = DateTimeOffset.Now.AddDays(-DateTimeOffset.Now.Day).Date;
                DateTimeOffset LastMonth            = DateTimeOffset.Now.AddDays(-DateTimeOffset.Now.Day).AddMonths(-1).Date;
                DateTimeOffset EarlierThisYearTime  = DateTimeOffset.Now.AddMonths(-DateTimeOffset.Now.Month).Date;

                if (Item.ModifiedTimeRaw >= TodayTime)
                {
                    return(Globalization.GetString("GroupHeader_Today"));
                }
                else if (Item.ModifiedTimeRaw >= YesterdayTime && Item.ModifiedTimeRaw < TodayTime)
                {
                    return(Globalization.GetString("GroupHeader_Yesterday"));
                }
                else if (Item.ModifiedTimeRaw >= EarlierThisWeekTime && Item.ModifiedTimeRaw < YesterdayTime)
                {
                    return(Globalization.GetString("GroupHeader_EarlierThisWeek"));
                }
                else if (Item.ModifiedTimeRaw >= LastWeekTime && Item.ModifiedTimeRaw < EarlierThisWeekTime)
                {
                    return(Globalization.GetString("GroupHeader_LastWeek"));
                }
                else if (Item.ModifiedTimeRaw >= EarlierThisMonthTime && Item.ModifiedTimeRaw < LastWeekTime)
                {
                    return(Globalization.GetString("GroupHeader_EarlierThisMonth"));
                }
                else if (Item.ModifiedTimeRaw >= LastMonth && Item.ModifiedTimeRaw < EarlierThisMonthTime)
                {
                    return(Globalization.GetString("GroupHeader_LastMonth"));
                }
                else if (Item.ModifiedTimeRaw >= EarlierThisYearTime && Item.ModifiedTimeRaw < LastMonth)
                {
                    return(Globalization.GetString("GroupHeader_EarlierThisYear"));
                }
                else if (Item.ModifiedTimeRaw < EarlierThisYearTime)
                {
                    return(Globalization.GetString("GroupHeader_LongTimeAgo"));
                }
                else
                {
                    return(string.Empty);
                }
            }

            case GroupTarget.Size:
            {
                if (Item is FileSystemStorageFile)
                {
                    if (Item.SizeRaw >> 10 < 1024)
                    {
                        return(Globalization.GetString("GroupHeader_Smaller"));
                    }
                    else if (Item.SizeRaw >> 10 >= 1024 && Item.SizeRaw >> 20 < 128)
                    {
                        return(Globalization.GetString("GroupHeader_Medium"));
                    }
                    else if (Item.SizeRaw >> 20 >= 128 && Item.SizeRaw >> 20 < 1024)
                    {
                        return(Globalization.GetString("GroupHeader_Larger"));
                    }
                    else if (Item.SizeRaw >> 30 >= 1)
                    {
                        return(Globalization.GetString("GroupHeader_Huge"));
                    }
                    else
                    {
                        return(string.Empty);
                    }
                }
                else
                {
                    return(Globalization.GetString("GroupHeader_Unspecified"));
                }
            }

            default:
            {
                return(null);
            }
            }
        }
示例#15
0
        /// <summary>
        /// 初始化数据库预先导入的数据
        /// </summary>
        private void InitializeDatabase()
        {
            using SqliteTransaction Transaction = Connection.BeginTransaction();
            using SqliteCommand InitCommand     = new SqliteCommand
                  {
                      Connection  = Connection,
                      Transaction = Transaction
                  };

            StringBuilder Builder = new StringBuilder();

            Builder.Append("Create Table If Not Exists SearchHistory (SearchText Text Not Null, Primary Key (SearchText));")
            .Append("Create Table If Not Exists QuickStart (Name Text Not Null, FullPath Text Not Null Collate NoCase, Protocal Text Not Null, Type Text Not Null, Primary Key (Name,FullPath,Protocal,Type));")
            .Append("Create Table If Not Exists Library (Path Text Not Null Collate NoCase, Type Text Not Null, Primary Key (Path));")
            .Append("Create Table If Not Exists PathHistory (Path Text Not Null Collate NoCase, Primary Key (Path));")
            .Append("Create Table If Not Exists BackgroundPicture (FileName Text Not Null, Primary Key (FileName));")
            .Append("Create Table If Not Exists ProgramPicker (FileType Text Not Null, Path Text Not Null Collate NoCase, IsDefault Text Default 'False' Check(IsDefault In ('True','False')), IsRecommanded Text Default 'False' Check(IsRecommanded In ('True','False')), Primary Key(FileType, Path));")
            .Append("Create Table If Not Exists TerminalProfile (Name Text Not Null, Path Text Not Null Collate NoCase, Argument Text Not Null, RunAsAdmin Text Not Null, Primary Key(Name));")
            .Append("Create Table If Not Exists PathConfiguration (Path Text Not Null Collate NoCase, DisplayMode Integer Default 1 Check(DisplayMode In (0,1,2,3,4,5)), SortColumn Text Default 'Name' Check(SortColumn In ('Name','ModifiedTime','Type','Size')), SortDirection Text Default 'Ascending' Check(SortDirection In ('Ascending','Descending')), GroupColumn Text Default 'None' Check(GroupColumn In ('None','Name','ModifiedTime','Type','Size')), GroupDirection Text Default 'Ascending' Check(GroupDirection In ('Ascending','Descending')), Primary Key(Path));")
            .Append("Create Table If Not Exists FileColor (Path Text Not Null Collate NoCase, Color Text Not Null, Primary Key (Path));");

            InitCommand.CommandText = Builder.ToString();
            InitCommand.ExecuteNonQuery();

            if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("DatabaseInit"))
            {
                Builder.Clear();

                string UserCustomString = Enum.GetName(typeof(LibraryType), LibraryType.UserCustom);

                foreach (string LType in Enum.GetNames(typeof(LibraryType)))
                {
                    if (LType != UserCustomString)
                    {
                        Builder.Append($"Insert Or Replace Into Library Values ('{Guid.NewGuid():N}', '{LType}');");
                    }
                }

                foreach (int Index in Enumerable.Range(1, 15))
                {
                    Builder.Append($"Insert Or Replace Into BackgroundPicture Values ('ms-appx:///CustomImage/Picture{Index}.jpg');");
                }

                Builder.Append($"Insert Or Replace Into TerminalProfile Values ('Powershell', '{Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "WindowsPowerShell\\v1.0\\powershell.exe")}', '-NoExit -Command \"Set-Location ''[CurrentLocation]''\"', 'True');")
                .Append($"Insert Or Replace Into TerminalProfile Values ('CMD', '{Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe")}', '/k cd /d [CurrentLocation]', 'True');");

                InitCommand.CommandText = Builder.ToString();
                InitCommand.ExecuteNonQuery();

                InitCommand.CommandText = "Insert Or Replace Into QuickStart Values (@Name,@Path,@Protocal,@Type)";

                IReadOnlyList <(string, string, string, QuickStartType)> DefaultQuickStartList = new List <(string, string, string, QuickStartType)>
                {
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_1"), "ms-appx:///QuickStartImage/MicrosoftStore.png", "ms-windows-store://home", QuickStartType.Application),
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_2"), "ms-appx:///QuickStartImage/Calculator.png", "calculator:", QuickStartType.Application),
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_3"), "ms-appx:///QuickStartImage/Setting.png", "ms-settings:", QuickStartType.Application),
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_4"), "ms-appx:///QuickStartImage/Email.png", "mailto:", QuickStartType.Application),
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_5"), "ms-appx:///QuickStartImage/Calendar.png", "outlookcal:", QuickStartType.Application),
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_6"), "ms-appx:///QuickStartImage/Photos.png", "ms-photos:", QuickStartType.Application),
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_7"), "ms-appx:///QuickStartImage/Weather.png", "msnweather:", QuickStartType.Application),
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_9"), "ms-appx:///HotWebImage/Facebook.png", "https://www.facebook.com/", QuickStartType.WebSite),
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_10"), "ms-appx:///HotWebImage/Instagram.png", "https://www.instagram.com/", QuickStartType.WebSite),
                    (Globalization.GetString("ExtendedSplash_QuickStartItem_Name_11"), "ms-appx:///HotWebImage/Twitter.png", "https://twitter.com", QuickStartType.WebSite)
                };

                foreach ((string Name, string FullPath, string Protocal, QuickStartType Type) in DefaultQuickStartList)
                {
                    InitCommand.Parameters.Clear();
                    InitCommand.Parameters.AddWithValue("@Name", Name);
                    InitCommand.Parameters.AddWithValue("@Path", FullPath);
                    InitCommand.Parameters.AddWithValue("@Protocal", Protocal);
                    InitCommand.Parameters.AddWithValue("@Type", Enum.GetName(typeof(QuickStartType), Type));
                    InitCommand.ExecuteNonQuery();
                }

                ApplicationData.Current.LocalSettings.Values["DatabaseInit"] = true;
            }

            if (ApplicationData.Current.LocalSettings.Values.ContainsKey("RefreshQuickStart"))
            {
                ApplicationData.Current.LocalSettings.Values.Remove("RefreshQuickStart");

                IReadOnlyList <(string, string, QuickStartType)> UpdateArray = new List <(string, string, QuickStartType)>
                {
                    ("ms-appx:///QuickStartImage/MicrosoftStore.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_1"), QuickStartType.Application),
                    ("ms-appx:///QuickStartImage/Calculator.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_2"), QuickStartType.Application),
                    ("ms-appx:///QuickStartImage/Setting.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_3"), QuickStartType.Application),
                    ("ms-appx:///QuickStartImage/Email.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_4"), QuickStartType.Application),
                    ("ms-appx:///QuickStartImage/Calendar.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_5"), QuickStartType.Application),
                    ("ms-appx:///QuickStartImage/Photos.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_6"), QuickStartType.Application),
                    ("ms-appx:///QuickStartImage/Weather.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_7"), QuickStartType.Application),
                    ("ms-appx:///HotWebImage/Facebook.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_9"), QuickStartType.WebSite),
                    ("ms-appx:///HotWebImage/Instagram.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_10"), QuickStartType.WebSite),
                    ("ms-appx:///HotWebImage/Twitter.png", Globalization.GetString("ExtendedSplash_QuickStartItem_Name_11"), QuickStartType.WebSite)
                };

                foreach ((string FullPath, string NewName, QuickStartType Type) in UpdateArray)
                {
                    InitCommand.Parameters.Clear();

                    InitCommand.CommandText = "Select Count(*) From QuickStart Where FullPath = @FullPath";
                    InitCommand.Parameters.AddWithValue("@FullPath", FullPath);

                    if (Convert.ToInt32(InitCommand.ExecuteScalar()) > 0)
                    {
                        InitCommand.Parameters.Clear();

                        InitCommand.CommandText = "Update QuickStart Set Name = @NewName Where FullPath = @FullPath And Type = @Type";
                        InitCommand.Parameters.AddWithValue("@FullPath", FullPath);
                        InitCommand.Parameters.AddWithValue("@NewName", NewName);
                        InitCommand.Parameters.AddWithValue("@Type", Enum.GetName(typeof(QuickStartType), Type));
                        InitCommand.ExecuteNonQuery();
                    }
                }
            }

            Transaction.Commit();
        }
        public async Task ConnectAsync()
        {
            try
            {
                if (AudioConnection != null)
                {
                    AudioConnection.Dispose();
                    AudioConnection = null;
                }

                ActionButtonText    = Globalization.GetString("BluetoothAudio_Button_Text_1");
                ActionButtonEnabled = false;
                Status = Globalization.GetString("BluetoothAudio_Status_2");

                OnPropertyChanged(nameof(ActionButtonEnabled));
                OnPropertyChanged(nameof(ActionButtonText));
                OnPropertyChanged(nameof(Status));

                ConnectionStatusChanged?.Invoke(this, true);

                AudioConnection = AudioPlaybackConnection.TryCreateFromId(Id);

                if (AudioConnection != null)
                {
                    await AudioConnection.StartAsync();

                    AudioPlaybackConnectionOpenResult Result = await AudioConnection.OpenAsync();

                    switch (Result.Status)
                    {
                    case AudioPlaybackConnectionOpenResultStatus.Success:
                    {
                        IsConnected = true;

                        ActionButtonText    = Globalization.GetString("BluetoothAudio_Button_Text_2");
                        Status              = Globalization.GetString("BluetoothAudio_Status_3");
                        ActionButtonEnabled = true;

                        OnPropertyChanged(nameof(ActionButtonEnabled));
                        OnPropertyChanged(nameof(ActionButtonText));
                        OnPropertyChanged(nameof(Status));

                        break;
                    }

                    case AudioPlaybackConnectionOpenResultStatus.RequestTimedOut:
                    {
                        IsConnected = false;

                        ActionButtonText    = Globalization.GetString("BluetoothAudio_Button_Text_1");
                        Status              = Globalization.GetString("BluetoothAudio_Status_4");
                        ActionButtonEnabled = true;

                        OnPropertyChanged(nameof(ActionButtonEnabled));
                        OnPropertyChanged(nameof(ActionButtonText));
                        OnPropertyChanged(nameof(Status));

                        ConnectionStatusChanged?.Invoke(this, false);

                        LogTracer.Log("Connect to AudioPlayback failed for time out");

                        break;
                    }

                    case AudioPlaybackConnectionOpenResultStatus.DeniedBySystem:
                    {
                        IsConnected = false;

                        ActionButtonText    = Globalization.GetString("BluetoothAudio_Button_Text_1");
                        Status              = Globalization.GetString("BluetoothAudio_Status_5");
                        ActionButtonEnabled = true;

                        OnPropertyChanged(nameof(ActionButtonEnabled));
                        OnPropertyChanged(nameof(ActionButtonText));
                        OnPropertyChanged(nameof(Status));

                        ConnectionStatusChanged?.Invoke(this, false);

                        LogTracer.Log("Connect to AudioPlayback failed for being denied by system");

                        break;
                    }

                    case AudioPlaybackConnectionOpenResultStatus.UnknownFailure:
                    {
                        IsConnected = false;

                        ActionButtonText    = Globalization.GetString("BluetoothAudio_Button_Text_1");
                        Status              = Globalization.GetString("BluetoothAudio_Status_6");
                        ActionButtonEnabled = true;

                        OnPropertyChanged(nameof(ActionButtonEnabled));
                        OnPropertyChanged(nameof(ActionButtonText));
                        OnPropertyChanged(nameof(Status));

                        ConnectionStatusChanged?.Invoke(this, false);

                        if (Result.ExtendedError != null)
                        {
                            LogTracer.Log(Result.ExtendedError, "Connect to AudioPlayback failed for unknown reason");
                        }
                        else
                        {
                            LogTracer.Log("Connect to AudioPlayback failed for unknown reason");
                        }

                        break;
                    }
                    }
                }
                else
                {
                    IsConnected = false;

                    ActionButtonText    = Globalization.GetString("BluetoothAudio_Button_Text_1");
                    Status              = Globalization.GetString("BluetoothAudio_Status_7");
                    ActionButtonEnabled = true;

                    OnPropertyChanged(nameof(ActionButtonEnabled));
                    OnPropertyChanged(nameof(ActionButtonText));
                    OnPropertyChanged(nameof(Status));

                    ConnectionStatusChanged?.Invoke(this, false);
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"Unable to create a new {nameof(AudioPlaybackConnection)}");

                IsConnected = false;

                ActionButtonText    = Globalization.GetString("BluetoothAudio_Button_Text_1");
                Status              = Globalization.GetString("BluetoothAudio_Status_7");
                ActionButtonEnabled = true;

                OnPropertyChanged(nameof(ActionButtonEnabled));
                OnPropertyChanged(nameof(ActionButtonText));
                OnPropertyChanged(nameof(Status));

                ConnectionStatusChanged?.Invoke(this, false);
            }
        }
示例#17
0
        /// <summary>
        /// 启动WIFI连接侦听器
        /// </summary>
        public async Task StartToListenRequest()
        {
            if (IsListeningThreadWorking)
            {
                return;
            }

            if (IsDisposed)
            {
                throw new ObjectDisposedException("This Object has been disposed");
            }

            IsListeningThreadWorking = true;

            try
            {
                Listener.Start();

                while (true)
                {
                    HttpListenerContext Context = await Listener.GetContextAsync().ConfigureAwait(false);

                    _ = Task.Factory.StartNew(async(Para) =>
                    {
                        try
                        {
                            HttpListenerContext HttpContext = Para as HttpListenerContext;

                            if (HttpContext.Request.Url.LocalPath.Substring(1) == FilePathMap.Key)
                            {
                                if (await FileSystemStorageItemBase.OpenAsync(FilePathMap.Value) is FileSystemStorageFile ShareFile)
                                {
                                    using (FileStream Stream = await ShareFile.GetFileStreamFromFileAsync(AccessMode.Read))
                                    {
                                        try
                                        {
                                            Context.Response.AddHeader("Pragma", "No-cache");
                                            Context.Response.AddHeader("Cache-Control", "No-cache");
                                            Context.Response.AddHeader("Content-Disposition", $"Attachment;filename={Uri.EscapeDataString(ShareFile.Name)}");
                                            Context.Response.ContentLength64 = Stream.Length;
                                            Context.Response.ContentType     = "application/octet-stream";

                                            Stream.CopyTo(Context.Response.OutputStream);
                                        }
                                        catch (HttpListenerException ex)
                                        {
                                            LogTracer.Log(ex);
                                        }
                                        finally
                                        {
                                            Context.Response.Close();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                string ErrorMessage                = $"<html><head><title>Error 404 Bad Request</title></head><body><p style=\"font-size:50px\">HTTP ERROR 404</p><p style=\"font-size:40px\">{Globalization.GetString("WIFIShare_Error_Web_Content")}</p></body></html>";
                                Context.Response.StatusCode        = 404;
                                Context.Response.StatusDescription = "Bad Request";
                                Context.Response.ContentType       = "text/html";
                                Context.Response.ContentEncoding   = Encoding.UTF8;
                                using (StreamWriter Writer = new StreamWriter(Context.Response.OutputStream, Encoding.UTF8))
                                {
                                    Writer.Write(ErrorMessage);
                                }
                                Context.Response.Close();
                            }
                        }
                        catch (Exception e)
                        {
                            LogTracer.Log(e);
                            ThreadExitedUnexpectly?.Invoke(this, e);
                        }
                    }, Context, Cancellation.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current);
                }
            }
            catch (ObjectDisposedException)
            {
                IsListeningThreadWorking = false;
            }
            catch (Exception e)
            {
                IsListeningThreadWorking = false;
                ThreadExitedUnexpectly?.Invoke(this, e);
            }
            finally
            {
                Cancellation?.Dispose();
                Cancellation = null;
            }
        }
示例#18
0
        private static void SendUpdatableToastWithProgressForTranscode(StorageFile SourceFile, StorageFile DestinationFile)
        {
            try
            {
                string Tag = "TranscodeNotification";

                ToastContent content = new ToastContent()
                {
                    Launch   = "Transcode",
                    Scenario = ToastScenario.Reminder,
                    Visual   = new ToastVisual()
                    {
                        BindingGeneric = new ToastBindingGeneric()
                        {
                            Children =
                            {
                                new AdaptiveText()
                                {
                                    Text = $"{Globalization.GetString("Transcode_Toast_Title")} {SourceFile.Name}"
                                },

                                new AdaptiveProgressBar()
                                {
                                    Title = SourceFile.FileType.Substring(1).ToUpper() + " ⋙⋙⋙⋙ " + DestinationFile.FileType.Substring(1).ToUpper(),
                                    Value = new BindableProgressBarValue("ProgressValue"),
                                    ValueStringOverride = new BindableString("ProgressValueString"),
                                    Status = new BindableString("ProgressStatus")
                                }
                            }
                        }
                    }
                };

                NotificationData Data = new NotificationData
                {
                    SequenceNumber = 0
                };
                Data.Values["ProgressValue"]       = "0";
                Data.Values["ProgressValueString"] = "0%";
                Data.Values["ProgressStatus"]      = Globalization.GetString("Toast_ClickToCancel_Text");

                ToastNotification Toast = new ToastNotification(content.GetXml())
                {
                    Tag  = Tag,
                    Data = Data
                };

                Toast.Activated += (s, e) =>
                {
                    if (s.Tag == "TranscodeNotification")
                    {
                        AVTranscodeCancellation?.Cancel();
                    }
                };

                ToastNotificationManager.CreateToastNotifier().Show(Toast);
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "Toast notification could not be sent");
            }
        }
示例#19
0
        public static async Task ExtractAllAsync(IEnumerable <string> SourceItemGroup, string BaseDestPath, bool CreateFolder, ProgressChangedEventHandler ProgressHandler)
        {
            ulong TotalSize       = 0;
            ulong CurrentPosition = 0;

            List <FileSystemStorageFile> TransformList = new List <FileSystemStorageFile>();

            foreach (string FileItem in SourceItemGroup)
            {
                if (await FileSystemStorageItemBase.OpenAsync(FileItem).ConfigureAwait(false) is FileSystemStorageFile File)
                {
                    TransformList.Add(File);
                    TotalSize += File.SizeRaw;
                }
                else
                {
                    throw new FileNotFoundException("Could not found the file or path is a directory");
                }
            }

            if (TotalSize == 0)
            {
                return;
            }

            foreach (FileSystemStorageFile File in TransformList)
            {
                string DestPath = BaseDestPath;

                //如果解压到独立文件夹,则要额外创建目录
                if (CreateFolder)
                {
                    string NewFolderName = File.Name.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase)
                                                        ? File.Name.Substring(0, File.Name.Length - 7)
                                                        : (File.Name.EndsWith(".tar.bz2", StringComparison.OrdinalIgnoreCase)
                                                                        ? File.Name.Substring(0, File.Name.Length - 8)
                                                                        : Path.GetFileNameWithoutExtension(File.Name));

                    if (string.IsNullOrEmpty(NewFolderName))
                    {
                        NewFolderName = Globalization.GetString("Operate_Text_CreateFolder");
                    }

                    DestPath = await MakeSureCreateFolderHelperAsync(Path.Combine(BaseDestPath, NewFolderName));
                }

                if (File.Name.EndsWith(".gz", StringComparison.OrdinalIgnoreCase) && !File.Name.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase))
                {
                    await ExtractGZipAsync(File, DestPath, (s, e) =>
                    {
                        ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToUInt64(e.ProgressPercentage / 100d * File.SizeRaw)) * 100d / TotalSize), null));
                    });

                    CurrentPosition += Convert.ToUInt64(File.SizeRaw);
                    ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null));
                }
                else if (File.Name.EndsWith(".bz2", StringComparison.OrdinalIgnoreCase) && !File.Name.EndsWith(".tar.bz2", StringComparison.OrdinalIgnoreCase))
                {
                    await ExtractBZip2Async(File, DestPath, (s, e) =>
                    {
                        ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToUInt64(e.ProgressPercentage / 100d * File.SizeRaw)) * 100d / TotalSize), null));
                    });

                    CurrentPosition += Convert.ToUInt64(File.SizeRaw);
                    ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null));
                }
                else
                {
                    ReaderOptions ReadOptions = new ReaderOptions();
                    ReadOptions.ArchiveEncoding.Default = EncodingSetting;

                    using (FileStream InputStream = await File.GetFileStreamFromFileAsync(AccessMode.Read))
                        using (IReader Reader = ReaderFactory.Open(InputStream, ReadOptions))
                        {
                            Dictionary <string, string> DirectoryMap = new Dictionary <string, string>();

                            while (Reader.MoveToNextEntry())
                            {
                                if (Reader.Entry.IsDirectory)
                                {
                                    string DirectoryPath    = Path.Combine(DestPath, Reader.Entry.Key.Replace("/", @"\").TrimEnd('\\'));
                                    string NewDirectoryPath = await MakeSureCreateFolderHelperAsync(DirectoryPath);

                                    if (!DirectoryPath.Equals(NewDirectoryPath, StringComparison.OrdinalIgnoreCase))
                                    {
                                        DirectoryMap.Add(DirectoryPath, NewDirectoryPath);
                                    }
                                }
                                else
                                {
                                    string[] PathList = (Reader.Entry.Key?.Replace("/", @"\")?.Split(@"\")) ?? Array.Empty <string>();

                                    string LastFolder = DestPath;

                                    for (int i = 0; i < PathList.Length - 1; i++)
                                    {
                                        LastFolder = Path.Combine(LastFolder, PathList[i]);

                                        if (DirectoryMap.ContainsKey(LastFolder))
                                        {
                                            LastFolder = DirectoryMap[LastFolder];
                                        }

                                        string NewDirectoryPath = await MakeSureCreateFolderHelperAsync(LastFolder);

                                        if (!LastFolder.Equals(NewDirectoryPath, StringComparison.OrdinalIgnoreCase))
                                        {
                                            DirectoryMap.Add(LastFolder, NewDirectoryPath);
                                            LastFolder = NewDirectoryPath;
                                        }
                                    }

                                    string DestFileName = Path.Combine(LastFolder, PathList.LastOrDefault() ?? Path.GetFileNameWithoutExtension(File.Name));

                                    if (await FileSystemStorageItemBase.CreateAsync(DestFileName, StorageItemTypes.File, CreateOption.GenerateUniqueName).ConfigureAwait(false) is FileSystemStorageFile NewFile)
                                    {
                                        using (FileStream OutputStream = await NewFile.GetFileStreamFromFileAsync(AccessMode.Write))
                                            using (EntryStream EntryStream = Reader.OpenEntryStream())
                                            {
                                                await EntryStream.CopyToAsync(OutputStream, Reader.Entry.Size, (s, e) =>
                                                {
                                                    ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32((CurrentPosition + Convert.ToUInt64(e.ProgressPercentage / 100d * Reader.Entry.CompressedSize)) * 100d / TotalSize), null));
                                                });

                                                CurrentPosition += Convert.ToUInt64(Reader.Entry.CompressedSize);
                                                ProgressHandler?.Invoke(null, new ProgressChangedEventArgs(Convert.ToInt32(CurrentPosition * 100d / TotalSize), null));
                                            }
                                    }
                                }
                            }
                        }
                }
            }
        }
示例#20
0
        /// <summary>
        /// 初始化HardDeviceInfo对象
        /// </summary>
        /// <param name="Device">驱动器文件夹</param>
        /// <param name="Thumbnail">缩略图</param>
        /// <param name="PropertiesRetrieve">额外信息</param>
        public HardDeviceInfo(StorageFolder Device, BitmapImage Thumbnail, IDictionary <string, object> PropertiesRetrieve, DriveType DriveType)
        {
            Folder = Device ?? throw new FileNotFoundException();

            this.Thumbnail = Thumbnail ?? new BitmapImage(new Uri("ms-appx:///Assets/DeviceIcon.png"));
            this.DriveType = DriveType;

            if (PropertiesRetrieve != null)
            {
                if (PropertiesRetrieve.TryGetValue("System.Capacity", out object TotalByteRaw) && TotalByteRaw is ulong TotalByte)
                {
                    this.TotalByte = TotalByte;
                    Capacity       = TotalByte.ToFileSizeDescription();
                }
                else
                {
                    Capacity = Globalization.GetString("UnknownText");
                }

                if (PropertiesRetrieve.TryGetValue("System.FreeSpace", out object FreeByteRaw) && FreeByteRaw is ulong FreeByte)
                {
                    this.FreeByte = FreeByte;
                    FreeSpace     = FreeByte.ToFileSizeDescription();
                }
                else
                {
                    FreeSpace = Globalization.GetString("UnknownText");
                }

                if (PropertiesRetrieve.TryGetValue("System.Volume.FileSystem", out object FileSystemRaw) && FileSystemRaw is string FileSystem)
                {
                    this.FileSystem = FileSystem;
                }
                else
                {
                    this.FileSystem = Globalization.GetString("UnknownText");
                }

                /*
                 * | System.Volume.      | Control Panel                    | manage-bde conversion     | manage-bde     | Get-BitlockerVolume          | Get-BitlockerVolume |
                 * | BitLockerProtection |                                  |                           | protection     | VolumeStatus                 | ProtectionStatus    |
                 * | ------------------- | -------------------------------- | ------------------------- | -------------- | ---------------------------- | ------------------- |
                 * |                   1 | BitLocker on                     | Used Space Only Encrypted | Protection On  | FullyEncrypted               | On                  |
                 * |                   1 | BitLocker on                     | Fully Encrypted           | Protection On  | FullyEncrypted               | On                  |
                 * |                   1 | BitLocker on                     | Fully Encrypted           | Protection On  | FullyEncryptedWipeInProgress | On                  |
                 * |                   2 | BitLocker off                    | Fully Decrypted           | Protection Off | FullyDecrypted               | Off                 |
                 * |                   3 | BitLocker Encrypting             | Encryption In Progress    | Protection Off | EncryptionInProgress         | Off                 |
                 * |                   3 | BitLocker Encryption Paused      | Encryption Paused         | Protection Off | EncryptionSuspended          | Off                 |
                 * |                   4 | BitLocker Decrypting             | Decryption in progress    | Protection Off | DecyptionInProgress          | Off                 |
                 * |                   4 | BitLocker Decryption Paused      | Decryption Paused         | Protection Off | DecryptionSuspended          | Off                 |
                 * |                   5 | BitLocker suspended              | Used Space Only Encrypted | Protection Off | FullyEncrypted               | Off                 |
                 * |                   5 | BitLocker suspended              | Fully Encrypted           | Protection Off | FullyEncrypted               | Off                 |
                 * |                   6 | BitLocker on (Locked)            | Unknown                   | Unknown        | $null                        | Unknown             |
                 * |                   7 |                                  |                           |                |                              |                     |
                 * |                   8 | BitLocker waiting for activation | Used Space Only Encrypted | Protection Off | FullyEncrypted               | Off                 |
                 *
                 * We could use Powershell command: Get-BitLockerVolume -MountPoint C: | Select -ExpandProperty LockStatus -------------->Locked / Unlocked
                 * But powershell might speed too much time to load. So we would not use it
                 */
                if (PropertiesRetrieve.TryGetValue("System.Volume.BitLockerProtection", out object BitlockerStateRaw) && BitlockerStateRaw is int BitlockerState)
                {
                    if (BitlockerState == 6 && Capacity == Globalization.GetString("UnknownText") && FreeSpace == Globalization.GetString("UnknownText"))
                    {
                        IsLockedByBitlocker = true;
                    }
                    else
                    {
                        IsLockedByBitlocker = false;
                    }
                }
                else
                {
                    IsLockedByBitlocker = false;
                }

                if (this.TotalByte != 0)
                {
                    Percent = 1 - this.FreeByte / Convert.ToDouble(this.TotalByte);
                }
                else
                {
                    Percent = 0;
                }
            }
            else
            {
                Capacity   = Globalization.GetString("UnknownText");
                FreeSpace  = Globalization.GetString("UnknownText");
                FileSystem = Globalization.GetString("UnknownText");
                Percent    = 0;
            }
        }
示例#21
0
        public static async Task SetCommandBarFlyoutWithExtraContextMenuItems(this ListViewBase ListControl, CommandBarFlyout Flyout, Point ShowAt)
        {
            if (Flyout == null)
            {
                throw new ArgumentNullException(nameof(Flyout), "Argument could not be null");
            }

            if (Interlocked.Exchange(ref ContextMenuLockResource, 1) == 0)
            {
                try
                {
                    if (ApplicationData.Current.LocalSettings.Values["ContextMenuExtSwitch"] is bool IsExt && !IsExt)
                    {
                        foreach (AppBarElementContainer ExistContainer in Flyout.SecondaryCommands.OfType <AppBarElementContainer>())
                        {
                            Flyout.SecondaryCommands.Remove(ExistContainer);
                        }

                        List <int> SeparatorGroup = Flyout.SecondaryCommands.Select((Item, Index) => (Index, Item)).Where((Group) => Group.Item is AppBarSeparator).Select((Group) => Group.Index).ToList();

                        if (SeparatorGroup.Count == 1)
                        {
                            if (SeparatorGroup[0] == 0)
                            {
                                Flyout.SecondaryCommands.RemoveAt(0);
                            }
                        }
                        else
                        {
                            for (int i = 0; i < SeparatorGroup.Count - 1; i++)
                            {
                                if (Math.Abs(SeparatorGroup[i] - SeparatorGroup[i + 1]) == 1)
                                {
                                    Flyout.SecondaryCommands.RemoveAt(SeparatorGroup[i]);
                                }
                            }
                        }
                    }
                    else
                    {
                        string SelectedPath;

                        if (ListControl.SelectedItems.Count <= 1)
                        {
                            if (ListControl.SelectedItem is FileSystemStorageItemBase Selected)
                            {
                                SelectedPath = Selected.Path;
                            }
                            else if (ListControl.FindParentOfType <FileControl>() is FileControl Control)
                            {
                                if (!string.IsNullOrEmpty(Control.CurrentPresenter.CurrentFolder?.Path))
                                {
                                    SelectedPath = Control.CurrentPresenter.CurrentFolder.Path;
                                }
                                else
                                {
                                    return;
                                }
                            }
                            else
                            {
                                return;
                            }

                            using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController())
                            {
                                List <ContextMenuItem> ExtraMenuItems = await Exclusive.Controller.GetContextMenuItemsAsync(SelectedPath, Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down)).ConfigureAwait(true);

                                foreach (AppBarButton ExtraButton in Flyout.SecondaryCommands.OfType <AppBarButton>().Where((Btn) => Btn.Name == "ExtraButton").ToArray())
                                {
                                    Flyout.SecondaryCommands.Remove(ExtraButton);
                                }

                                foreach (AppBarSeparator Separator in Flyout.SecondaryCommands.OfType <AppBarSeparator>().Where((Sep) => Sep.Name == "CustomSep").ToArray())
                                {
                                    Flyout.SecondaryCommands.Remove(Separator);
                                }

                                if (ExtraMenuItems.Count > 0)
                                {
                                    async void ClickHandler(object sender, RoutedEventArgs args)
                                    {
                                        if (sender is FrameworkElement Btn)
                                        {
                                            if (Btn.Tag is ContextMenuItem MenuItem)
                                            {
                                                Flyout.Hide();
                                                await MenuItem.InvokeAsync().ConfigureAwait(true);
                                            }
                                        }
                                    }

                                    const short ShowExtNum = 2;

                                    int Index = Flyout.SecondaryCommands.IndexOf(Flyout.SecondaryCommands.OfType <AppBarSeparator>().FirstOrDefault()) + 1;

                                    if (ExtraMenuItems.Count > ShowExtNum)
                                    {
                                        Flyout.SecondaryCommands.Insert(Index, new AppBarSeparator {
                                            Name = "CustomSep"
                                        });

                                        foreach (ContextMenuItem AddItem in ExtraMenuItems.Take(ShowExtNum))
                                        {
                                            Flyout.SecondaryCommands.Insert(Index, await AddItem.GenerateUIButtonAsync(ClickHandler).ConfigureAwait(true));
                                        }

                                        AppBarButton MoreItem = new AppBarButton
                                        {
                                            Label    = Globalization.GetString("CommandBarFlyout_More_Item"),
                                            Icon     = new SymbolIcon(Symbol.More),
                                            Name     = "ExtraButton",
                                            MinWidth = 250
                                        };

                                        MenuFlyout MoreFlyout = new MenuFlyout();

                                        await ContextMenuItem.GenerateSubMenuItemsAsync(MoreFlyout.Items, ExtraMenuItems.Skip(ShowExtNum).ToArray(), ClickHandler).ConfigureAwait(true);

                                        MoreItem.Flyout = MoreFlyout;

                                        Flyout.SecondaryCommands.Insert(Index + ShowExtNum, MoreItem);
                                    }
                                    else
                                    {
                                        foreach (ContextMenuItem AddItem in ExtraMenuItems)
                                        {
                                            Flyout.SecondaryCommands.Insert(Index, await AddItem.GenerateUIButtonAsync(ClickHandler).ConfigureAwait(true));
                                        }

                                        Flyout.SecondaryCommands.Insert(Index + ExtraMenuItems.Count, new AppBarSeparator {
                                            Name = "CustomSep"
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
示例#22
0
        /// <summary>
        /// 提供音视频转码
        /// </summary>
        /// <param name="SourceFile">源文件</param>
        /// <param name="DestinationFile">目标文件</param>
        /// <param name="MediaTranscodeEncodingProfile">转码编码</param>
        /// <param name="MediaTranscodeQuality">转码质量</param>
        /// <param name="SpeedUp">是否启用硬件加速</param>
        /// <returns></returns>
        public static Task TranscodeFromAudioOrVideoAsync(StorageFile SourceFile, StorageFile DestinationFile, string MediaTranscodeEncodingProfile, string MediaTranscodeQuality, bool SpeedUp)
        {
            return Task.Factory.StartNew((ob) =>
            {
                IsAnyTransformTaskRunning = true;

                AVTranscodeCancellation = new CancellationTokenSource();

                var Para = (ValueTuple<StorageFile, StorageFile, string, string, bool>)ob;

                MediaTranscoder Transcoder = new MediaTranscoder
                {
                    HardwareAccelerationEnabled = true,
                    VideoProcessingAlgorithm = Para.Item5 ? MediaVideoProcessingAlgorithm.Default : MediaVideoProcessingAlgorithm.MrfCrf444
                };

                try
                {
                    MediaEncodingProfile Profile = null;
                    VideoEncodingQuality VideoQuality = default;
                    AudioEncodingQuality AudioQuality = default;

                    switch (Para.Item4)
                    {
                        case "UHD2160p":
                            VideoQuality = VideoEncodingQuality.Uhd2160p;
                            break;
                        case "QVGA":
                            VideoQuality = VideoEncodingQuality.Qvga;
                            break;
                        case "HD1080p":
                            VideoQuality = VideoEncodingQuality.HD1080p;
                            break;
                        case "HD720p":
                            VideoQuality = VideoEncodingQuality.HD720p;
                            break;
                        case "WVGA":
                            VideoQuality = VideoEncodingQuality.Wvga;
                            break;
                        case "VGA":
                            VideoQuality = VideoEncodingQuality.Vga;
                            break;
                        case "High":
                            AudioQuality = AudioEncodingQuality.High;
                            break;
                        case "Medium":
                            AudioQuality = AudioEncodingQuality.Medium;
                            break;
                        case "Low":
                            AudioQuality = AudioEncodingQuality.Low;
                            break;
                    }

                    switch (Para.Item3)
                    {
                        case "MKV":
                            Profile = MediaEncodingProfile.CreateHevc(VideoQuality);
                            break;
                        case "MP4":
                            Profile = MediaEncodingProfile.CreateMp4(VideoQuality);
                            break;
                        case "WMV":
                            Profile = MediaEncodingProfile.CreateWmv(VideoQuality);
                            break;
                        case "AVI":
                            Profile = MediaEncodingProfile.CreateAvi(VideoQuality);
                            break;
                        case "MP3":
                            Profile = MediaEncodingProfile.CreateMp3(AudioQuality);
                            break;
                        case "ALAC":
                            Profile = MediaEncodingProfile.CreateAlac(AudioQuality);
                            break;
                        case "WMA":
                            Profile = MediaEncodingProfile.CreateWma(AudioQuality);
                            break;
                        case "M4A":
                            Profile = MediaEncodingProfile.CreateM4a(AudioQuality);
                            break;
                    }

                    PrepareTranscodeResult Result = Transcoder.PrepareFileTranscodeAsync(Para.Item1, Para.Item2, Profile).AsTask().Result;
                    if (Result.CanTranscode)
                    {
                        SendUpdatableToastWithProgressForTranscode(Para.Item1, Para.Item2);
                        Progress<double> TranscodeProgress = new Progress<double>((CurrentValue) =>
                        {
                            NotificationData Data = new NotificationData();
                            Data.SequenceNumber = 0;
                            Data.Values["ProgressValue"] = (Math.Ceiling(CurrentValue) / 100).ToString();
                            Data.Values["ProgressValueString"] = Convert.ToInt32(CurrentValue) + "%";

                            ToastNotificationManager.CreateToastNotifier().Update(Data, "TranscodeNotification");
                        });

                        Result.TranscodeAsync().AsTask(AVTranscodeCancellation.Token, TranscodeProgress).Wait();

                        ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = "Success";
                    }
                    else
                    {
                        ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = "NotSupport";
                        Para.Item2.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait();
                    }
                }
                catch (AggregateException)
                {
                    ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = "Cancel";
                    Para.Item2.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait();
                }
                catch (Exception e)
                {
                    ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] = e.Message;
                    Para.Item2.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait();
                }
            }, (SourceFile, DestinationFile, MediaTranscodeEncodingProfile, MediaTranscodeQuality, SpeedUp), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Current).ContinueWith((task, ob) =>
               {
                   AVTranscodeCancellation.Dispose();
                   AVTranscodeCancellation = null;

                   var Para = (ValueTuple<StorageFile, StorageFile>)ob;

                   if (ApplicationData.Current.LocalSettings.Values["MediaTranscodeStatus"] is string ExcuteStatus)
                   {
                       CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                       {
                           switch (ExcuteStatus)
                           {
                               case "Success":
                                   TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Transcode_Success"), 5000);
                                   ShowTranscodeCompleteNotification(Para.Item1, Para.Item2);
                                   break;
                               case "Cancel":
                                   TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Transcode_Cancel"), 5000);
                                   ShowTranscodeCancelNotification();
                                   break;
                               case "NotSupport":
                                   TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Transcode_NotSupport"), 5000);
                                   break;
                               default:
                                   TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Transcode_Failure") + ExcuteStatus, 5000);
                                   break;
                           }
                       }).AsTask().Wait();
                   }

                   IsAnyTransformTaskRunning = false;

               }, (SourceFile, DestinationFile), TaskScheduler.Current);
        }
示例#23
0
 /// <summary>
 /// 初始化FeedBackItem
 /// </summary>
 /// <param name="UserName">用户名</param>
 /// <param name="Title">标题</param>
 /// <param name="Suggestion">建议或反馈内容</param>
 /// <param name="LikeNum">支持的人数</param>
 /// <param name="DislikeNum">反对的人数</param>
 /// <param name="UserID">用户ID</param>
 /// <param name="GUID">反馈的GUID</param>
 /// <param name="UserVoteAction">指示支持或反对</param>
 public FeedBackItem(string UserName, string Title, string Suggestion, string LikeNum, string DislikeNum, string UserID, string GUID, string UserVoteAction = "=")
 {
     this.UserName       = UserName;
     this.Title          = Title;
     this.Suggestion     = Suggestion;
     this.LikeNum        = LikeNum;
     this.DislikeNum     = DislikeNum;
     this.UserID         = UserID;
     this.GUID           = GUID;
     this.UserVoteAction = UserVoteAction;
     SupportDescription  = $"({LikeNum} {Globalization.GetString("FeedBackItem_SupportDescription_Positive")} , {DislikeNum} {Globalization.GetString("FeedBackItem_SupportDescription_Negative")})";
 }
示例#24
0
        /// <summary>
        /// 将指定的视频文件裁剪后保存值新文件中
        /// </summary>
        /// <param name="DestinationFile">新文件</param>
        /// <param name="Composition">片段</param>
        /// <param name="EncodingProfile">编码</param>
        /// <param name="TrimmingPreference">裁剪精度</param>
        /// <returns></returns>
        public static Task GenerateCroppedVideoFromOriginAsync(StorageFile DestinationFile, MediaComposition Composition, MediaEncodingProfile EncodingProfile, MediaTrimmingPreference TrimmingPreference)
        {
            return Task.Factory.StartNew((obj) =>
            {
                IsAnyTransformTaskRunning = true;

                AVTranscodeCancellation = new CancellationTokenSource();

                var Para = (ValueTuple<StorageFile, MediaComposition, MediaEncodingProfile, MediaTrimmingPreference>)obj;

                SendUpdatableToastWithProgressForCropVideo(Para.Item1);

                Progress<double> CropVideoProgress = new Progress<double>((CurrentValue) =>
                {
                    string Tag = "CropVideoNotification";

                    var data = new NotificationData
                    {
                        SequenceNumber = 0
                    };
                    data.Values["ProgressValue"] = Math.Round(CurrentValue / 100, 2, MidpointRounding.AwayFromZero).ToString();
                    data.Values["ProgressValueString"] = Convert.ToInt32(CurrentValue) + "%";

                    ToastNotificationManager.CreateToastNotifier().Update(data, Tag);
                });

                try
                {
                    Para.Item2.RenderToFileAsync(Para.Item1, Para.Item4, Para.Item3).AsTask(AVTranscodeCancellation.Token, CropVideoProgress).Wait();
                    ApplicationData.Current.LocalSettings.Values["MediaCropStatus"] = "Success";
                }
                catch (AggregateException)
                {
                    ApplicationData.Current.LocalSettings.Values["MediaCropStatus"] = "Cancel";
                    Para.Item1.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait();
                }
                catch (Exception e)
                {
                    ApplicationData.Current.LocalSettings.Values["MediaCropStatus"] = e.Message;
                    Para.Item1.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait();
                }

            }, (DestinationFile, Composition, EncodingProfile, TrimmingPreference), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Current).ContinueWith((task) =>
               {
                   CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                   {

                       switch (ApplicationData.Current.LocalSettings.Values["MediaCropStatus"].ToString())
                       {
                           case "Success":
                               {
                                   TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Crop_Success"), 5000);
                                   ShowCropCompleteNotification();
                                   break;
                               }
                           case "Cancel":
                               {
                                   TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Crop_Cancel"), 5000);
                                   ShowCropCancelNotification();
                                   break;
                               }
                           default:
                               {
                                   TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Crop_Error"), 5000);
                                   break;
                               }
                       }
                   }).AsTask().Wait();

                   IsAnyTransformTaskRunning = false;

               }, TaskScheduler.Current);
        }
示例#25
0
        public static async Task <ProgramPickerItem> CreateAsync(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);
            }

            if (await ExecuteFile.GetThumbnailRawStreamAsync() is IRandomAccessStream RAStream)
            {
                BitmapImage Logo = new BitmapImage();
                await Logo.SetSourceAsync(RAStream);

                return(new ProgramPickerItem(Logo, string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path));
            }
            else
            {
                return(new ProgramPickerItem(string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName, Globalization.GetString("Application_Admin_Name"), ExecuteFile.Path));
            }
        }