public async Task LoadMorePropertyAsync()
        {
            if ((this is FileSystemStorageFile && SettingControl.ContentLoadMode == LoadMode.OnlyFile) || SettingControl.ContentLoadMode == LoadMode.FileAndFolder)
            {
                if (!CheckIfPropertyLoaded())
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() =>
                    {
                        try
                        {
                            await LoadMorePropertyCore();

                            OnPropertyChanged(nameof(Size));
                            OnPropertyChanged(nameof(Name));
                            OnPropertyChanged(nameof(ModifiedTime));
                            OnPropertyChanged(nameof(Thumbnail));
                            OnPropertyChanged(nameof(DisplayType));
                        }
                        catch (Exception ex)
                        {
                            LogTracer.Log(ex, $"An exception was threw in {nameof(LoadMorePropertyAsync)}, StorageType: {GetType().FullName}, Path: {Path}");
                        }
                    });
                }
            }
        }
Exemple #2
0
        public async virtual Task <FileStream> GetFileStreamFromFileAsync(AccessMode Mode)
        {
            try
            {
                if (WIN_Native_API.CreateFileStreamFromExistingPath(Path, Mode) is FileStream Stream)
                {
                    return(Stream);
                }
                else
                {
                    if (await GetStorageItemAsync() is StorageFile File)
                    {
                        SafeFileHandle Handle = File.GetSafeFileHandle();

                        return(new FileStream(Handle, FileAccess.ReadWrite));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "Could not create a new file stream");
                return(null);
            }
        }
Exemple #3
0
        /// <summary>
        /// 更新反馈对象的标题和建议内容
        /// </summary>
        /// <param name="Title">标题</param>
        /// <param name="Suggestion">建议</param>
        /// <param name="Guid">唯一标识</param>
        /// <returns></returns>
        public async Task <bool> UpdateFeedBackAsync(string Title, string Suggestion, string Guid)
        {
            if (await MakeConnectionUseable().ConfigureAwait(false))
            {
                try
                {
                    using (MySqlCommand Command = new MySqlCommand("Update FeedBackTable Set Title=@NewTitle, Suggestion=@NewSuggestion Where GUID=@GUID", Connection))
                    {
                        Command.Parameters.AddWithValue("@NewTitle", Title);
                        Command.Parameters.AddWithValue("@NewSuggestion", Suggestion);
                        Command.Parameters.AddWithValue("@GUID", Guid);
                        await Command.ExecuteNonQueryAsync().ConfigureAwait(false);
                    }

                    return(true);
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"An error was threw in { nameof(UpdateFeedBackAsync)}");
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Exemple #4
0
        /// <summary>
        /// 删除反馈内容
        /// </summary>
        /// <param name="Item">反馈对象</param>
        /// <returns></returns>
        public async Task <bool> DeleteFeedBackAsync(FeedBackItem Item)
        {
            if (Item != null)
            {
                if (await MakeConnectionUseable().ConfigureAwait(false))
                {
                    try
                    {
                        using (MySqlCommand Command = new MySqlCommand("Delete From FeedBackTable Where GUID=@GUID", Connection))
                        {
                            Command.Parameters.AddWithValue("@GUID", Item.GUID);
                            await Command.ExecuteNonQueryAsync().ConfigureAwait(false);
                        }

                        return(true);
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, $"An error was threw in { nameof(DeleteFeedBackAsync)}");
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                throw new ArgumentNullException(nameof(Item), "Parameter could not be null");
            }
        }
        public async Task RefreshAsync()
        {
            try
            {
                if (await CheckExistAsync(Path))
                {
                    if (LoadMorePropertiesWithFullTrustProcess())
                    {
                        using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController())
                        {
                            await LoadMorePropertiesCoreAsync(Exclusive.Controller, true);
                        }
                    }
                    else
                    {
                        await LoadMorePropertiesCoreAsync(true);
                    }

                    OnPropertyChanged(nameof(Size));
                    OnPropertyChanged(nameof(Name));
                    OnPropertyChanged(nameof(ModifiedTime));
                    OnPropertyChanged(nameof(Thumbnail));
                    OnPropertyChanged(nameof(DisplayType));
                }
                else
                {
                    LogTracer.Log($"File/Folder not found or access deny when executing FileSystemStorageItemBase.Update, path: {Path}");
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"An exception was threw when executing FileSystemStorageItemBase.Update, path: {Path}");
            }
        }
Exemple #6
0
        private static async Task <string> GetDailyPhotoPath()
        {
            try
            {
                HttpWebRequest Request = WebRequest.CreateHttp(new Uri("http://cn.bing.com/HPImageArchive.aspx?idx=0&n=1"));
                Request.Timeout          = 5000;
                Request.ReadWriteTimeout = 5000;

                using (WebResponse Response = await Request.GetResponseAsync())
                    using (Stream ResponseStream = Response.GetResponseStream())
                        using (StreamReader Reader = new StreamReader(ResponseStream))
                        {
                            string XmlString = await Reader.ReadToEndAsync();

                            XmlDocument Document = new XmlDocument();
                            Document.LoadXml(XmlString);

                            if (Document.SelectSingleNode("/images/image/url") is IXmlNode Node)
                            {
                                return(Node.InnerText);
                            }
                            else
                            {
                                return(string.Empty);
                            }
                        }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "Network is not available");
                return(string.Empty);
            }
        }
        public async Task RemoveItem(JumpListGroup Group, params string[] PathList)
        {
            try
            {
                if (await Initialize().ConfigureAwait(false))
                {
                    bool   ItemModified = false;
                    string GroupString  = ConvertGroupEnumToResourceString(Group);

                    JumpListItem[] GroupItem = InnerList.Items.Where((Item) => Item.GroupName == GroupString).ToArray();

                    foreach (string Path in PathList)
                    {
                        if (GroupItem.FirstOrDefault((Item) => Item.Description == Path) is JumpListItem RemoveItem)
                        {
                            InnerList.Items.Remove(RemoveItem);
                            ItemModified = true;
                        }
                    }

                    if (ItemModified)
                    {
                        await InnerList.SaveAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex);
            }
        }
Exemple #8
0
        public static async Task <ProgramPickerItem> CreateAsync(AppInfo App)
        {
            try
            {
                using (IRandomAccessStreamWithContentType LogoStream = await App.DisplayInfo.GetLogo(new Windows.Foundation.Size(128, 128)).OpenReadAsync())
                {
                    BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(LogoStream);

                    using (SoftwareBitmap SBitmap = await Decoder.GetSoftwareBitmapAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied))
                        using (SoftwareBitmap ResizeBitmap = ComputerVisionProvider.ResizeToActual(SBitmap))
                            using (InMemoryRandomAccessStream Stream = new InMemoryRandomAccessStream())
                            {
                                BitmapEncoder Encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, Stream);

                                Encoder.SetSoftwareBitmap(ResizeBitmap);
                                await Encoder.FlushAsync();

                                BitmapImage Logo = new BitmapImage();
                                await Logo.SetSourceAsync(Stream);

                                return(new ProgramPickerItem(Logo, App.DisplayInfo.DisplayName, App.DisplayInfo.Description, App.PackageFamilyName));
                            }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "An exception was threw when getting or processing App Logo");
                return(new ProgramPickerItem(App.DisplayInfo.DisplayName, App.DisplayInfo.Description, App.PackageFamilyName));
            }
        }
        public async Task <List <FileSystemStorageItemBase> > GetChildItemsAsync(bool IncludeHiddenItems, ItemFilters Filter = ItemFilters.File | ItemFilters.Folder)
        {
            if (WIN_Native_API.CheckLocationAvailability(Path))
            {
                return(WIN_Native_API.GetStorageItems(Path, IncludeHiddenItems, Filter));
            }
            else
            {
                LogTracer.Log($"Native API could not enum subitems in path: \"{Path}\", fall back to UWP storage API");

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

                        StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options);

                        uint Count = await Query.GetItemCountAsync();

                        List <FileSystemStorageItemBase> Result = new List <FileSystemStorageItemBase>(Convert.ToInt32(Count));

                        for (uint i = 0; i < Count; i += 30)
                        {
                            IReadOnlyList <IStorageItem> CurrentList = await Query.GetItemsAsync(i, 30);

                            foreach (IStorageItem Item in CurrentList.Where((Item) => (Item.IsOfType(StorageItemTypes.Folder) && Filter.HasFlag(ItemFilters.Folder)) || (Item.IsOfType(StorageItemTypes.File) && Filter.HasFlag(ItemFilters.File))))
                            {
                                if (Item is StorageFolder SubFolder)
                                {
                                    Result.Add(new FileSystemStorageFolder(SubFolder, await SubFolder.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFolder.GetModifiedTimeAsync().ConfigureAwait(true)));
                                }
                                else if (Item is StorageFile SubFile)
                                {
                                    Result.Add(new FileSystemStorageFile(SubFile, await SubFile.GetThumbnailBitmapAsync().ConfigureAwait(true), await SubFile.GetSizeRawDataAsync().ConfigureAwait(true), await SubFile.GetModifiedTimeAsync().ConfigureAwait(true)));
                                }
                            }
                        }

                        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));
                }
            }
        }
        public async Task LaunchAsync()
        {
            try
            {
                using (FullTrustProcessController.ExclusiveUsage Exclusive = await FullTrustProcessController.GetAvailableController())
                {
                    if (LinkType == ShellLinkType.Normal)
                    {
                        if (!await Exclusive.Controller.RunAsync(LinkTargetPath, WorkDirectory, WindowState, NeedRunAsAdmin, false, false, Arguments))
                        {
                            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                            {
                                QueueContentDialog Dialog = new QueueContentDialog
                                {
                                    Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                    Content         = Globalization.GetString("QueueDialog_LaunchFailed_Content"),
                                    CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                };

                                await Dialog.ShowAsync();
                            });
                        }
                    }
                    else
                    {
                        if (!await Exclusive.Controller.LaunchUWPFromPfnAsync(LinkTargetPath))
                        {
                            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                            {
                                QueueContentDialog Dialog = new QueueContentDialog
                                {
                                    Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                    Content         = Globalization.GetString("QueueDialog_LaunchFailed_Content"),
                                    CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                };

                                await Dialog.ShowAsync();
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex);

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

                    await Dialog.ShowAsync();
                });
            }
        }
