Пример #1
0
        async void LoadStudentDetails()
        {
            // Check to see if file exists
            //Get local storage folder
            StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            //create a file query
            StorageFileQueryResult fileResults = storageFolder.CreateFileQuery();
            //Get all files in the directory
            IReadOnlyList <StorageFile> fileList = await fileResults.GetFilesAsync();

            //check to see if we have a file
            studentsFile = fileList.SingleOrDefault(file => file.Name == "students.txt");
            if (studentsFile == null)
            {
                //if not create
                studentsFile = await storageFolder.CreateFileAsync("students.txt");
            }
            else
            {
                //else load from a stream
                using (StreamReader reader = new StreamReader(await studentsFile.OpenStreamForReadAsync()))
                {
                    while (!reader.EndOfStream)
                    {
                        string  line    = reader.ReadLine();
                        Student student = new Student();
                        student.parse(line);
                        RegisteredStudents.Add(student);
                    }
                }
            }
        }
Пример #2
0
        public async Task Initialize(ICamera camera, IStorage storage)
        {
            this.camera  = camera;
            this.storage = storage;

            var cacheFolder = KnownFolders.PicturesLibrary;

            this.dropFolder = await cacheFolder.GetFolderAsync("securitysystem-cameradrop");

            this.dropFolderWatcher = dropFolder.CreateFileQuery();

            var images = await this.dropFolderWatcher.GetFilesAsync();

            var orderedImages = images.OrderByDescending(x => x.DateCreated);

            this.newestImage = orderedImages.FirstOrDefault();

            this.dropFolderWatcher.ContentsChanged += DropFolderWatcher_ContentsChanged;

            this.allJoynBusAttachment = new AllJoynBusAttachment();
            this.producer             = new SecuritySystemProducer(this.allJoynBusAttachment);
            this.allJoynBusAttachment.AboutData.DefaultAppName      = Package.Current.DisplayName;
            this.allJoynBusAttachment.AboutData.DefaultDescription  = Package.Current.Description;
            this.allJoynBusAttachment.AboutData.DefaultManufacturer = Package.Current.Id.Publisher;
            this.allJoynBusAttachment.AboutData.SoftwareVersion     = Package.Current.Id.Version.ToString();
            this.allJoynBusAttachment.AboutData.IsEnabled           = true;
            this.producer.Service = this;
            this.producer.Start();
        }
Пример #3
0
        public static async Task <List <string> > GetMatchingFilesByPrefixAsync(string prefix, List <string> excludeFiles)
        {
            try
            {
                List <string> result       = new List <string>();
                var           folder       = ApplicationData.Current.LocalFolder;
                QueryOptions  queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new List <string>()
                {
                    "*"
                });
                queryOptions.UserSearchFilter = $"{prefix}*.*";
                queryOptions.FolderDepth      = FolderDepth.Shallow;
                queryOptions.IndexerOption    = IndexerOption.UseIndexerWhenAvailable;
                StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions);

                IReadOnlyList <StorageFile> matchingFiles = await queryResult.GetFilesAsync();

                if (matchingFiles.Count > 0)
                {
                    result.AddRange(
                        matchingFiles.Where(f => !excludeFiles.Contains(f.Name)).Select(f => f.Name)
                        );
                }
                return(result);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            return(null);
        }
Пример #4
0
        public void LoadContent(StorageFolder folder)
        {
            Thumbnails.Clear();
            List <string> fileTypeFilter = new List <string>();

            fileTypeFilter.Add(".jpg");
            fileTypeFilter.Add(".jpeg");
            fileTypeFilter.Add(".png");
            fileTypeFilter.Add(".bmp");
            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, fileTypeFilter);

            Task.Run(async() =>
            {
                StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions);
                var files = await queryResult.GetFilesAsync();
                foreach (var file in files)
                {
                    if (IsImageFile(file))
                    {
                        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            Thumbnails.Add(new ImageViewerItem(file));
                        });
                    }
                }
            });
        }
