示例#1
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) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).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) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).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) =>
                                {
                                    CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                                    {
                                        Model.UpdateProgress(e.ProgressPercentage);
                                    }).AsTask().Wait();
                                }).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) =>
                                        {
                                            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, true, (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 (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 (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) => 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 (UnauthorizedAccessException)
                    {
                        CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                            {
                                Model.UpdateStatus(OperationStatus.Error, Globalization.GetString("QueueDialog_UnauthorizedDecompression_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);
            }
        }
示例#2
0
        private static void QueueProcessHandler()
        {
            while (true)
            {
                if (OpeartionQueue.IsEmpty)
                {
                    QueueProcessSleepLocker.WaitOne();
                }

                try
                {
                    while (OpeartionQueue.TryDequeue(out OperationListBaseModel Model))
                    {
Retry:
                        if (Model.Status == OperationStatus.Cancel)
                        {
                            continue;
                        }

                        switch (Model)
                        {
                        case OperationListCompressionModel:
                        case OperationListDecompressionModel:
                        {
                            if (AllowParalledExecution)
                            {
                                Thread SubThread = new Thread((input) =>
                                    {
                                        if (input is OperationListBaseModel Model)
                                        {
                                            ExecuteTaskCore(Model);
                                        }
                                    });

                                SubThread.Start(Model);
                            }
                            else
                            {
                                ExecuteTaskCore(Model);
                            }

                            break;
                        }

                        default:
                        {
                            if (FullTrustProcessController.AvailableControllerNum > FullTrustProcessController.DynamicBackupProcessNum)
                            {
                                FullTrustProcessController.ExclusiveUsage Exclusive = FullTrustProcessController.GetAvailableController().Result;

                                if (FullTrustProcessController.AvailableControllerNum >= FullTrustProcessController.DynamicBackupProcessNum)
                                {
                                    if (AllowParalledExecution)
                                    {
                                        Thread SubThread = new Thread((input) =>
                                            {
                                                if (input is (FullTrustProcessController.ExclusiveUsage Exclusive, OperationListBaseModel Model))
                                                {
                                                    try
                                                    {
                                                        ExecuteTaskCore(Exclusive, Model);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        LogTracer.Log(ex, "A subthread in Task List threw an exception");
                                                    }
                                                    finally
                                                    {
                                                        Exclusive.Dispose();
                                                    }
                                                }
                                            })
                                        {
                                            IsBackground = true,
                                            Priority     = ThreadPriority.Normal
                                        };

                                        SubThread.Start((Exclusive, Model));
                                    }
                                    else
                                    {
                                        try
                                        {
                                            ExecuteTaskCore(Exclusive, Model);
                                        }
                                        catch (Exception ex)
                                        {
                                            LogTracer.Log(ex, "A subthread in Task List threw an exception");
                                        }
                                        finally
                                        {
                                            Exclusive.Dispose();
                                        }
                                    }
                                }
                                else
                                {
                                    Exclusive.Dispose();
                                    //Give up execute, make sure the operation will not use DynamicBackupProcess
                                    goto Retry;
                                }
                            }
                            else
                            {
                                Thread.Sleep(1000);
                                goto Retry;
                            }

                            break;
                        }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "QueueOperation threw an exception");
                }
            }
        }
        public virtual async Task <ulong> GetFolderSizeAsync(CancellationToken CancelToken = default)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(await Task.Run(() =>
                {
                    return WIN_Native_API.CalulateSize(Path, CancelToken);
                }));
            }
            else
            {
                try
                {
                    LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                    if (await GetStorageItemAsync() is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Deep,
                            IndexerOption = IndexerOption.DoNotUseIndexer
                        };
                        Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size" });

                        StorageFileQueryResult Query = Folder.CreateFileQueryWithOptions(Options);

                        ulong TotalSize = 0;

                        for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += 25)
                        {
                            IReadOnlyList <StorageFile> ReadOnlyItemList = await Query.GetFilesAsync(Index, 25);

                            if (ReadOnlyItemList.Count > 0)
                            {
                                foreach (StorageFile File in ReadOnlyItemList)
                                {
                                    TotalSize += await File.GetSizeRawDataAsync().ConfigureAwait(false);

                                    if (CancelToken.IsCancellationRequested)
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        return(TotalSize);
                    }
                    else
                    {
                        return(0);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"{nameof(GetFolderSizeAsync)} failed for uwp API");
                    return(0);
                }
            }
        }
示例#4
0
        public static async Task <FileSystemStorageFile> GetBingPictureAsync()
        {
            string Path = await GetDailyPhotoPath().ConfigureAwait(false);

            if (await FileSystemStorageItemBase.OpenAsync(System.IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, "BingDailyPicture.jpg")) is FileSystemStorageFile ExistFile)
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(Path))
                    {
                        return(ExistFile);
                    }

                    if (await CheckIfNeedToUpdate())
                    {
                        if (await FileSystemStorageItemBase.CreateAsync(System.IO.Path.Combine(ApplicationData.Current.TemporaryFolder.Path, $"BingDailyPicture_Cache_[{DateTime.Now:yyyy-MM-dd HH-mm-ss}].jpg"), StorageItemTypes.File, CreateOption.GenerateUniqueName) is FileSystemStorageFile TempFile)
                        {
                            using (FileStream TempFileStream = await TempFile.GetFileStreamFromFileAsync(AccessMode.ReadWrite))
                            {
                                HttpWebRequest Request = WebRequest.CreateHttp(new Uri($"https://www.bing.com{Path}"));
                                Request.Timeout          = 10000;
                                Request.ReadWriteTimeout = 10000;

                                using (WebResponse Response = await Request.GetResponseAsync())
                                    using (Stream ResponseStream = Response.GetResponseStream())
                                    {
                                        await ResponseStream.CopyToAsync(TempFileStream);
                                    }

                                using (Stream FileStream = await ExistFile.GetFileStreamFromFileAsync(AccessMode.Read))
                                    using (MD5 MD5Alg1 = MD5.Create())
                                        using (MD5 MD5Alg2 = MD5.Create())
                                        {
                                            Task <string> CalTask1 = MD5Alg1.GetHashAsync(FileStream);
                                            Task <string> CalTask2 = MD5Alg2.GetHashAsync(TempFileStream);

                                            string[] ResultArray = await Task.WhenAll(CalTask1, CalTask2);

                                            if (ResultArray[0] == ResultArray[1])
                                            {
                                                return(ExistFile);
                                            }
                                        }

                                TempFileStream.Seek(0, SeekOrigin.Begin);

                                using (StorageStreamTransaction Transaction = await ExistFile.GetTransactionStreamFromFileAsync())
                                {
                                    await TempFileStream.CopyToAsync(Transaction.Stream.AsStreamForWrite());

                                    await Transaction.CommitAsync();
                                }
                            }
                        }
                        else
                        {
                            LogTracer.Log($"Could not create temp file as needed in {nameof(GetBingPictureAsync)}");
                        }

                        return(ExistFile);
                    }
                    else
                    {
                        return(ExistFile);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"An error was threw in {nameof(GetBingPictureAsync)}");
                    return(ExistFile);
                }
            }
            else
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(Path))
                    {
                        return(null);
                    }

                    if (await FileSystemStorageItemBase.CreateAsync(System.IO.Path.Combine(ApplicationData.Current.TemporaryFolder.Path, $"BingDailyPicture_Cache_[{DateTime.Now:yyyy-MM-dd HH-mm-ss}].jpg"), StorageItemTypes.File, CreateOption.GenerateUniqueName) is FileSystemStorageFile TempFile)
                    {
                        using (Stream TempFileStream = await TempFile.GetFileStreamFromFileAsync(AccessMode.ReadWrite))
                        {
                            HttpWebRequest Request = WebRequest.CreateHttp(new Uri($"https://www.bing.com{Path}"));
                            Request.Timeout          = 10000;
                            Request.ReadWriteTimeout = 10000;

                            using (WebResponse Response = await Request.GetResponseAsync())
                                using (Stream ResponseStream = Response.GetResponseStream())
                                {
                                    await ResponseStream.CopyToAsync(TempFileStream);
                                }

                            if (await FileSystemStorageItemBase.CreateAsync(System.IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, "BingDailyPicture.jpg"), StorageItemTypes.File, CreateOption.ReplaceExisting) is FileSystemStorageFile BingDailyPictureFile)
                            {
                                using (StorageStreamTransaction Transaction = await BingDailyPictureFile.GetTransactionStreamFromFileAsync())
                                {
                                    TempFileStream.Seek(0, SeekOrigin.Begin);
                                    await TempFileStream.CopyToAsync(Transaction.Stream.AsStreamForWrite());

                                    await Transaction.CommitAsync();
                                }

                                return(BingDailyPictureFile);
                            }
                            else
                            {
                                LogTracer.Log($"Could not create BingPicture file as needed in {nameof(GetBingPictureAsync)}");
                                return(null);
                            }
                        }
                    }
                    else
                    {
                        LogTracer.Log($"Could not create temp file as needed in {nameof(GetBingPictureAsync)}");
                        return(null);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"An error was threw in {nameof(GetBingPictureAsync)}");
                    return(null);
                }
            }
        }