Exemple #11
0
        public async Task <bool> CheckPurchaseStatusAsync()
        {
            try
            {
                if (ApplicationData.Current.LocalSettings.Values.TryGetValue("LicenseGrant", out object GrantState) && Convert.ToBoolean(GrantState))
                {
                    return(true);
                }

                if (PreLoadTask == null)
                {
                    PreLoadStoreData();
                }

                await PreLoadTask;

                if (License != null)
                {
                    if (License.AddOnLicenses.Any((Item) => Item.Value.InAppOfferToken == "Donation"))
                    {
                        ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = true;
                        return(true);
                    }
                    else
                    {
                        if (License.IsActive)
                        {
                            if (License.IsTrial)
                            {
                                ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = false;
                                return(false);
                            }
                            else
                            {
                                ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = true;
                                return(true);
                            }
                        }
                        else
                        {
                            ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = false;
                            return(false);
                        }
                    }
                }
                else
                {
                    ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = false;
                    return(false);
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"{nameof(CheckPurchaseStatusAsync)} threw an exception");
                return(false);
            }
        }
        public 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.UseIndexerWhenAvailable
                        };
                        Options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size" });

                        StorageFileQueryResult Query = Folder.CreateFileQueryWithOptions(Options);

                        uint FileCount = await Query.GetItemCountAsync();

                        ulong TotalSize = 0;

                        for (uint Index = 0; Index < FileCount && !CancelToken.IsCancellationRequested; Index += 50)
                        {
                            foreach (StorageFile File in await Query.GetFilesAsync(Index, 50))
                            {
                                TotalSize += await File.GetSizeRawDataAsync().ConfigureAwait(false);

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

                        return(TotalSize);
                    }
                    else
                    {
                        return(0);
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"{nameof(GetFolderSizeAsync)} failed for uwp API");
                    return(0);
                }
            }
        }