Пример #5
0
        private async void ReadAllFiles()
        {
            // Get the app's installation folder.
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            // Get the files in the current folder.
            StorageFileQueryResult results = storageFolder.CreateFileQuery();

            // Iterate over the results and print the list of files
            // to the Visual Studio Output window.
            IReadOnlyList <StorageFile> filesInFolder = await results.GetFilesAsync();

            foreach (StorageFile item in filesInFolder)
            {
                TextBlock tb = new TextBlock();
                tb.Text = item.Name;

                StackPanel sp = new StackPanel();
                sp.Tag         = item.Name;
                sp.Orientation = Orientation.Vertical;
                sp.Tapped     += Sp_Tapped;
                sp.Children.Add(tb);

                outerWrapper.Children.Add(sp);
            }
        }
Пример #6
0
 public void Stop()
 {
     if (_query != null)
     {
         _query = null;
     }
     if (_onboardingProducer != null)
     {
         _onboardingProducer.Stop();
         _onboardingProducer = null;
     }
     if (_iconProducer != null)
     {
         _iconProducer.Stop();
         _iconProducer = null;
     }
     if (_busAttachment != null)
     {
         _busAttachment = null;
     }
     if (_softAccessPoint != null)
     {
         _softAccessPoint.Stop();
         _softAccessPoint = null;
     }
     if (_deviceWatcher != null)
     {
         _deviceWatcher.Stop();
         _deviceWatcher = null;
     }
     _wlanAdapterId = null;
     _state         = OnboardingState.NotConfigured;
 }
Пример #7
0
 public static async Task<IReadOnlyList<StorageFile>> GetFilesInFolder(List<string> fileTypeFilter, StorageFolder folder)
 {
     if (folder == null || fileTypeFilter == null || fileTypeFilter.Count == 0)
     {
         return null;
     }
     else
     {
         try
         {
             QueryOptions queryOptions = new QueryOptions();
             foreach (var item in fileTypeFilter)
             {
                 if (item.IndexOf(".") == 0)
                 {
                     queryOptions.FileTypeFilter.Add(item);
                 }
                 else
                 {
                     continue;
                 }
             }
             StorageFileQueryResult results = folder.CreateFileQueryWithOptions(queryOptions);
             return await results.GetFilesAsync();
         }
         catch (IOException)
         {
             return null;
         }
         catch (UnauthorizedAccessException)
         {
             return null;
         }
     }
 }
Пример #8
0
        public static async Task <IReadOnlyList <Picture> > GetPicturesByAlbum(string albumName)
        {
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
            var           allPicsList   = new List <Picture>();
            // Set options for file type and sort order.
            List <string> fileTypeFilter = new List <string>();

            fileTypeFilter.Add(".jpg");
            fileTypeFilter.Add(".png");
            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);
            // Get the JPG files in the user's Pictures folder
            // and its subfolders and sort them by date.
            StorageFileQueryResult results = storageFolder.CreateFileQueryWithOptions(queryOptions);

            IReadOnlyList <StorageFile> files = await results.GetFilesAsync();


            foreach (StorageFile file in files.OrderBy(a => a.DateCreated))
            {
                var pic = new Picture()
                {
                    picName   = file.Name,
                    albumName = null,
                    path      = file.Path,
                    dateAdded = file.DateCreated.LocalDateTime
                };
                allPicsList.Add(pic);
            }
            return(allPicsList);
        }
Пример #9
0
        public async Task <IEnumerable <StorageFile> > GetStorageFilesInFolderAsync(StorageFolder folder)
        {
            //Get query options with which we search for files in the specified folder
            var options = DirectoryWalker.GetQueryOptions();

            /*
             * options.FileTypeFilter.Add(".mp3");
             * options.FileTypeFilter.Add(".wav");
             * options.FileTypeFilter.Add(".ogg");
             * options.FileTypeFilter.Add(".flac");
             * options.FileTypeFilter.Add(".m4a");
             * options.FileTypeFilter.Add(".aif");
             * options.FileTypeFilter.Add(".wma");*/

            //this is the query result which we recieve after querying in the folder
            StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(options);

            //'count' is for total files got after querying.
            uint count = await queryResult.GetItemCountAsync();

            //the event for files changed
            queryResult.ContentsChanged += QueryResult_ContentsChanged;

            if (count == 0)
            {
                string error = "No songs found!";
                BLogger.Logger.Error("No songs were found!");
                await SharedLogic.NotificationManager.ShowMessageAsync(error);

                return(null);
            }

            return(await queryResult.GetFilesAsync());
        }