示例#5
0
        /// <summary>
        /// 将指定的视频文件合并并产生新文件
        /// </summary>
        /// <param name="DestinationFile">新文件</param>
        /// <param name="Composition">片段</param>
        /// <param name="EncodingProfile">编码</param>
        /// <returns></returns>
        public static Task GenerateMergeVideoFromOriginAsync(StorageFile DestinationFile, MediaComposition Composition, MediaEncodingProfile EncodingProfile)
        {
            return(Task.Factory.StartNew((ob) =>
            {
                IsAnyTransformTaskRunning = true;

                AVTranscodeCancellation = new CancellationTokenSource();

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

                SendUpdatableToastWithProgressForMergeVideo();
                Progress <double> CropVideoProgress = new Progress <double>((CurrentValue) =>
                {
                    try
                    {
                        string Tag = "MergeVideoNotification";

                        NotificationData 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);
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "Toast notification could not be sent");
                    }
                });

                try
                {
                    Para.Item2.RenderToFileAsync(Para.Item1, MediaTrimmingPreference.Precise, Para.Item3).AsTask(AVTranscodeCancellation.Token, CropVideoProgress).Wait();
                    ApplicationData.Current.LocalSettings.Values["MediaMergeStatus"] = "Success";
                }
                catch (AggregateException)
                {
                    ApplicationData.Current.LocalSettings.Values["MediaMergeStatus"] = "Cancel";
                    Para.Item1.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait();
                }
                catch (Exception e)
                {
                    ApplicationData.Current.LocalSettings.Values["MediaMergeStatus"] = e.Message;
                    Para.Item1.DeleteAsync(StorageDeleteOption.PermanentDelete).AsTask().Wait();
                }
            }, (DestinationFile, Composition, EncodingProfile), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Current).ContinueWith((task) =>
            {
                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    switch (ApplicationData.Current.LocalSettings.Values["MediaMergeStatus"].ToString())
                    {
                    case "Success":
                        {
                            TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Merge_Success"), 5000);
                            ShowMergeCompleteNotification();
                            break;
                        }

                    case "Cancel":
                        {
                            TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Merge_Cancel"), 5000);
                            ShowMergeCancelNotification();
                            break;
                        }

                    default:
                        {
                            TabViewContainer.ThisPage.Notification.Show(Globalization.GetString("GeneralTransformer_Merge_Error"), 5000);
                            break;
                        }
                    }
                }).AsTask().Wait();

                IsAnyTransformTaskRunning = false;
            }, TaskScheduler.Current));
        }
        private void View_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            if (IsEnabled && e.Pointer.PointerDeviceType == PointerDeviceType.Mouse && e.GetCurrentPoint(View).Properties.IsLeftButtonPressed)
            {
                if (Interlocked.Exchange(ref Locker, 1) == 0)
                {
                    try
                    {
                        Point RelativeEndPoint = e.GetCurrentPoint(View).Position;
                        SrcollIfNeed(RelativeEndPoint);

                        Point AbsEndPoint        = new Point(RelativeEndPoint.X + InnerScrollView.HorizontalOffset, RelativeEndPoint.Y + InnerScrollView.VerticalOffset);
                        Point RelativeStartPoint = new Point(AbsStartPoint.X - InnerScrollView.HorizontalOffset, AbsStartPoint.Y - InnerScrollView.VerticalOffset);

                        DrawRectangleInCanvas(RelativeStartPoint, RelativeEndPoint);

                        if (Math.Abs(RelativeStartPoint.X - RelativeEndPoint.X) >= 20 && Math.Abs(RelativeStartPoint.Y - RelativeEndPoint.Y) >= 20)
                        {
                            List <FileSystemStorageItemBase> VisibleList = new List <FileSystemStorageItemBase>();

                            if (View is ListView)
                            {
                                ItemsStackPanel VirtualPanel = View.ItemsPanelRoot as ItemsStackPanel;

                                for (int i = VirtualPanel.FirstVisibleIndex; i <= VirtualPanel.LastVisibleIndex; i++)
                                {
                                    VisibleList.Add(View.Items[i] as FileSystemStorageItemBase);
                                }
                            }
                            else
                            {
                                ItemsWrapGrid VirtualPanel = View.ItemsPanelRoot as ItemsWrapGrid;

                                for (int i = VirtualPanel.FirstVisibleIndex; i <= VirtualPanel.LastVisibleIndex; i++)
                                {
                                    VisibleList.Add(View.Items[i] as FileSystemStorageItemBase);
                                }
                            }

                            foreach (FileSystemStorageItemBase Item in VisibleList.Except(AbsItemLocationRecord.Select((Rec) => Rec.Key)))
                            {
                                if (View.ContainerFromItem(Item) is SelectorItem Selector)
                                {
                                    AbsItemLocationRecord.Add(new KeyValuePair <FileSystemStorageItemBase, Rect>(Item, Selector.TransformToVisual(View).TransformBounds(new Rect(InnerScrollView.HorizontalOffset, InnerScrollView.VerticalOffset, Selector.ActualWidth, Selector.ActualHeight))));
                                }
                            }

                            Rect AbsBoxSelectionRect = new Rect(Math.Min(AbsStartPoint.X, AbsEndPoint.X), Math.Min(AbsStartPoint.Y, AbsEndPoint.Y), Math.Abs(AbsStartPoint.X - AbsEndPoint.X), Math.Abs(AbsStartPoint.Y - AbsEndPoint.Y));

                            foreach (KeyValuePair <FileSystemStorageItemBase, Rect> Pair in AbsItemLocationRecord)
                            {
                                Rect Intersect = RectHelper.Intersect(AbsBoxSelectionRect, Pair.Value);

                                if (!Intersect.IsEmpty && Intersect.Width > 0 && Intersect.Height > 0)
                                {
                                    if (!View.SelectedItems.Contains(Pair.Key))
                                    {
                                        View.SelectedItems.Add(Pair.Key);
                                    }
                                }
                                else
                                {
                                    View.SelectedItems.Remove(Pair.Key);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex);
                    }
                    finally
                    {
                        _ = Interlocked.Exchange(ref Locker, 0);
                    }
                }
            }
        }
示例#7
0
        public static async Task <StorageFile> UpdateBingPicture()
        {
            string Path = await GetDailyPhotoPath().ConfigureAwait(false);

            if ((await ApplicationData.Current.LocalFolder.TryGetItemAsync("BingDailyPicture.jpg")) is StorageFile ExistFile)
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(Path))
                    {
                        return(ExistFile);
                    }

                    if (await CheckIfNeedToUpdate().ConfigureAwait(false))
                    {
                        StorageFile TempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync($"BingDailyPicture_Cache_[{DateTime.Now:yyyy-MM-dd HH-mm-ss}].jpg", CreationCollisionOption.GenerateUniqueName);

                        using (Stream TempFileStream = (await TempFile.OpenAsync(FileAccessMode.ReadWrite)).AsStream())
                        {
                            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(new Uri($"https://www.bing.com{Path}"));

                            using (WebResponse Response = await Request.GetResponseAsync().ConfigureAwait(false))
                                using (Stream ResponseStream = Response.GetResponseStream())
                                {
                                    await ResponseStream.CopyToAsync(TempFileStream).ConfigureAwait(false);
                                }

                            using (Stream FileStream = await ExistFile.OpenStreamForReadAsync().ConfigureAwait(false))
                            {
                                if (FileStream.ComputeMD5Hash() == TempFileStream.ComputeMD5Hash())
                                {
                                    return(ExistFile);
                                }
                            }

                            using (StorageStreamTransaction Transaction = await ExistFile.OpenTransactedWriteAsync())
                            {
                                TempFileStream.Seek(0, SeekOrigin.Begin);
                                await TempFileStream.CopyToAsync(Transaction.Stream.AsStreamForWrite()).ConfigureAwait(false);

                                await Transaction.CommitAsync();
                            }
                        }

                        return(ExistFile);
                    }
                    else
                    {
                        return(ExistFile);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"An error was threw in {nameof(UpdateBingPicture)}");
                    return(ExistFile);
                }
            }
            else
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(Path))
                    {
                        return(null);
                    }

                    StorageFile TempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync($"BingDailyPicture_Cache_[{DateTime.Now:yyyy-MM-dd HH-mm-ss}].jpg", CreationCollisionOption.GenerateUniqueName);

                    using (Stream TempFileStream = (await TempFile.OpenAsync(FileAccessMode.ReadWrite)).AsStream())
                    {
                        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(new Uri($"https://www.bing.com{Path}"));

                        using (WebResponse Response = await Request.GetResponseAsync().ConfigureAwait(false))
                            using (Stream ResponseStream = Response.GetResponseStream())
                            {
                                await ResponseStream.CopyToAsync(TempFileStream).ConfigureAwait(false);
                            }

                        StorageFile BingDailyPictureFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("BingDailyPicture.jpg", CreationCollisionOption.ReplaceExisting);

                        using (StorageStreamTransaction Transaction = await BingDailyPictureFile.OpenTransactedWriteAsync())
                        {
                            TempFileStream.Seek(0, SeekOrigin.Begin);
                            await TempFileStream.CopyToAsync(Transaction.Stream.AsStreamForWrite()).ConfigureAwait(false);

                            await Transaction.CommitAsync();
                        }

                        return(BingDailyPictureFile);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"An error was threw in {nameof(UpdateBingPicture)}");
                    return(null);
                }
            }
        }
        public virtual async Task <List <FileSystemStorageItemBase> > GetChildItemsAsync(bool IncludeHiddenItems, bool IncludeSystemItem, uint MaxNumLimit = uint.MaxValue, ItemFilters Filter = ItemFilters.File | ItemFilters.Folder)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(WIN_Native_API.GetStorageItems(Path, IncludeHiddenItems, IncludeSystemItem, MaxNumLimit, Filter));
            }
            else
            {
                LogTracer.Log($"Native API could not enum subitems in path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    if (await GetStorageItemAsync() is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Shallow,
                            IndexerOption = IndexerOption.DoNotUseIndexer
                        };
                        Options.SetThumbnailPrefetch(ThumbnailMode.ListView, 150, ThumbnailOptions.UseCurrentScale);
                        Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size", "System.DateModified" });

                        StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                        List <FileSystemStorageItemBase> Result = new List <FileSystemStorageItemBase>();

                        for (uint i = 0; ; i += 25)
                        {
                            IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(i, 25);

                            if (ReadOnlyItemList.Count > 0)
                            {
                                foreach (IStorageItem Item in ReadOnlyItemList.Where((Item) => (Item.IsOfType(StorageItemTypes.Folder) && Filter.HasFlag(ItemFilters.Folder)) || (Item.IsOfType(StorageItemTypes.File) && Filter.HasFlag(ItemFilters.File))))
                                {
                                    if (Result.Count >= MaxNumLimit)
                                    {
                                        return(Result);
                                    }

                                    if (Item is StorageFolder SubFolder)
                                    {
                                        Result.Add(new FileSystemStorageFolder(SubFolder, await SubFolder.GetModifiedTimeAsync()));
                                    }
                                    else if (Item is StorageFile SubFile)
                                    {
                                        Result.Add(await CreateFromStorageItemAsync(SubFile));
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        return(Result);
                    }
                    else
                    {
                        return(new List <FileSystemStorageItemBase>(0));
                    }
                }
                catch
                {
                    LogTracer.Log($"UWP API could not enum subitems in path: \"{Path}\"");
                    return(new List <FileSystemStorageItemBase>(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, ItemFilters.File).ConfigureAwait(true) is FileSystemStorageItemBase ShareFile)
                                {
                                    using (FileStream Stream = ShareFile.GetFileStreamFromFile(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;
            }
        }
        public static async Task LoadDriveAsync(bool IsRefresh = false)
        {
            if (Interlocked.Exchange(ref LoadDriveLockResource, 1) == 0)
            {
                try
                {
                    if (!IsDriveLoaded || IsRefresh)
                    {
                        IsDriveLoaded = true;

                        foreach (DriveInfo Drive in DriveInfo.GetDrives().Where((Drives) => Drives.DriveType == DriveType.Fixed || Drives.DriveType == DriveType.Removable || Drives.DriveType == DriveType.Network)
                                 .Where((NewItem) => DriveList.All((Item) => !Item.Path.Equals(NewItem.RootDirectory.FullName, StringComparison.OrdinalIgnoreCase))))
                        {
                            try
                            {
                                StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(Drive.RootDirectory.FullName);

                                if (DriveList.All((Item) => (string.IsNullOrEmpty(Item.Path) || string.IsNullOrEmpty(Folder.Path)) ? !Item.Name.Equals(Folder.Name, StringComparison.OrdinalIgnoreCase) : !Item.Path.Equals(Folder.Path, StringComparison.OrdinalIgnoreCase)))
                                {
                                    DriveList.Add(await DriveDataBase.CreateAsync(Folder, Drive.DriveType));
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, $"Hide the device \"{Drive.RootDirectory.FullName}\" for error");
                            }
                        }

                        foreach (DeviceInformation Drive in await DeviceInformation.FindAllAsync(StorageDevice.GetDeviceSelector()))
                        {
                            try
                            {
                                StorageFolder Folder = StorageDevice.FromId(Drive.Id);

                                if (DriveList.All((Item) => (string.IsNullOrEmpty(Item.Path) || string.IsNullOrEmpty(Folder.Path)) ? !Item.Name.Equals(Folder.Name, StringComparison.OrdinalIgnoreCase) : !Item.Path.Equals(Folder.Path, StringComparison.OrdinalIgnoreCase)))
                                {
                                    DriveList.Add(await DriveDataBase.CreateAsync(Folder, DriveType.Removable));
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, $"Hide the device for error");
                            }
                        }

                        foreach (StorageFolder Folder in await GetWslDriveAsync())
                        {
                            try
                            {
                                if (DriveList.All((Item) => (string.IsNullOrEmpty(Item.Path) || string.IsNullOrEmpty(Folder.Path)) ? !Item.Name.Equals(Folder.Name, StringComparison.OrdinalIgnoreCase) : !Item.Path.Equals(Folder.Path, StringComparison.OrdinalIgnoreCase)))
                                {
                                    DriveList.Add(await DriveDataBase.CreateAsync(Folder, DriveType.Network));
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, $"Hide the device \"{Folder.Name}\" for error");
                            }
                        }

                        switch (PortalDeviceWatcher.Status)
                        {
                        case DeviceWatcherStatus.Created:
                        case DeviceWatcherStatus.Aborted:
                        case DeviceWatcherStatus.Stopped:
                        {
                            PortalDeviceWatcher.Start();
                            break;
                        }
                        }

                        if (!NetworkDriveCheckTimer.IsEnabled)
                        {
                            NetworkDriveCheckTimer.Start();
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"An exception was threw in {nameof(LoadDriveAsync)}");
                }
                finally
                {
                    _ = Interlocked.Exchange(ref LoadDriveLockResource, 0);
                }
            }
        }
        public static async Task LoadQuickStartItemsAsync(bool IsRefresh = false)
        {
            if (Interlocked.Exchange(ref LoadQuickStartLockResource, 1) == 0)
            {
                try
                {
                    if (!IsQuickStartLoaded || IsRefresh)
                    {
                        IsQuickStartLoaded = true;

                        if (IsRefresh)
                        {
                            QuickStartList.Clear();
                            WebLinkList.Clear();
                        }

                        foreach ((string Name, string IconPath, string Protocal, string Type) in SQLite.Current.GetQuickStartItem())
                        {
                            StorageFile ImageFile = null;

                            try
                            {
                                ImageFile = IconPath.StartsWith("ms-appx") ? await StorageFile.GetFileFromApplicationUriAsync(new Uri(IconPath))
                                                                       : await StorageFile.GetFileFromPathAsync(Path.Combine(ApplicationData.Current.LocalFolder.Path, IconPath));

                                BitmapImage Bitmap = new BitmapImage();

                                using (IRandomAccessStream Stream = await ImageFile.OpenAsync(FileAccessMode.Read))
                                {
                                    await Bitmap.SetSourceAsync(Stream);
                                }

                                if (Enum.Parse <QuickStartType>(Type) == QuickStartType.Application)
                                {
                                    QuickStartList.Add(new QuickStartItem(QuickStartType.Application, Bitmap, Protocal, IconPath, Name));
                                }
                                else
                                {
                                    WebLinkList.Add(new QuickStartItem(QuickStartType.WebSite, Bitmap, Protocal, IconPath, Name));
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, $"Could not load QuickStart item, Name: {Name}");

                                SQLite.Current.DeleteQuickStartItem(Name, Protocal, IconPath, Type);

                                if (ImageFile != null)
                                {
                                    await ImageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
                                }
                            }
                        }

                        QuickStartList.Add(new QuickStartItem());
                        WebLinkList.Add(new QuickStartItem());
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex);
                }
                finally
                {
                    _ = Interlocked.Exchange(ref LoadQuickStartLockResource, 0);
                }
            }
        }
示例#12
0
        /// <summary>
        /// 从数据库连接池中获取连接对象
        /// </summary>
        /// <returns></returns>
        public async Task <bool> MakeConnectionUseable()
        {
            try
            {
                if (!await Connection.PingAsync().ConfigureAwait(false))
                {
                    await Connection.CloseAsync().ConfigureAwait(false);

                    await Connection.OpenAsync().ConfigureAwait(false);
                }

                #region MySQL数据库存储过程和触发器初始化代码,仅首次运行时需要
                //StringBuilder Builder = new StringBuilder();
                //Builder.AppendLine("Create Table If Not Exists FeedBackTable (UserName Text Not Null, Title Text Not Null, Suggestion Text Not Null, LikeNum Text Not Null, DislikeNum Text Not Null, UserID Text Not Null, GUID Text Not Null);")
                //       .AppendLine("Create Table If Not Exists VoteRecordTable (UserID Text Not Null, GUID Text Not Null, Behavior Text Not Null);")

                //       .AppendLine("Drop Trigger If Exists RemoveVoteRecordTrigger;")
                //       .AppendLine("Create Trigger RemoveVoteRecordTrigger After Delete On FeedBackTable For Each Row Delete From VoteRecordTable Where GUID=old.GUID;")

                //       .AppendLine("Drop Procedure If Exists GetFeedBackProcedure;")
                //       .AppendLine("Create Procedure GetFeedBackProcedure(IN Para Text)")
                //       .AppendLine("Begin")
                //       .AppendLine("Declare EndSignal int Default 0;")
                //       .AppendLine("Declare P1 Text;")
                //       .AppendLine("Declare P2 Text;")
                //       .AppendLine("Declare P3 Text;")
                //       .AppendLine("Declare P4 Text;")
                //       .AppendLine("Declare P5 Text;")
                //       .AppendLine("Declare P6 Text;")
                //       .AppendLine("Declare P7 Text;")
                //       .AppendLine("Declare P8 Text;")
                //       .AppendLine("Declare RowData Cursor For Select * From FeedBackTable;")
                //       .AppendLine("Declare Continue Handler For Not Found Set EndSignal=1;")
                //       .AppendLine("Drop Table If Exists DataTemporary;")
                //       .AppendLine("Create Temporary Table DataTemporary (UserName Text, Title Text, Suggestion Text, LikeNum Text, DislikeNum Text, UserID Text, GUID Text, Behavior Text);")
                //       .AppendLine("Open RowData;")
                //       .AppendLine("Fetch RowData Into P1,P2,P3,P4,P5,P6,P7;")
                //       .AppendLine("While EndSignal<>1 Do")
                //       .AppendLine("If (Select Count(*) From VoteRecordTable Where UserID=Para And GUID=P7) <> 0")
                //       .AppendLine("Then")
                //       .AppendLine("Select Behavior Into P8 From VoteRecordTable Where UserID=Para And GUID=P7;")
                //       .AppendLine("Else")
                //       .AppendLine("Set P8 = 'NULL';")
                //       .AppendLine("End If;")
                //       .AppendLine("Insert Into DataTemporary Values (P1,P2,P3,P4,P5,P6,P7,P8);")
                //       .AppendLine("Fetch RowData Into P1,P2,P3,P4,P5,P6,P7;")
                //       .AppendLine("End While;")
                //       .AppendLine("Close RowData;")
                //       .AppendLine("Select * From DataTemporary;")
                //       .AppendLine("End;")

                //       .AppendLine("Drop Procedure If Exists UpdateFeedBackVoteProcedure;")
                //       .AppendLine("Create Procedure UpdateFeedBackVoteProcedure(IN LNum Text,IN DNum Text,IN UID Text,IN GID Text,IN Beh Text)")
                //       .AppendLine("Begin")
                //       .AppendLine("Update FeedBackTable Set LikeNum=LNum, DislikeNum=DNum Where GUID=GID;")
                //       .AppendLine("If (Select Count(*) From VoteRecordTable Where UserID=UID And GUID=GID) <> 0")
                //       .AppendLine("Then")
                //       .AppendLine("If Beh <> '='")
                //       .AppendLine("Then")
                //       .AppendLine("Update VoteRecordTable Set Behavior=Beh Where UserID=UID And GUID=GID;")
                //       .AppendLine("Else")
                //       .AppendLine("Delete From VoteRecordTable Where UserID=UID And GUID=GID;")
                //       .AppendLine("End If;")
                //       .AppendLine("Else")
                //       .AppendLine("If Beh <> '='")
                //       .AppendLine("Then")
                //       .AppendLine("Insert Into VoteRecordTable Values (UID,GID,Beh);")
                //       .AppendLine("End If;")
                //       .AppendLine("End If;")
                //       .AppendLine("End;");
                //using (MySqlCommand Command = new MySqlCommand(Builder.ToString(), Connection))
                //{
                //    await Command.ExecuteNonQueryAsync().ConfigureAwait(false);
                //}
                #endregion

                return(Connection.State == ConnectionState.Open);
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "Could not make sure mysql connection available");
                return(false);
            }
        }
示例#13
0
        /// <summary>
        /// 获取所有快速启动项
        /// </summary>
        /// <returns></returns>
        public async Task <List <KeyValuePair <QuickStartType, QuickStartItem> > > GetQuickStartItemAsync()
        {
            List <Tuple <string, string, string> > ErrorList             = new List <Tuple <string, string, string> >();
            List <KeyValuePair <QuickStartType, QuickStartItem> > Result = new List <KeyValuePair <QuickStartType, QuickStartItem> >();

            using (SqliteCommand Command = new SqliteCommand("Select * From QuickStart", Connection))
                using (SqliteDataReader Reader = await Command.ExecuteReaderAsync())
                {
                    while (Reader.Read())
                    {
                        StorageFile ImageFile = null;

                        try
                        {
                            ImageFile = Convert.ToString(Reader[1]).StartsWith("ms-appx")
                                                ? await StorageFile.GetFileFromApplicationUriAsync(new Uri(Reader[1].ToString()))
                                                : await StorageFile.GetFileFromPathAsync(Path.Combine(ApplicationData.Current.LocalFolder.Path, Convert.ToString(Reader[1])));

                            BitmapImage Bitmap = new BitmapImage();

                            using (IRandomAccessStream Stream = await ImageFile.OpenAsync(FileAccessMode.Read))
                            {
                                await Bitmap.SetSourceAsync(Stream);
                            }

                            if (Enum.Parse <QuickStartType>(Reader[3].ToString()) == QuickStartType.Application)
                            {
                                Result.Add(new KeyValuePair <QuickStartType, QuickStartItem>(QuickStartType.Application, new QuickStartItem(Bitmap, Convert.ToString(Reader[2]), QuickStartType.Application, Reader[1].ToString(), Reader[0].ToString())));
                            }
                            else
                            {
                                Result.Add(new KeyValuePair <QuickStartType, QuickStartItem>(QuickStartType.WebSite, new QuickStartItem(Bitmap, Convert.ToString(Reader[2]), QuickStartType.WebSite, Reader[1].ToString(), Reader[0].ToString())));
                            }
                        }
                        catch (Exception ex)
                        {
                            LogTracer.Log(ex, $"Could not load QuickStart item, Name: {Reader[0]}");

                            ErrorList.Add(new Tuple <string, string, string>(Convert.ToString(Reader[0]), Convert.ToString(Reader[1]), Convert.ToString(Reader[3])));

                            if (ImageFile != null)
                            {
                                await ImageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
                            }
                        }
                    }
                }

            foreach (Tuple <string, string, string> ErrorItem in ErrorList)
            {
                using (SqliteCommand Command = new SqliteCommand("Delete From QuickStart Where Name = @Name And FullPath = @FullPath And Type=@Type", Connection))
                {
                    Command.Parameters.AddWithValue("@Name", ErrorItem.Item1);
                    Command.Parameters.AddWithValue("@FullPath", ErrorItem.Item2);
                    Command.Parameters.AddWithValue("@Type", ErrorItem.Item3);
                    await Command.ExecuteNonQueryAsync();
                }
            }

            return(Result);
        }
示例#14
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();
        }
示例#15
0
        public async Task InitializeAsync()
        {
            if (!IsInitialized)
            {
                try
                {
                    switch (CurrentType)
                    {
                    case BackgroundBrushType.Picture:
                    {
                        string UriString = Convert.ToString(ApplicationData.Current.LocalSettings.Values["PictureBackgroundUri"]);

                        if (!string.IsNullOrEmpty(UriString))
                        {
                            BitmapImage Bitmap = new BitmapImage();

                            PictureBackgroundBrush.ImageSource = Bitmap;

                            string PicturePath = Path.Combine(Package.Current.InstalledPath, UriString.Replace("ms-appx:///", string.Empty).Replace("/", @"\"));

                            if (await FileSystemStorageItemBase.OpenAsync(PicturePath) is FileSystemStorageFile File)
                            {
                                using (IRandomAccessStream Stream = await File.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read))
                                {
                                    await Bitmap.SetSourceAsync(Stream);
                                }

                                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush)));
                            }
                            else
                            {
                                LogTracer.Log($"PicturePath is \"{PicturePath}\" but could not found, {nameof(BackgroundController.InitializeAsync)} is not finished");
                            }
                        }
                        else
                        {
                            LogTracer.Log($"PicturePath is empty, {nameof(BackgroundController.InitializeAsync)} is not finished");
                        }

                        break;
                    }

                    case BackgroundBrushType.BingPicture:
                    {
                        if (await BingPictureDownloader.GetBingPictureAsync() is FileSystemStorageFile ImageFile)
                        {
                            BitmapImage Bitmap = new BitmapImage();

                            BingPictureBursh.ImageSource = Bitmap;

                            using (IRandomAccessStream Stream = await ImageFile.GetRandomAccessStreamFromFileAsync(FileAccessMode.Read))
                            {
                                await Bitmap.SetSourceAsync(Stream);
                            }

                            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush)));
                        }
                        else
                        {
                            LogTracer.Log("Download Bing picture failed, BackgroundController.Initialize is not finished");
                        }

                        break;
                    }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Exception happend when loading image for background");
                }
                finally
                {
                    IsInitialized = true;
                }
            }
        }