Exemple #13
0
        public async Task <bool> CheckPurchaseStatusAsync()
        {
            try
            {
                if (ApplicationData.Current.LocalSettings.Values.TryGetValue("LicenseGrant", out object GrantState) && Convert.ToBoolean(GrantState))
                {
                    return(true);
                }

                if (HasVerifiedLicense && ApplicationData.Current.LocalSettings.Values.ContainsKey("LicenseGrant"))
                {
                    return(Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values["LicenseGrant"]));
                }
                else
                {
                    HasVerifiedLicense = true;

                    StoreAppLicense License = GetLicenseTask == null ? await Store.GetAppLicenseAsync() : await GetLicenseTask.ConfigureAwait(false);

                    if (License.AddOnLicenses.Any((Item) => Item.Value.InAppOfferToken == "Donation"))
                    {
                        ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = true;
                        return(true);
                    }
                    else
                    {
                        if (License.IsActive)
                        {
                            if (License.IsTrial)
                            {
                                ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = false;
                                return(false);
                            }
                            else
                            {
                                ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = true;
                                return(true);
                            }
                        }
                        else
                        {
                            ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = false;
                            return(false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"{nameof(CheckPurchaseStatusAsync)} threw an exception");
                return(false);
            }
        }
 public override async Task <IStorageItem> GetStorageItemAsync()
 {
     try
     {
         return(StorageItem ??= (TempStorageItem ?? await StorageFolder.GetFolderFromPathAsync(Path)));
     }
     catch (Exception ex)
     {
         LogTracer.Log(ex, $"Could not get StorageFolder, Path: {Path}");
         return(null);
     }
 }
Exemple #15
0
 public async override Task <IStorageItem> GetStorageItemAsync()
 {
     try
     {
         return(await StorageFile.GetFileFromPathAsync(Path));
     }
     catch (Exception ex)
     {
         LogTracer.Log(ex, $"Could not get StorageFile, Path: {Path}");
         return(null);
     }
 }
Exemple #16
0
        public static List <string> GetStorageItemsPath(string Path, bool IncludeHiddenItem, ItemFilters Filter)
        {
            if (string.IsNullOrWhiteSpace(Path))
            {
                throw new ArgumentNullException(nameof(Path), "Argument could not be null");
            }

            IntPtr Ptr = FindFirstFileExFromApp(System.IO.Path.Combine(Path, "*"), FINDEX_INFO_LEVELS.FindExInfoBasic, out WIN32_FIND_DATA Data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, FIND_FIRST_EX_LARGE_FETCH);

            try
            {
                if (Ptr.ToInt64() != -1)
                {
                    List <string> Result = new List <string>();

                    do
                    {
                        FileAttributes Attribute = (FileAttributes)Data.dwFileAttributes;

                        if (IncludeHiddenItem || !Attribute.HasFlag(FileAttributes.Hidden))
                        {
                            if (((FileAttributes)Data.dwFileAttributes).HasFlag(FileAttributes.Directory) && Filter.HasFlag(ItemFilters.Folder))
                            {
                                if (Data.cFileName != "." && Data.cFileName != "..")
                                {
                                    Result.Add(System.IO.Path.Combine(Path, Data.cFileName));
                                }
                            }
                            else if (Filter.HasFlag(ItemFilters.File))
                            {
                                Result.Add(System.IO.Path.Combine(Path, Data.cFileName));
                            }
                        }
                    }while (FindNextFile(Ptr, out Data));

                    return(Result);
                }
                else
                {
                    LogTracer.Log(new Win32Exception(Marshal.GetLastWin32Error()));
                    return(new List <string>());
                }
            }
            catch
            {
                return(new List <string>());
            }
            finally
            {
                FindClose(Ptr);
            }
        }
Exemple #17
0
        private static void QueueProcessHandler()
        {
            while (true)
            {
                if (OpeartionQueue.IsEmpty)
                {
                    QueueProcessSleepLocker.WaitOne();
                }

                try
                {
                    while (OpeartionQueue.TryDequeue(out OperationListBaseModel Model))
                    {
Retry:
                        if (Model.Status != OperationStatus.Cancelled)
                        {
                            if (Model is not(OperationListCompressionModel or OperationListDecompressionModel))
                            {
                                if (FullTrustProcessController.AvailableControllerNum < FullTrustProcessController.DynamicBackupProcessNum)
                                {
                                    Thread.Sleep(1000);
                                    goto Retry;
                                }
                            }

                            if (AllowParalledExecution)
                            {
                                Thread SubThread = new Thread(() =>
                                {
                                    ExecuteSubTaskCore(Model);
                                })
                                {
                                    IsBackground = true,
                                    Priority     = ThreadPriority.Normal
                                };

                                SubThread.Start();
                            }
                            else
                            {
                                ExecuteSubTaskCore(Model);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "QueueOperation threw an exception");
                }
            }
        }
        public static async Task <FileSystemStorageItemBase> OpenAsync(string Path)
        {
            if (System.IO.Path.GetPathRoot(Path) != Path && WIN_Native_API.GetStorageItem(Path) is FileSystemStorageItemBase Item)
            {
                return(Item);
            }
            else
            {
                LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    string DirectoryPath = System.IO.Path.GetDirectoryName(Path);

                    if (string.IsNullOrEmpty(DirectoryPath))
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(Path);

                        return(new FileSystemStorageFolder(Folder, await Folder.GetThumbnailBitmapAsync(), await Folder.GetModifiedTimeAsync()));
                    }
                    else
                    {
                        StorageFolder ParentFolder = await StorageFolder.GetFolderFromPathAsync(DirectoryPath);

                        switch (await ParentFolder.TryGetItemAsync(System.IO.Path.GetFileName(Path)))
                        {
                        case StorageFolder Folder:
                        {
                            return(new FileSystemStorageFolder(Folder, await Folder.GetThumbnailBitmapAsync(), await Folder.GetModifiedTimeAsync()));
                        }

                        case StorageFile File:
                        {
                            return(new FileSystemStorageFile(File, await File.GetThumbnailBitmapAsync(), await File.GetSizeRawDataAsync(), await File.GetModifiedTimeAsync()));
                        }

                        default:
                        {
                            LogTracer.Log($"UWP storage API could not found the path: \"{Path}\"");
                            return(null);
                        }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"UWP storage API could not found the path: \"{Path}\"");
                    return(null);
                }
            }
        }
Exemple #19
0
        public static async Task <FileSystemStorageItemBase> OpenAsync(string Path)
        {
            if (WIN_Native_API.CheckLocationAvailability(System.IO.Path.GetDirectoryName(Path)))
            {
                return(WIN_Native_API.GetStorageItem(Path));
            }
            else
            {
                LogTracer.Log($"Native API could not found the path: \"{Path}\", fall back to UWP storage API");

                try
                {
                    string DirectoryPath = System.IO.Path.GetDirectoryName(Path);

                    if (string.IsNullOrEmpty(DirectoryPath))
                    {
                        StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(Path);

                        return(await CreateFromStorageItemAsync(Folder));
                    }
                    else
                    {
                        StorageFolder ParentFolder = await StorageFolder.GetFolderFromPathAsync(DirectoryPath);

                        switch (await ParentFolder.TryGetItemAsync(System.IO.Path.GetFileName(Path)))
                        {
                        case StorageFolder Folder:
                        {
                            return(await CreateFromStorageItemAsync(Folder));
                        }

                        case StorageFile File:
                        {
                            return(await CreateFromStorageItemAsync(File));
                        }

                        default:
                        {
                            LogTracer.Log($"UWP storage API could not found the path: \"{Path}\"");
                            return(null);
                        }
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, $"UWP storage API could not found the path: \"{Path}\"");
                    return(null);
                }
            }
        }
Exemple #20
0
        public static (uint, uint) CalculateFolderAndFileCount(string Path, CancellationToken CancelToken = default)
        {
            if (string.IsNullOrWhiteSpace(Path))
            {
                throw new ArgumentException("Argument could not be empty", nameof(Path));
            }

            IntPtr Ptr = FindFirstFileExFromApp(System.IO.Path.Combine(Path, "*"), FINDEX_INFO_LEVELS.FindExInfoBasic, out WIN32_FIND_DATA Data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, FIND_FIRST_EX_LARGE_FETCH);

            try
            {
                if (Ptr.ToInt64() != -1)
                {
                    uint FolderCount = 0;
                    uint FileCount   = 0;

                    do
                    {
                        if (((FileAttributes)Data.dwFileAttributes).HasFlag(FileAttributes.Directory))
                        {
                            if (Data.cFileName != "." && Data.cFileName != "..")
                            {
                                (uint SubFolderCount, uint SubFileCount) = CalculateFolderAndFileCount(System.IO.Path.Combine(Path, Data.cFileName), CancelToken);
                                FolderCount += ++SubFolderCount;
                                FileCount   += SubFileCount;
                            }
                        }
                        else
                        {
                            FileCount++;
                        }
                    }while (FindNextFile(Ptr, out Data) && !CancelToken.IsCancellationRequested);

                    return(FolderCount, FileCount);
                }
                else
                {
                    LogTracer.Log(new Win32Exception(Marshal.GetLastWin32Error()));
                    return(0, 0);
                }
            }
            catch
            {
                return(0, 0);
            }
            finally
            {
                FindClose(Ptr);
            }
        }
Exemple #21
0
        public static bool CheckContainsAnyItem(string Path, ItemFilters Filter)
        {
            if (string.IsNullOrWhiteSpace(Path))
            {
                throw new ArgumentException("Argument could not be empty", nameof(Path));
            }

            IntPtr Ptr = FindFirstFileExFromApp(System.IO.Path.Combine(Path, "*"), FINDEX_INFO_LEVELS.FindExInfoBasic, out WIN32_FIND_DATA Data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, FIND_FIRST_EX_LARGE_FETCH);

            try
            {
                if (Ptr.ToInt64() != -1)
                {
                    do
                    {
                        FileAttributes Attribute = (FileAttributes)Data.dwFileAttributes;

                        if (!Attribute.HasFlag(FileAttributes.System))
                        {
                            if (Attribute.HasFlag(FileAttributes.Directory) && Filter.HasFlag(ItemFilters.Folder))
                            {
                                if (Data.cFileName != "." && Data.cFileName != "..")
                                {
                                    return(true);
                                }
                            }
                            else if (Filter.HasFlag(ItemFilters.File) && !Data.cFileName.EndsWith(".url", StringComparison.OrdinalIgnoreCase))
                            {
                                return(true);
                            }
                        }
                    }while (FindNextFile(Ptr, out Data));

                    return(false);
                }
                else
                {
                    LogTracer.Log(new Win32Exception(Marshal.GetLastWin32Error()));
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
            finally
            {
                FindClose(Ptr);
            }
        }
Exemple #22
0
        public static async Task <ExtendedExecutionController> TryCreateExtendedExecution()
        {
            await SlimLocker.WaitAsync();

            try
            {
                if (IsRequestExtensionSent)
                {
                    return(new ExtendedExecutionController());
                }
                else
                {
                    if (Session == null)
                    {
                        Session = new ExtendedExecutionSession
                        {
                            Reason = ExtendedExecutionReason.Unspecified
                        };

                        Session.Revoked += Session_Revoked;
                    }

                    switch (await Session.RequestExtensionAsync())
                    {
                    case ExtendedExecutionResult.Allowed:
                    {
                        IsRequestExtensionSent = true;
                        return(new ExtendedExecutionController());
                    }

                    default:
                    {
                        IsRequestExtensionSent = false;
                        LogTracer.Log("Extension execution was rejected by system");
                        return(null);
                    }
                    }
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, "An exception was threw when creating the extended execution");
                IsRequestExtensionSent = false;
                return(null);
            }
            finally
            {
                SlimLocker.Release();
            }
        }
Exemple #23
0
        public static Task CopyToAsync(this Stream From, Stream To, long Length = -1, ProgressChangedEventHandler ProgressHandler = null, CancellationToken CancelToken = default)
        {
            return(Task.Run(() =>
            {
                try
                {
                    long TotalBytesRead = 0;
                    long TotalBytesLength = Length > 0 ? Length : From.Length;

                    byte[] DataBuffer = new byte[4096];

                    int ProgressValue = 0;

                    while (true)
                    {
                        int bytesRead = From.Read(DataBuffer, 0, DataBuffer.Length);

                        if (bytesRead > 0)
                        {
                            To.Write(DataBuffer, 0, bytesRead);
                            TotalBytesRead += bytesRead;
                        }
                        else
                        {
                            To.Flush();
                            break;
                        }

                        if (TotalBytesLength > 1024 * 1024)
                        {
                            int LatestValue = Convert.ToInt32(TotalBytesRead * 100d / TotalBytesLength);

                            if (LatestValue > ProgressValue)
                            {
                                ProgressValue = LatestValue;
                                ProgressHandler.Invoke(null, new ProgressChangedEventArgs(ProgressValue, null));
                            }
                        }

                        CancelToken.ThrowIfCancellationRequested();
                    }
                }
                catch (Exception ex) when(ex is not OperationCanceledException)
                {
                    LogTracer.Log(ex, "Could not track the progress of coping the stream");
                    From.CopyTo(To);
                }
            }));
        }
        private async void Store_OfflineLicensesChanged(StoreContext sender, object args)
        {
            try
            {
                StoreAppLicense License = await sender.GetAppLicenseAsync();

                if (License.IsActive && !License.IsTrial)
                {
                    ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = true;
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"{nameof(Store_OfflineLicensesChanged)} threw an exception");
            }
        }
Exemple #25
0
        public static ulong CalculateSize(string Path, CancellationToken CancelToken = default)
        {
            if (string.IsNullOrWhiteSpace(Path))
            {
                throw new ArgumentException("Argument could not be empty", nameof(Path));
            }

            IntPtr Ptr = FindFirstFileExFromApp(System.IO.Path.Combine(Path, "*"), FINDEX_INFO_LEVELS.FindExInfoBasic, out WIN32_FIND_DATA Data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, FIND_FIRST_EX_LARGE_FETCH);

            try
            {
                if (Ptr.ToInt64() != -1)
                {
                    ulong TotalSize = 0;

                    do
                    {
                        if (((FileAttributes)Data.dwFileAttributes).HasFlag(FileAttributes.Directory))
                        {
                            if (Data.cFileName != "." && Data.cFileName != "..")
                            {
                                TotalSize += CalculateSize(System.IO.Path.Combine(Path, Data.cFileName), CancelToken);
                            }
                        }
                        else
                        {
                            TotalSize += ((ulong)Data.nFileSizeHigh << 32) + Data.nFileSizeLow;
                        }
                    }while (FindNextFile(Ptr, out Data) && !CancelToken.IsCancellationRequested);

                    return(TotalSize);
                }
                else
                {
                    LogTracer.Log(new Win32Exception(Marshal.GetLastWin32Error()));
                    return(0);
                }
            }
            catch
            {
                return(0);
            }
            finally
            {
                FindClose(Ptr);
            }
        }
Exemple #26
0
        private void View_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            if (AllowProcess && 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 RelativeStartPoint = new Point(AbsStartPoint.X - InnerScrollView.HorizontalOffset, AbsStartPoint.Y - InnerScrollView.VerticalOffset);

                        DrawRectangleInCanvas(RelativeStartPoint, RelativeEndPoint);

                        GeneralTransform AbsToWindowTransform = View.TransformToVisual(Window.Current.Content);

                        Rect SelectedRect = new Rect(RelativeStartPoint, RelativeEndPoint);

                        if (SelectedRect.Width >= 20 && SelectedRect.Height >= 20)
                        {
                            IEnumerable <FileSystemStorageItemBase> SelectedList = VisualTreeHelper.FindElementsInHostCoordinates(AbsToWindowTransform.TransformBounds(SelectedRect), View).OfType <SelectorItem>().Select((Item) => Item.Content as FileSystemStorageItemBase);

                            foreach (FileSystemStorageItemBase Item in View.SelectedItems.OfType <FileSystemStorageItemBase>().Except(SelectedList).Where((Item) => (View.ContainerFromItem(Item) as SelectorItem).IsVisibleOnContainer(View)))
                            {
                                View.SelectedItems.Remove(Item);
                            }

                            foreach (FileSystemStorageItemBase Item in SelectedList.Except(View.SelectedItems.OfType <FileSystemStorageItemBase>()))
                            {
                                View.SelectedItems.Add(Item);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex);
                    }
                    finally
                    {
                        _ = Interlocked.Exchange(ref Locker, 0);
                    }
                }
            }
        }
Exemple #27
0
        public static async Task <bool> CheckExistAsync(string Path)
        {
            if (!string.IsNullOrEmpty(Path) && System.IO.Path.IsPathRooted(Path))
            {
                if (WIN_Native_API.CheckLocationAvailability(System.IO.Path.GetDirectoryName(Path)))
                {
                    return(WIN_Native_API.CheckExist(Path));
                }
                else
                {
                    try
                    {
                        string DirectoryPath = System.IO.Path.GetDirectoryName(Path);

                        if (string.IsNullOrEmpty(DirectoryPath))
                        {
                            await StorageFolder.GetFolderFromPathAsync(Path);

                            return(true);
                        }
                        else
                        {
                            StorageFolder Folder = await StorageFolder.GetFolderFromPathAsync(DirectoryPath);

                            if (await Folder.TryGetItemAsync(System.IO.Path.GetFileName(Path)) != null)
                            {
                                return(true);
                            }
                            else
                            {
                                return(false);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTracer.Log(ex, "CheckExist threw an exception");
                        return(false);
                    }
                }
            }
            else
            {
                return(false);
            }
        }
        public async Task <StorePurchaseStatus> PurchaseAsync()
        {
            try
            {
                if (PreLoadTask == null)
                {
                    PreLoadStoreData();
                }

                await PreLoadTask;

                if (ProductResult != null && ProductResult.ExtendedError == null)
                {
                    if (ProductResult.Product != null)
                    {
                        StorePurchaseResult Result = await ProductResult.Product.RequestPurchaseAsync();

                        switch (Result.Status)
                        {
                        case StorePurchaseStatus.AlreadyPurchased:
                        case StorePurchaseStatus.Succeeded:
                        {
                            ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = true;
                            break;
                        }
                        }

                        return(Result.Status);
                    }
                    else
                    {
                        return(StorePurchaseStatus.NetworkError);
                    }
                }
                else
                {
                    return(StorePurchaseStatus.NetworkError);
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"{nameof(PurchaseAsync)} threw an exception");
                return(StorePurchaseStatus.NetworkError);
            }
        }
Exemple #29
0
        public static async Task LoadDeviceAsync()
        {
            if (Interlocked.Exchange(ref LoadDriveLockResource, 1) == 0)
            {
                try
                {
                    if (!IsDriveLoaded)
                    {
                        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.Folder.Path != NewItem.RootDirectory.FullName)))
                        {
                            try
                            {
                                StorageFolder DriveFolder = await StorageFolder.GetFolderFromPathAsync(Drive.RootDirectory.FullName);

                                DriveList.Add(await DriveRelatedData.CreateAsync(DriveFolder, Drive.DriveType));
                            }
                            catch (Exception ex)
                            {
                                LogTracer.Log(ex, $"Hide the device \"{Drive.RootDirectory.FullName}\" for error");
                            }
                        }

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

                        NetworkDriveCheckTimer.Start();
                    }
                }
                finally
                {
                    _ = Interlocked.Exchange(ref LoadDriveLockResource, 0);
                }
            }
        }
Exemple #30
0
        public async Task <StorePurchaseStatus> PurchaseAsync()
        {
            try
            {
                await Task.Run(() =>
                {
                    InitLocker.WaitOne();
                });

                StoreProductResult ProductResult = await Store.GetStoreProductForCurrentAppAsync();

                if (ProductResult.ExtendedError == null)
                {
                    if (ProductResult.Product != null)
                    {
                        StorePurchaseResult Result = await ProductResult.Product.RequestPurchaseAsync();

                        switch (Result.Status)
                        {
                        case StorePurchaseStatus.AlreadyPurchased:
                        case StorePurchaseStatus.Succeeded:
                        {
                            ApplicationData.Current.LocalSettings.Values["LicenseGrant"] = true;
                            break;
                        }
                        }

                        return(Result.Status);
                    }
                    else
                    {
                        return(StorePurchaseStatus.NetworkError);
                    }
                }
                else
                {
                    return(StorePurchaseStatus.NetworkError);
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex, $"{nameof(PurchaseAsync)} threw an exception");
                return(StorePurchaseStatus.NetworkError);
            }
        }