Пример #10
0
        private async Task LoadPicturesFromAlbums()
        {
            //Ordering album files by date
            // initialize queryOptions using a common query
            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new string[] { ".txt" });

            // clear all existing sorts
            queryOptions.SortOrder.Clear();

            // add ascending sort by date modified
            SortEntry se = new SortEntry();

            se.PropertyName   = "System.DateModified";
            se.AscendingOrder = true;
            queryOptions.SortOrder.Add(se);

            //Open folder containing album files
            var storageFolder = ApplicationData.Current.LocalFolder;

            //Use query to sort album data text files by date
            StorageFileQueryResult      queryResult = storageFolder.CreateFileQueryWithOptions(queryOptions);
            IReadOnlyList <StorageFile> textFiles   = await queryResult.GetFilesAsync();

            foreach (var textFile in textFiles)
            {
                if (textFile.Name != "Library.txt")
                {
                    await dynamicControlAsync(textFile.Name);
                }
            }
        }
Пример #11
0
        public async static Task AddStorageFilesToLibrary(StorageFileQueryResult queryResult)
        {
            foreach (var file in await queryResult.GetFilesAsync())
            {
                Mediafile mp3file = null;
                int       index   = -1;
                if (file != null)
                {
                    if (TracksCollection.Elements.Any(t => t.Path == file.Path))
                    {
                        index = TracksCollection.Elements.IndexOf(TracksCollection.Elements.First(t => t.Path == file.Path));
                        RemoveMediafile(TracksCollection.Elements.First(t => t.Path == file.Path));
                    }
                    //this methods notifies the Player that one song is loaded. We use both 'count' and 'i' variable here to report current progress.
                    await NotificationManager.ShowAsync(" Song(s) Loaded", "Loading...");

                    await Task.Run(async() =>
                    {
                        //here we load into 'mp3file' variable our processed Song. This is a long process, loading all the properties and the album art.
                        mp3file = await SharedLogic.CreateMediafile(file, false); //the core of the whole method.
                        await SaveSingleFileAlbumArtAsync(mp3file, file).ConfigureAwait(false);
                    });

                    AddMediafile(mp3file, index);
                }
            }
        }
Пример #12
0
        public async Task GetAppFiles(string searchKey)
        {
            try
            {
                List <string> fileTypeFilter = new List <string>
                {
                    searchKey
                };

                QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);

                StorageFileQueryResult queryResult = this.SearchedDirectory.CreateFileQueryWithOptions(queryOptions);

                var files = await queryResult.GetFilesAsync();

                foreach (var file in files)
                {
                    var copyTo = Path.Combine(this.OutputDirectory, file.Name);
                    await file.CopyAsync(this.folder, file.DisplayName, NameCollisionOption.ReplaceExisting);
                }
            }
            catch (Exception e) when(e is IOException || e is UnauthorizedAccessException || e is ArgumentException)
            {
                throw;
            }
        }
Пример #13
0
        private async void FindGif()
        {
            List <string> fileTypeFilter = new List <string>
            {
                ".gif"
            };

            var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter)
            {
                ApplicationSearchFilter = "System.FileName:*\"" + Path.GetFileNameWithoutExtension(File.Name) + "\"*"
            };

            StorageFolder folder = await File.GetParentAsync();

            StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions);

            var files = await queryResult.GetFilesAsync();

            if (files.Count > 0)
            {
                IRandomAccessStream fileStream = await files[0].OpenAsync(FileAccessMode.Read);
                BitmapImage         image      = new BitmapImage();
                image.SetSource(fileStream);
                Gif = image;
            }
        }