示例#16
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();
        }
示例#17
0
        public static async Task LoadLibraryFoldersAsync()
        {
            if (Interlocked.Exchange(ref LoadLibraryLockResource, 1) == 0)
            {
                try
                {
                    if (!IsLibaryLoaded)
                    {
                        IsLibaryLoaded = true;

                        if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("IsLibraryInitialized"))
                        {
                            try
                            {
                                IReadOnlyList <User> UserList = await User.FindAllAsync();

                                UserDataPaths DataPath = UserList.FirstOrDefault((User) => User.AuthenticationStatus == UserAuthenticationStatus.LocallyAuthenticated && User.Type == UserType.LocalUser) is User CurrentUser
                                                         ? UserDataPaths.GetForUser(CurrentUser)
                                                         : UserDataPaths.GetDefault();

                                try
                                {
                                    if (!string.IsNullOrEmpty(DataPath.Downloads))
                                    {
                                        await SQLite.Current.SetLibraryPathAsync(DataPath.Downloads, LibraryType.Downloads);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Desktop))
                                    {
                                        await SQLite.Current.SetLibraryPathAsync(DataPath.Desktop, LibraryType.Desktop);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Videos))
                                    {
                                        await SQLite.Current.SetLibraryPathAsync(DataPath.Videos, LibraryType.Videos);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Pictures))
                                    {
                                        await SQLite.Current.SetLibraryPathAsync(DataPath.Pictures, LibraryType.Pictures);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Documents))
                                    {
                                        await SQLite.Current.SetLibraryPathAsync(DataPath.Documents, LibraryType.Document);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Music))
                                    {
                                        await SQLite.Current.SetLibraryPathAsync(DataPath.Music, LibraryType.Music);
                                    }

                                    if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("OneDrive")))
                                    {
                                        await SQLite.Current.SetLibraryPathAsync(Environment.GetEnvironmentVariable("OneDrive"), LibraryType.OneDrive);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogTracer.Log(ex, "An error was threw when getting library folder (In initialize)");
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, "An error was threw when try to get 'UserDataPath' (In initialize)");

                                string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                                if (!string.IsNullOrEmpty(DesktopPath))
                                {
                                    await SQLite.Current.SetLibraryPathAsync(DesktopPath, LibraryType.Desktop);
                                }

                                string VideoPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
                                if (!string.IsNullOrEmpty(VideoPath))
                                {
                                    await SQLite.Current.SetLibraryPathAsync(VideoPath, LibraryType.Videos);
                                }

                                string PicturesPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                                if (!string.IsNullOrEmpty(PicturesPath))
                                {
                                    await SQLite.Current.SetLibraryPathAsync(PicturesPath, LibraryType.Pictures);
                                }

                                string DocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                                if (!string.IsNullOrEmpty(DocumentsPath))
                                {
                                    await SQLite.Current.SetLibraryPathAsync(DocumentsPath, LibraryType.Document);
                                }

                                string MusicPath = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
                                if (!string.IsNullOrEmpty(MusicPath))
                                {
                                    await SQLite.Current.SetLibraryPathAsync(MusicPath, LibraryType.Music);
                                }

                                string OneDrivePath = Environment.GetEnvironmentVariable("OneDrive");
                                if (!string.IsNullOrEmpty(OneDrivePath))
                                {
                                    await SQLite.Current.SetLibraryPathAsync(OneDrivePath, LibraryType.OneDrive);
                                }
                            }
                            finally
                            {
                                ApplicationData.Current.LocalSettings.Values["IsLibraryInitialized"] = true;
                            }
                        }
                        else
                        {
                            try
                            {
                                IReadOnlyList <User> UserList = await User.FindAllAsync();

                                UserDataPaths DataPath = UserList.FirstOrDefault((User) => User.AuthenticationStatus == UserAuthenticationStatus.LocallyAuthenticated && User.Type == UserType.LocalUser) is User CurrentUser
                                                         ? UserDataPaths.GetForUser(CurrentUser)
                                                         : UserDataPaths.GetDefault();

                                try
                                {
                                    if (!string.IsNullOrEmpty(DataPath.Downloads))
                                    {
                                        await SQLite.Current.UpdateLibraryAsync(DataPath.Downloads, LibraryType.Downloads);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Desktop))
                                    {
                                        await SQLite.Current.UpdateLibraryAsync(DataPath.Desktop, LibraryType.Desktop);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Videos))
                                    {
                                        await SQLite.Current.UpdateLibraryAsync(DataPath.Videos, LibraryType.Videos);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Pictures))
                                    {
                                        await SQLite.Current.UpdateLibraryAsync(DataPath.Pictures, LibraryType.Pictures);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Documents))
                                    {
                                        await SQLite.Current.UpdateLibraryAsync(DataPath.Documents, LibraryType.Document);
                                    }

                                    if (!string.IsNullOrEmpty(DataPath.Music))
                                    {
                                        await SQLite.Current.UpdateLibraryAsync(DataPath.Music, LibraryType.Music);
                                    }

                                    if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("OneDrive")))
                                    {
                                        await SQLite.Current.UpdateLibraryAsync(Environment.GetEnvironmentVariable("OneDrive"), LibraryType.OneDrive);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogTracer.Log(ex, "An error was threw when getting library folder (Not in initialize)");
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, "An error was threw when try to get 'UserDataPath' (Not in initialize)");

                                string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                                if (!string.IsNullOrEmpty(DesktopPath))
                                {
                                    await SQLite.Current.UpdateLibraryAsync(DesktopPath, LibraryType.Desktop);
                                }

                                string VideoPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
                                if (!string.IsNullOrEmpty(VideoPath))
                                {
                                    await SQLite.Current.UpdateLibraryAsync(VideoPath, LibraryType.Videos);
                                }

                                string PicturesPath = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                                if (!string.IsNullOrEmpty(PicturesPath))
                                {
                                    await SQLite.Current.UpdateLibraryAsync(PicturesPath, LibraryType.Pictures);
                                }

                                string DocumentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                                if (!string.IsNullOrEmpty(DocumentsPath))
                                {
                                    await SQLite.Current.UpdateLibraryAsync(DocumentsPath, LibraryType.Document);
                                }

                                string MusicPath = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
                                if (!string.IsNullOrEmpty(MusicPath))
                                {
                                    await SQLite.Current.UpdateLibraryAsync(MusicPath, LibraryType.Music);
                                }

                                string OneDrivePath = Environment.GetEnvironmentVariable("OneDrive");
                                if (!string.IsNullOrEmpty(OneDrivePath))
                                {
                                    await SQLite.Current.UpdateLibraryAsync(OneDrivePath, LibraryType.OneDrive);
                                }
                            }
                        }

                        Queue <string> ErrorList = new Queue <string>();

                        foreach ((string, LibraryType)Library in await SQLite.Current.GetLibraryPathAsync())
                        {
                            try
                            {
                                LibraryFolderList.Add(await LibraryFolder.CreateAsync(Library.Item1, Library.Item2));
                            }
                            catch (Exception)
                            {
                                ErrorList.Enqueue(Library.Item1);
                                await SQLite.Current.DeleteLibraryAsync(Library.Item1);
                            }
                        }

                        await JumpListController.Current.AddItemAsync(JumpListGroup.Library, LibraryFolderList.Where((Library) => Library.Type == LibraryType.UserCustom).Select((Library) => Library.Folder.Path).ToArray());

                        if (ErrorList.Count > 0)
                        {
                            LibraryNotFound?.Invoke(null, ErrorList);
                        }
                    }
                }
                finally
                {
                    _ = Interlocked.Exchange(ref LoadLibraryLockResource, 0);
                }
            }
        }