Пример #14
0
        /// <summary>
        /// 指定フォルダ以下にある画像ファイルのみを抽出して返す
        /// </summary>
        /// <param name="folder"></param>
        /// <returns></returns>
        private async Task <IReadOnlyList <StorageFile> > getImageFilesAsync(StorageFolder folder)
        {
            QueryOptions           queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, FileKind.GetImageFilterList());
            StorageFileQueryResult queryResult  = folder.CreateFileQueryWithOptions(queryOptions);

            return(await queryResult.GetFilesAsync());
        }
Пример #15
0
            private async Task Create(FolderViewModel vm)
            {
                var sf = await vm.GetStorageFolderAsync();

                var options = new QueryOptions
                {
                    FolderDepth             = FolderDepth.Deep,
                    IndexerOption           = IndexerOption.DoNotUseIndexer,
                    ApplicationSearchFilter = ComposeFilters(),
                };

                options.FileTypeFilter.AddRange(Statics.AudioFileTypes);

                Query = sf.CreateFileQueryWithOptions(options);
                // Event "ContentsChanged" only fires after GetFilesAsync has been called at least once.
                await Query.GetFilesAsync();

                _subscription = Observable.FromEventPattern <TypedEventHandler <IStorageQueryResultBase, object>, object>(
                    h => Query.ContentsChanged += h, h => Query.ContentsChanged -= h)
                                //.SkipUntil(autoRefresh.Where(x => x == true))
                                //.TakeUntil(autoRefresh.Where(x => x == false))
                                //.Repeat()
                                .Select(_ => Unit.Default)
                                .Subscribe(_contentChanged);
            }
Пример #16
0
        private async void LoadVideosFromFolder(StorageFolder selectedFolder)
        {
            if (selectedFolder != null)
            {
                // Clear old files.
                importingList.Clear();

                // Filter to get video files only.
                List <string> fileTypeFilter = new List <string>
                {
                    ".mp4",
                    ".wmv",
                    ".mkv",
                    ".avi"
                };
                QueryOptions                queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);
                StorageFileQueryResult      results      = selectedFolder.CreateFileQueryWithOptions(queryOptions);
                IReadOnlyList <StorageFile> fileList     = await results.GetFilesAsync();

                // Populate file list.
                foreach (StorageFile file in fileList)
                {
                    importingList.Add(new VideoFile(file));
                }

                StatusText.Text = "Loaded " + importingList.Count + " files.";
            }

            TextFileNum.Text = importingList.Count + " files";
        }
Пример #17
0
        private async void LoadFolder(StorageFolder selectedFolder)
        {
            if (selectedFolder != null)
            {
                // Clear old files.
                displayedFileList.Clear();

                // Application now has read/write access to all contents in the picked folder (including other sub-folder contents).
                StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", selectedFolder);

                // Filter to get video files only.
                List <string> fileTypeFilter = new List <string>
                {
                    ".mp4",
                    ".wmv",
                    ".mkv",
                    ".avi"
                };
                QueryOptions                queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);
                StorageFileQueryResult      results      = selectedFolder.CreateFileQueryWithOptions(queryOptions);
                IReadOnlyList <StorageFile> fileList     = await results.GetFilesAsync();

                // Populate file list.
                foreach (StorageFile file in fileList)
                {
                    displayedFileList.Add(new VideoFile(file));
                }
            }
        }
Пример #18
0
        /// <summary>
        /// This is the click handler for the button that represents a user.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void UserButton_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;

            if (b != null)
            {
                OutputProgressRing.IsActive = true;

                // Get the folder that represents the user's files, which wwe saved as the DataContext.
                StorageFolder folder = (StorageFolder)b.DataContext;

                // This try/catch block is for scenarios where the HomeGroup Known Folder is not available.
                try
                {
                    // Search for all files in that folder.
                    QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, null);
                    queryOptions.UserSearchFilter = "*";
                    StorageFileQueryResult      queryResults = folder.CreateFileQueryWithOptions(queryOptions);
                    IReadOnlyList <StorageFile> files        = await queryResults.GetFilesAsync();

                    string outputString = string.Format("Files shared by {0}: {1}\n", folder.Name, files.Count);
                    foreach (StorageFile file in files)
                    {
                        outputString += file.Name + "\n";
                    }
                    rootPage.NotifyUser(outputString, NotifyType.StatusMessage);
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                }
                OutputProgressRing.IsActive = false;
            }
        }
Пример #19
0
        public override Task <IList <StorageMedia> > LoadDataAsync()
        {
            return(Task.Run <IList <StorageMedia> >(async() =>
            {
                using (await _loadMoreLock.WaitAsync())
                {
                    if (_query == null)
                    {
                        await KnownFolders.PicturesLibrary.TryGetItemAsync("yolo");

                        var queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, Constants.MediaTypes);
                        queryOptions.FolderDepth = FolderDepth.Deep;

                        _query = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
                        _query.ContentsChanged += OnContentsChanged;
                        _startIndex = 0;
                    }

                    var items = new List <StorageMedia>();
                    var result = await _query.GetFilesAsync(_startIndex, 10);
                    _startIndex += (uint)result.Count;

                    foreach (var file in result)
                    {
                        if (await StorageMedia.CreateAsync(file) is StorageMedia storage)
                        {
                            items.Add(storage);
                        }
                    }

                    return items;
                }
            }));
        }
Пример #20
0
        /// <summary>
        /// 扫描本地Music Library的所有音乐
        /// </summary>
        /// <returns>返回所有的音乐文件属性和相对music library的路径</returns>
        public static async Task <List <MusicPropertiesWithPath> > ScanLocalMusicInLibrary()
        {
            StorageFolder folder = KnownFolders.MusicLibrary;

            List <MusicPropertiesWithPath> songs = new List <MusicPropertiesWithPath>();

            StorageFileQueryResult query = folder.CreateFileQuery(CommonFileQuery.OrderByMusicProperties);

            //var files = await folder.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByMusicProperties);
            var files = await query.GetFilesAsync();

            foreach (var file in files)
            {
                var properties = await file.Properties.GetMusicPropertiesAsync();

                try
                {
                    using (var stream = await file.OpenReadAsync())
                    {
                        songs.Add(new MusicPropertiesWithPath()
                        {
                            DefinedProperties = properties,
                            FileName          = file.Path.Substring(file.Path.IndexOf("Music")).Remove(0, 6)
                        });
                    }
                }
                catch (Exception ex)
                {
                }
            }

            return(songs);
        }
Пример #21
0
        /// <summary>
        /// Loads songs from a specified folder into the library. <seealso cref="LoadCommand"/>
        /// </summary>
        public async void Load()
        {
            //LibVM.Database.RemoveFolder(LibraryFoldersCollection[0].Path);
            FolderPicker picker = new FolderPicker();

            picker.FileTypeFilter.Add(".mp3");
            picker.FileTypeFilter.Add(".wav");
            picker.FileTypeFilter.Add(".ogg");
            picker.FileTypeFilter.Add(".flac");
            picker.FileTypeFilter.Add(".m4a");
            picker.FileTypeFilter.Add(".aif");
            picker.FileTypeFilter.Add(".wma");
            picker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
            picker.ViewMode         = PickerViewMode.List;
            picker.CommitButtonText = "Import";
            StorageFolder folder = await picker.PickSingleFolderAsync();

            if (folder != null)
            {
                LibraryFoldersCollection.Add(folder);
                StorageApplicationPermissions.FutureAccessList.Add(folder);
                //Get query options with which we search for files in the specified folder
                var options = Common.DirectoryWalker.GetQueryOptions();
                //this is the query result which we recieve after querying in the folder
                StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(options);
                //the event for files changed
                queryResult.ContentsChanged += QueryResult_ContentsChanged;
                await AddFolderToLibraryAsync(queryResult);
            }
        }