示例#18
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) =>
                        {
                            try
                            {
                                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");
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, "Toast notification could not be sent");
                            }
                        });

                        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));
        }
示例#19
0
        private async void Modified(string Path)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() =>
            {
                await Locker.WaitAsync().ConfigureAwait(true);

                if (CurrentLocation == System.IO.Path.GetDirectoryName(Path))
                {
                    try
                    {
                        if (await FileSystemStorageItemBase.OpenAsync(Path).ConfigureAwait(true) is FileSystemStorageItemBase ModifiedItem)
                        {
                            if (CurrentCollection.FirstOrDefault((Item) => Item.Path.Equals(Path, StringComparison.OrdinalIgnoreCase)) is FileSystemStorageItemBase OldItem)
                            {
                                if (ModifiedItem.GetType() == OldItem.GetType())
                                {
                                    await OldItem.RefreshAsync().ConfigureAwait(true);
                                }
                                else
                                {
                                    CurrentCollection.Remove(OldItem);

                                    if ((ModifiedItem is IHiddenStorageItem && SettingControl.IsDisplayHiddenItem) || ModifiedItem is not IHiddenStorageItem)
                                    {
                                        if (CurrentCollection.Any())
                                        {
                                            int Index = SortCollectionGenerator.Current.SearchInsertLocation(CurrentCollection, ModifiedItem);

                                            if (Index >= 0)
                                            {
                                                CurrentCollection.Insert(Index, ModifiedItem);
                                            }
                                            else
                                            {
                                                CurrentCollection.Add(ModifiedItem);
                                            }
                                        }
                                        else
                                        {
                                            CurrentCollection.Add(ModifiedItem);
                                        }
                                    }
                                }
                            }
                            else if (ModifiedItem is not IHiddenStorageItem)
                            {
                                if (CurrentCollection.Any())
                                {
                                    int Index = SortCollectionGenerator.Current.SearchInsertLocation(CurrentCollection, ModifiedItem);

                                    if (Index >= 0)
                                    {
                                        CurrentCollection.Insert(Index, ModifiedItem);
                                    }
                                    else
                                    {
                                        CurrentCollection.Add(ModifiedItem);
                                    }
                                }
                                else
                                {
                                    CurrentCollection.Add(ModifiedItem);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, $"{ nameof(StorageAreaWatcher)}: Modify item in collection failed");
                    }
                    finally
                    {
                        Locker.Release();
                    }
                }
            });
示例#20
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");
            }
        }
        public static async Task <FileSystemStorageItemBase> CreateAsync(string Path, StorageItemTypes ItemTypes, CreateOption Option)
        {
            switch (ItemTypes)
            {
            case StorageItemTypes.File:
            {
                if (WIN_Native_API.CreateFileFromPath(Path, Option, out string NewPath))
                {
                    return(await OpenAsync(NewPath));
                }
                else
                {
                    LogTracer.Log($"Native API could not create file: \"{Path}\", fall back to UWP storage API");

                    try
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(Path));

                        switch (Option)
                        {
                        case CreateOption.GenerateUniqueName:
                        {
                            StorageFile NewFile = await Folder.CreateFileAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.GenerateUniqueName);

                            return(await CreatedByStorageItemAsync(NewFile));
                        }

                        case CreateOption.OpenIfExist:
                        {
                            StorageFile NewFile = await Folder.CreateFileAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.OpenIfExists);

                            return(await CreatedByStorageItemAsync(NewFile));
                        }

                        case CreateOption.ReplaceExisting:
                        {
                            StorageFile NewFile = await Folder.CreateFileAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.ReplaceExisting);

                            return(await CreatedByStorageItemAsync(NewFile));
                        }

                        default:
                        {
                            return(null);
                        }
                        }
                    }
                    catch
                    {
                        LogTracer.Log($"UWP storage API could not create file: \"{Path}\"");
                        return(null);
                    }
                }
            }

            case StorageItemTypes.Folder:
            {
                if (WIN_Native_API.CreateDirectoryFromPath(Path, Option, out string NewPath))
                {
                    return(await OpenAsync(NewPath));
                }
                else
                {
                    LogTracer.Log($"Native API could not create file: \"{Path}\", fall back to UWP storage API");

                    try
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(System.IO.Path.GetDirectoryName(Path));

                        switch (Option)
                        {
                        case CreateOption.GenerateUniqueName:
                        {
                            StorageFolder NewFolder = await Folder.CreateFolderAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.GenerateUniqueName);

                            return(await CreatedByStorageItemAsync(NewFolder));
                        }

                        case CreateOption.OpenIfExist:
                        {
                            StorageFolder NewFolder = await Folder.CreateFolderAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.OpenIfExists);

                            return(await CreatedByStorageItemAsync(NewFolder));
                        }

                        case CreateOption.ReplaceExisting:
                        {
                            StorageFolder NewFolder = await Folder.CreateFolderAsync(System.IO.Path.GetFileName(Path), CreationCollisionOption.ReplaceExisting);

                            return(await CreatedByStorageItemAsync(NewFolder));
                        }

                        default:
                        {
                            return(null);
                        }
                        }
                    }
                    catch
                    {
                        LogTracer.Log($"UWP storage API could not create folder: \"{Path}\"");
                        return(null);
                    }
                }
            }

            default:
            {
                return(null);
            }
            }
        }
        public async Task Initialize()
        {
            if (!IsInitialized)
            {
                try
                {
                    switch (CurrentType)
                    {
                    case BackgroundBrushType.Picture:
                    {
                        string UriString = Convert.ToString(ApplicationData.Current.LocalSettings.Values["PictureBackgroundUri"]);

                        if (!string.IsNullOrEmpty(UriString))
                        {
                            BitmapImage Bitmap = new BitmapImage();

                            StorageFile ImageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(UriString));

                            using (IRandomAccessStream Stream = await ImageFile.OpenAsync(FileAccessMode.Read))
                            {
                                await Bitmap.SetSourceAsync(Stream);
                            }

                            PictureBackgroundBrush.ImageSource = Bitmap;

                            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush)));
                        }
                        else
                        {
                            LogTracer.Log("UriString is empty, BackgroundController.Initialize is not finished");
                        }

                        break;
                    }

                    case BackgroundBrushType.BingPicture:
                    {
                        BitmapImage Bitmap = new BitmapImage();

                        if (await BingPictureDownloader.GetBingPictureAsync().ConfigureAwait(true) is StorageFile ImageFile)
                        {
                            using (IRandomAccessStream Stream = await ImageFile.OpenAsync(FileAccessMode.Read))
                            {
                                await Bitmap.SetSourceAsync(Stream);
                            }

                            BingPictureBursh.ImageSource = Bitmap;

                            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BackgroundBrush)));
                        }
                        else
                        {
                            LogTracer.Log("Download Bing picture failed, BackgroundController.Initialize is not finished");
                        }

                        break;
                    }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "Exception happend when loading image for background");
                }
                finally
                {
                    IsInitialized = true;
                }
            }
        }
        public async Task LoadAsync()
        {
            if (CheckIfPropertiesLoaded())
            {
                if (ThubmnalModeChanged)
                {
                    ThubmnalModeChanged = false;

                    if ((this is FileSystemStorageFile && SettingControl.ContentLoadMode == LoadMode.OnlyFile) || SettingControl.ContentLoadMode == LoadMode.FileAndFolder)
                    {
                        try
                        {
                            await LoadThumbnailAsync(ThumbnailMode);
                        }
                        catch (Exception ex)
                        {
                            LogTracer.Log(ex, $"An exception was threw in {nameof(LoadAsync)}, StorageType: {GetType().FullName}, Path: {Path}");
                        }
                        finally
                        {
                            OnPropertyChanged(nameof(Thumbnail));
                        }
                    }
                }
            }
            else
            {
                async void LocalLoadFunction()
                {
                    try
                    {
                        if (FullTrustProcessIsNeeded())
                        {
                            using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController())
                            {
                                if ((this is FileSystemStorageFile && SettingControl.ContentLoadMode == LoadMode.OnlyFile) || SettingControl.ContentLoadMode == LoadMode.FileAndFolder)
                                {
                                    await LoadPropertiesAsync(false, Exclusive.Controller);
                                    await LoadThumbnailAsync(ThumbnailMode);
                                }

                                if (CheckIfNeedLoadThumbnailOverlay())
                                {
                                    await LoadThumbnailOverlayAsync(Exclusive.Controller);
                                }
                            }
                        }
                        else
                        {
                            if ((this is FileSystemStorageFile && SettingControl.ContentLoadMode == LoadMode.OnlyFile) || SettingControl.ContentLoadMode == LoadMode.FileAndFolder)
                            {
                                await LoadPropertiesAsync(false);
                                await LoadThumbnailAsync(ThumbnailMode);
                            }

                            if (CheckIfNeedLoadThumbnailOverlay())
                            {
                                using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController())
                                {
                                    await LoadThumbnailOverlayAsync(Exclusive.Controller);
                                }
                            }
                        }

                        LoadForegroundConfiguration();

                        await LoadSyncStatusAsync();
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, $"An exception was threw in {nameof(LoadAsync)}, StorageType: {GetType().FullName}, Path: {Path}");
                    }
                    finally
                    {
                        OnPropertyChanged(nameof(Name));
                        OnPropertyChanged(nameof(Size));
                        OnPropertyChanged(nameof(DisplayType));
                        OnPropertyChanged(nameof(ModifiedTime));
                        OnPropertyChanged(nameof(Thumbnail));
                        OnPropertyChanged(nameof(ThumbnailOverlay));
                    }
                };

                if (CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess)
                {
                    LocalLoadFunction();
                }
                else
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, LocalLoadFunction);
                }
            }
        }
        public virtual async Task <(uint, uint)> GetFolderAndFileNumAsync(CancellationToken CancelToken = default)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(await Task.Run(() =>
                {
                    return WIN_Native_API.CalculateFolderAndFileCount(Path, CancelToken);
                }));
            }
            else
            {
                try
                {
                    LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                    if (await GetStorageItemAsync() is StorageFolder Folder)
                    {
                        QueryOptions Options = new QueryOptions
                        {
                            FolderDepth   = FolderDepth.Deep,
                            IndexerOption = IndexerOption.DoNotUseIndexer
                        };
                        Options.SetPropertyPrefetch(PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size" });

                        StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                        uint FolderCount = 0, FileCount = 0;

                        for (uint Index = 0; !CancelToken.IsCancellationRequested; Index += 25)
                        {
                            IReadOnlyList <IStorageItem> ReadOnlyItemList = await Query.GetItemsAsync(Index, 25);

                            if (ReadOnlyItemList.Count > 0)
                            {
                                foreach (IStorageItem Item in ReadOnlyItemList)
                                {
                                    if (Item.IsOfType(StorageItemTypes.Folder))
                                    {
                                        FolderCount++;
                                    }
                                    else
                                    {
                                        FileCount++;
                                    }

                                    if (CancelToken.IsCancellationRequested)
                                    {
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        return(FolderCount, FileCount);
                    }
                    else
                    {
                        return(0, 0);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"{nameof(GetFolderAndFileNumAsync)} failed for uwp API");
                    return(0, 0);
                }
            }
        }
        public async Task AddItem(JumpListGroup Group, params string[] FolderPathList)
        {
            try
            {
                if (await Initialize().ConfigureAwait(false))
                {
                    bool ItemModified = false;

                    string GroupString = ConvertGroupEnumToResourceString(Group);

                    foreach (string FolderPath in FolderPathList)
                    {
                        if (InnerList.Items.Where((Item) => Item.GroupName == GroupString).All((Item) => Item.Description != FolderPath))
                        {
                            string RecentGroupString  = ConvertGroupEnumToResourceString(JumpListGroup.Recent);
                            string LibraryGroupString = ConvertGroupEnumToResourceString(JumpListGroup.Library);

                            JumpListItem[] RecentGroupItems = InnerList.Items.Where((Item) => Item.GroupName == RecentGroupString).ToArray();

                            JumpListItem[] LibraryGroupItems = InnerList.Items.Where((Item) => Item.GroupName == LibraryGroupString).ToArray();

                            if (Group == JumpListGroup.Library)
                            {
                                if (LibraryGroupItems.Length >= GroupItemMaxNum && RecentGroupItems.Length + LibraryGroupItems.Length >= 2 * GroupItemMaxNum)
                                {
                                    if (RecentGroupItems.Length > 4)
                                    {
                                        InnerList.Items.Remove(RecentGroupItems.FirstOrDefault());
                                    }
                                    else
                                    {
                                        InnerList.Items.Remove(LibraryGroupItems.FirstOrDefault());
                                    }
                                }
                            }
                            else
                            {
                                if (RecentGroupItems.Length >= GroupItemMaxNum || RecentGroupItems.Length + LibraryGroupItems.Length >= 2 * GroupItemMaxNum)
                                {
                                    InnerList.Items.Remove(RecentGroupItems.FirstOrDefault());
                                }
                            }

                            JumpListItem NewItem = JumpListItem.CreateWithArguments(FolderPath, Path.GetFileName(FolderPath));

                            NewItem.Logo        = new Uri("ms-appx:///Assets/FolderIcon.png");
                            NewItem.Description = FolderPath;
                            NewItem.GroupName   = GroupString;

                            InnerList.Items.Add(NewItem);

                            ItemModified = true;
                        }
                    }

                    if (ItemModified)
                    {
                        await InnerList.SaveAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex);
            }
        }