Пример #22
0
        public static async Task <bool> CheckIfNeedToUpdate()
        {
            try
            {
                QueryOptions Options = new QueryOptions
                {
                    ApplicationSearchFilter = "System.FileName:BingDailyPicture_Cache*",
                    FolderDepth             = FolderDepth.Shallow,
                    IndexerOption           = IndexerOption.UseIndexerWhenAvailable
                };
                StorageFileQueryResult QueryResult = ApplicationData.Current.TemporaryFolder.CreateFileQueryWithOptions(Options);

                IReadOnlyList <StorageFile> AllPreviousPictureList = await QueryResult.GetFilesAsync();

                if (AllPreviousPictureList.All((Item) => DateTime.TryParseExact(Regex.Match(Item.Name, @"(?<=\[)(.+)(?=\])").Value, "yyyy-MM-dd HH-mm-ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out DateTime LastUpdateDate) && LastUpdateDate < DateTime.Now.Date))
                {
                    foreach (StorageFile ToDelete in AllPreviousPictureList)
                    {
                        await ToDelete.DeleteAsync(StorageDeleteOption.PermanentDelete);
                    }

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
        private async void Find_Click(object sender, RoutedEventArgs e)
        {
            ContentTextOutput.Text = "";
            List <string> propertyNames = new List <string>();

            propertyNames.Add("System.FileName");
            var queryOptions = new Windows.Storage.Search.QueryOptions();

            queryOptions.IndexerOption    = Windows.Storage.Search.IndexerOption.OnlyUseIndexer;
            queryOptions.UserSearchFilter = FindQueryText.Text;
            queryOptions.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.DocumentProperties, propertyNames);

            // Query the Pictures library.
            StorageFileQueryResult      queryResult = Windows.Storage.KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
            IReadOnlyList <StorageFile> files       = await queryResult.GetFilesAsync();

            foreach (StorageFile file in files)
            {
                IDictionary <String, IReadOnlyList <Windows.Data.Text.TextSegment> > fileRangeProperties = queryResult.GetMatchingPropertiesWithRanges(file);
                if (fileRangeProperties.ContainsKey("System.FileName"))
                {
                    IReadOnlyList <Windows.Data.Text.TextSegment> ranges;
                    fileRangeProperties.TryGetValue("System.FileName", out ranges);
                    rootPage.HighlightRanges(ContentTextOutput, file.DisplayName, ranges);
                }
                // Note: You can continue looking for other properties you would like to highlight on the file here.
            }
            if (files.Count == 0)
            {
                ContentTextOutput.Text = "There were no matching files in your Pictures Library";
            }
        }
Пример #24
0
        async void GetProfilePicAsync()
        {
            string profilePicPlaceholderPath = "ms-appx:///Assets/StoreLogo.scale-400.png";

            ProfilePic = new BitmapImage(new Uri(profilePicPlaceholderPath));

            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;

            if (localSettings.Values["PerformerImageFolder"] is string token)
            {
                StorageItemAccessList futureAccessList = StorageApplicationPermissions.FutureAccessList;
                StorageFolder         profilePicFolder = await futureAccessList.GetFolderAsync(token);

                List <string> fileTypeFilter = new List <string>
                {
                    ".jpg"
                };

                var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter)
                {
                    ApplicationSearchFilter = "System.FileName:*\"" + Name + "\"*"
                };

                StorageFileQueryResult queryResult = profilePicFolder.CreateFileQueryWithOptions(queryOptions);

                var files = await queryResult.GetFilesAsync();

                if (files.Count > 0)
                {
                    BitmapImage screen = new BitmapImage();
                    screen.SetSource(await files[0].GetThumbnailAsync(ThumbnailMode.SingleItem));
                    ProfilePic = screen;
                }
            }
        }
Пример #25
0
        /// Lifecycle



        public MonitoredFolder(StorageFolder folderToObserve, EventHandler <MonitoredFolderChangedArgs> changedEventHandler)
        {
            _monitoredFolder     = folderToObserve ?? throw new ArgumentNullException(nameof(folderToObserve));
            _changedEventHandler = changedEventHandler ?? throw new ArgumentNullException(nameof(changedEventHandler));

            StartMonitoringFolderForChanges();

            // Hookup user's handler for our changed event
            this.Changed += changedEventHandler;

            // Create cancellation token
            _cancellationToken = _cancellationTokenSource.Token;

            ReportLine($"Monitoring folder '{_monitoredFolder.Name}'");

            // Start producing results
            _ = InitialScan();


            return;


            /// Local Functions


            /// <summary>Sets up monitoring _rootFolder for changes. NOTE: Not used for scans.</summary>
            void StartMonitoringFolderForChanges()
            {
                var options = new QueryOptions();

                _contentChangedMonitor = _monitoredFolder.CreateFileQueryWithOptions(options);
                _contentChangedMonitor.ContentsChanged += OnContentsChanged;
                _ = _contentChangedMonitor.GetItemCountAsync();                 // Starts monitoring for changes
            }
        }
Пример #26
0
        /// <summary>
        /// Gets all the pictures from the Local state storage folder
        /// </summary>
        /// <returns></returns>
        public async Task GetAllPictures()
        {
            // Set options for file type
            List <string> fileTypeFilter = new List <string>();

            fileTypeFilter.Add(".jpg");
            fileTypeFilter.Add(".png");
            QueryOptions           queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypeFilter);
            StorageFileQueryResult results      = Helper.storageFolder.CreateFileQueryWithOptions(queryOptions);
            //Get all the pictures asynchronously
            IReadOnlyList <StorageFile> files = await results.GetFilesAsync();

            foreach (StorageFile file in files)
            {
                //Get thumbnail for the fetched picture
                var thumb = await file.GetThumbnailAsync(thumbnailMode, size);

                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(thumb);
                var pic = new Picture()
                {
                    picName      = file.Name,
                    albumName    = null,
                    path         = file.Path,
                    dateAdded    = file.DateCreated.LocalDateTime,
                    picThumbnail = bitmapImage
                };
                //add to observable collection
                allPicsList.Add(pic);
            }
        }
Пример #27
0
        private async Task <bool> MonitorConfigFile()
        {
            bool retVal = true;

            try
            {
                // Watch for all ".xml" files (there is only the config.xml file in this app's data folder)
                // And add a handler for when the folder contents change
                var fileTypeQuery = new List <string>();
                fileTypeQuery.Add(".xml");
                var options = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.DefaultQuery, fileTypeQuery);
                _query = ApplicationData.Current.LocalFolder.CreateFileQueryWithOptions(options);
                _query.ContentsChanged += FolderContentsChanged;

                // Start Monitoring.  The first time this is called (after starting the query) we want to ignore the notification
                _bIgnoreFirstChangeNotification = true;
                var files = await _query.GetFilesAsync();
            }
            catch (Exception /*ex*/)
            {
                retVal = false;
            }

            return(retVal);
        }
Пример #28
0
        public async Task <IReadOnlyList <StorageFile> > GetFilesAsync(List <string> fileTypes)
        {
            QueryOptions                queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, fileTypes);
            StorageFileQueryResult      queryResult  = _storage.CreateFileQueryWithOptions(queryOptions);
            IReadOnlyList <StorageFile> files        = await queryResult.GetFilesAsync();

            return(files);
        }
Пример #29
0
        private async static Task <IReadOnlyList <IStorageItem> > EnumerateFileQuery(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            // Get a StorageFolder for "path"
            string        fullPath = Path.GetFullPath(path);
            StorageFolder folder   = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true);

            // Construct a query for the search.
            QueryOptions query = new QueryOptions();

            // Translate SearchOption into FolderDepth
            query.FolderDepth = searchOption == SearchOption.AllDirectories ? FolderDepth.Deep : FolderDepth.Shallow;

            // Construct an AQS filter
            string normalizedSearchPattern = PathHelpers.NormalizeSearchPattern(searchPattern);

            if (normalizedSearchPattern.Length == 0)
            {
                // An empty searchPattern will return no results and requires no AQS parsing.
                return(new IStorageItem[0]);
            }
            else
            {
                // Parse the query as an ItemPathDisplay filter.
                string searchPath = PathHelpers.GetFullSearchString(fullPath, normalizedSearchPattern);
                string aqs        = "System.ItemPathDisplay:~\"" + searchPath + "\"";
                query.ApplicationSearchFilter = aqs;

                // If the filtered path is deeper than the given user path, we need to get a new folder for it.
                // This occurs when someone does something like Enumerate("C:\first\second\", "C:\first\second\third\*").
                // When AllDirectories is set this isn't an issue, but for TopDirectoryOnly we have to do some special work
                // to make sure something is actually returned when the searchPattern is a subdirectory of the path.
                // To do this, we attempt to get a new StorageFolder for the subdirectory and return an empty enumerable
                // if we can't.
                string searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern);
                string userPath             = string.IsNullOrEmpty(searchPatternDirName) ? fullPath : Path.Combine(fullPath, searchPatternDirName);
                if (userPath != folder.Path)
                {
                    folder = await StorageFolder.GetFolderFromPathAsync(userPath).TranslateWinRTTask(userPath, isDirectory: true);
                }
            }

            // Execute our built query
            if (searchTarget == SearchTarget.Files)
            {
                StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(query);
                return(await queryResult.GetFilesAsync().TranslateWinRTTask(folder.Path, isDirectory: true));
            }
            else if (searchTarget == SearchTarget.Directories)
            {
                StorageFolderQueryResult queryResult = folder.CreateFolderQueryWithOptions(query);
                return(await queryResult.GetFoldersAsync().TranslateWinRTTask(folder.Path, isDirectory: true));
            }
            else
            {
                StorageItemQueryResult queryResult = folder.CreateItemQueryWithOptions(query);
                return(await queryResult.GetItemsAsync().TranslateWinRTTask(folder.Path, isDirectory: true));
            }
        }
Пример #30
0
        /// <summary>
        /// Add folder to Library asynchronously.
        /// </summary>
        /// <param name="queryResult">The query result after querying in a specific folder.</param>
        /// <returns></returns>
        public static async Task <IEnumerable <Mediafile> > GetSongsFromFolderAsync(StorageFolder folder, bool useIndexer = true, uint stepSize = 20)
        {
            StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(DirectoryWalker.GetQueryOptions(null, useIndexer));

            uint index = 0;
            IReadOnlyList <StorageFile> files = await queryResult.GetFilesAsync(index, stepSize);

            index += stepSize;

            var count = await queryResult.GetItemCountAsync();

            if (count <= 0)
            {
                BLogger.I("No songs found.");
                await SharedLogic.Instance.NotificationManager.ShowMessageAsync("No songs found! Please try again.");

                return(null);
            }
            var   tempList = new List <Mediafile>((int)count);
            short progress = 0;

            try
            {
                // Note that I'm paging in the files as described
                while (files.Count != 0)
                {
                    var fileTask = queryResult.GetFilesAsync(index, stepSize).AsTask();
                    for (int i = 0; i < files.Count; i++)
                    {
                        if (files[i]?.IsAvailable == true)
                        {
                            progress++;
                            Messenger.Instance.NotifyColleagues(MessageTypes.MsgUpdateSongCount, progress);
                            Mediafile mp3File = await TagReaderHelper.CreateMediafile(files[i], false).ConfigureAwait(false); //the core of the whole method.

                            if (mp3File != null)
                            {
                                mp3File.FolderPath = Path.GetDirectoryName(files[i].Path);
                                await SaveSingleFileAlbumArtAsync(mp3File, files[i]).ConfigureAwait(false);

                                SharedLogic.Instance.NotificationManager.ShowStaticMessage(progress + "\\" + count + " Song(s) Loaded");
                                tempList.Add(mp3File);
                            }
                        }
                    }
                    files  = await fileTask;
                    index += stepSize;
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message + "||" + ex.InnerException;
                BLogger.E("Error while importing folder.", ex);
                await SharedLogic.Instance.NotificationManager.ShowMessageAsync(message);
            }
            return(tempList.DistinctBy(f => f.OrginalFilename));
        }