Inheritance: IQueryOptions
Ejemplo n.º 1
0
        private async void GetAllVideos(StorageFolder KnownFolders, QueryOptions QueryOptions)
        {
            StorageFileQueryResult query = KnownFolders.CreateFileQueryWithOptions(QueryOptions);
            IReadOnlyList<StorageFile> folderList = await query.GetFilesAsync();

            // Get all the videos in the folder past in parameter
            int id = 0;
            foreach (StorageFile file in folderList)
            {
                using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.VideosView, 200, ThumbnailOptions.UseCurrentScale))
                {
                    // Get video's properties
                    VideoProperties videoProperties = await file.Properties.GetVideoPropertiesAsync();

                    BitmapImage VideoCover = new BitmapImage();
                    VideoCover.SetSource(thumbnail);

                    Video video = new Video();
                    video.Id = id;
                    video.Name = file.Name;
                    video.DateCreated = file.DateCreated.UtcDateTime;
                    video.FileType = file.FileType;
                    video.VideoPath = file.Path;
                    video.Duration = videoProperties.Duration;
                    video.VideoFile = file;
                    video.VideoCover = VideoCover;

                    // Add the video to the ObservableCollection
                    Videos.Add(video);
                    id++;
                }
            }
        }
Ejemplo n.º 2
0
        sealed protected override async Task DoCleanup(Regex pattern, DateTime threshold)
        {

            var toDelete = new List<StorageFile>();
            foreach (var file in await _logFolder.GetFilesAsync())
            {
                if (pattern.Match(file.Name).Success && file.DateCreated <= threshold)
                    toDelete.Add(file);
            }


            var qo = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".zip" })
            {
                FolderDepth = FolderDepth.Shallow,
                UserSearchFilter = "System.FileName:~<\"Log -\""
            };

            var query = ApplicationData.Current.TemporaryFolder.CreateFileQueryWithOptions(qo);

            var oldLogs = await query.GetFilesAsync();
            toDelete.AddRange(oldLogs);

            // walk...
            foreach (var file in toDelete)
            {
                try
                {
                    await file.DeleteAsync();
                }
                catch (Exception ex)
                {
                    InternalLogger.Current.Warn(string.Format("Failed to delete '{0}'.", file.Path), ex);
                }
            }
        }
Ejemplo n.º 3
0
        public async void DeleteExpiredPictures(string camera)
        {
            //Delete older images
            try
            {
                var querySubfolders = new QueryOptions();
                querySubfolders.FolderDepth = FolderDepth.Deep;

                var cacheFolder = KnownFolders.PicturesLibrary;
                cacheFolder = await cacheFolder.GetFolderAsync(AppSettings.FolderName);
                var result = cacheFolder.CreateFileQueryWithOptions(querySubfolders);
                var files = await result.GetFilesAsync();

                foreach (StorageFile file in files)
                {
                    //Caluclate oldest time in ticks using the user selected storage duration 
                    long oldestTime = DateTime.UtcNow.Ticks - TimeSpan.FromDays(App.Controller.XmlSettings.StorageDuration).Ticks;
                    long picCreated = file.DateCreated.Ticks;
                    if (picCreated < oldestTime)
                    {
                        await file.DeleteAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception in deleteExpiredPictures() " + ex.Message);

                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "LocalStorage", ex.Message } };
                App.Controller.TelemetryClient.TrackEvent("FailedToDeletePicture", events);
            }
        }
        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";
            }
        }
		public virtual Assembly[] GetAssemblies()
		{
			var options = new QueryOptions { FileTypeFilter = { ".exe", ".dll" } };

			StorageFileQueryResult query = Package.Current.InstalledLocation.CreateFileQueryWithOptions(options);
			IReadOnlyList<StorageFile> files = query.GetFilesAsync().AsTask().Result;

			var assemblies = new List<Assembly>(files.Count);
			for (var i = 0; i < files.Count; i++)
			{
				StorageFile file = files[i];
				try
				{
					Assembly assembly = Assembly.Load(new AssemblyName { Name = Path.GetFileNameWithoutExtension(file.Name) });

					assemblies.Add(assembly);
				}
				catch (IOException)
				{
				}
				catch (BadImageFormatException)
				{
				}
			}

			Assembly thisAssembly = GetType().GetTypeInfo().Assembly;
			// this happens with .NET Native
			if (!assemblies.Contains(thisAssembly))
				assemblies.Add(thisAssembly);

			return assemblies.ToArray();
		}
Ejemplo n.º 6
0
        private async Task <List <StorageFile> > CreateFileListAsync()
        {
            List <StorageFile> files = new List <StorageFile>();

            if (string.IsNullOrWhiteSpace(_state.CurrentPackage.Name))
            {
                return(files);
            }

            StorageFolder pictureFolder = await KnownFolders.PicturesLibrary.CreateFolderAsync("SmartInk", CreationCollisionOption.OpenIfExists);

            var projectFolder = await pictureFolder.CreateFolderAsync(_state.CurrentPackage.Name, CreationCollisionOption.OpenIfExists);

            //await SetupWatcher(projectFolder);
            List <string> fileTypeFilter = new List <string>();

            fileTypeFilter.Add(".jpg");
            fileTypeFilter.Add(".jpeg");
            fileTypeFilter.Add(".png");
            var options = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.OrderByName, fileTypeFilter);


            var folders = await projectFolder.GetFoldersAsync();

            TotalImageCount = 0;
            foreach (var folder in folders)
            {
                var images = await folder.GetFilesAsync();

                TotalImageCount += images.Count;
                files.AddRange(images);
            }

            return(files);
        }
        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";
            }
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        public async static Task<bool> Validate(IXamlFilesData filesData)
        {
            var sha1 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
            var sha1Hash = sha1.CreateHash();

            var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".xaml" }) {FolderDepth = FolderDepth.Deep};
            var query = Package.Current.InstalledLocation.CreateFileQueryWithOptions(queryOptions);
            var files = await query.GetFilesAsync();

            foreach (var file in files)
            {
                string hash;
                if (filesData.FilesToVerify.TryGetValue(file.Name, out hash))
                {
                    var xaml = (await FileIO.ReadTextAsync(file)).Trim();
                    var buff = CryptographicBuffer.ConvertStringToBinary(xaml, BinaryStringEncoding.Utf16BE);
                    sha1Hash.Append(buff);
                    var newHash = CryptographicBuffer.EncodeToBase64String(sha1Hash.GetValueAndReset());

                    if (newHash != hash)
                        return false;
                }
            }

            return true;
        }
Ejemplo n.º 10
0
    public StartupPage()
    {
      InitializeComponent();

//#if WINDOWS_APP
      var temp = new QueryOptions();
//#endif

    }
        private async void GetFilesButton_Click(object sender, RoutedEventArgs e)
        {
            // Reset output.
            OutputPanel.Children.Clear();

            // Set up file type filter.
            List<string> fileTypeFilter = new List<string>();
            fileTypeFilter.Add(".jpg");
            fileTypeFilter.Add(".png");
            fileTypeFilter.Add(".bmp");
            fileTypeFilter.Add(".gif");

            // Create query options.
            var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);

            // Set up property prefetch - use the PropertyPrefetchOptions for top-level properties
            // and a list for additional properties.
            List<string> propertyNames = new List<string>();
            propertyNames.Add(CopyrightProperty);
            propertyNames.Add(ColorSpaceProperty);
            queryOptions.SetPropertyPrefetch(PropertyPrefetchOptions.ImageProperties, propertyNames);

            // Set up thumbnail prefetch if needed, e.g. when creating a picture gallery view.
            /*
            const uint requestedSize = 190;
            const ThumbnailMode thumbnailMode = ThumbnailMode.PicturesView;
            const ThumbnailOptions thumbnailOptions = ThumbnailOptions.UseCurrentScale;
            queryOptions.SetThumbnailPrefetch(thumbnailMode, requestedSize, thumbnailOptions);
            */

            // Set up the query and retrieve files.
            StorageFolder picturesFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.PicturesLibrary);
            var query = picturesFolder.CreateFileQueryWithOptions(queryOptions);
            IReadOnlyList<StorageFile> fileList = await query.GetFilesAsync();
            foreach (StorageFile file in fileList)
            {
                OutputPanel.Children.Add(CreateHeaderTextBlock(file.Name));

                // GetImagePropertiesAsync will return synchronously when prefetching has been able to
                // retrieve the properties in advance.
                var properties = await file.Properties.GetImagePropertiesAsync();
                OutputPanel.Children.Add(CreateLineItemTextBlock("Dimensions: " + properties.Width + "x" + properties.Height));

                // Similarly, extra properties are retrieved asynchronously but may
                // return immediately when prefetching has fulfilled its task.
                IDictionary<string, object> extraProperties = await file.Properties.RetrievePropertiesAsync(propertyNames);
                var propValue = extraProperties[CopyrightProperty];
                OutputPanel.Children.Add(CreateLineItemTextBlock("Copyright: " + GetPropertyDisplayValue(propValue)));
                propValue = extraProperties[ColorSpaceProperty];
                OutputPanel.Children.Add(CreateLineItemTextBlock("Color space: " + GetPropertyDisplayValue(propValue)));

                // Thumbnails can also be retrieved and used.
                // var thumbnail = await file.GetThumbnailAsync(thumbnailMode, requestedSize, thumbnailOptions);
            }
        }
Ejemplo n.º 12
0
        private void fileInitialisation()
        {
            var pictureQueryOptions = new QueryOptions();
            // Don't read through all the subfolders.
            pictureQueryOptions.FolderDepth = FolderDepth.Shallow;

            // Apply the query on the PicturesLibrary
            var pictureQuery = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(pictureQueryOptions);
            // Get picture information
            var picturesInformation = new FileInformationFactory(pictureQuery, ThumbnailMode.PicturesView);
            picturesSource.Source = picturesInformation.GetVirtualizedFilesVector();
        }
Ejemplo n.º 13
0
        public async void UploadPictures(string camera)
        {
            if (isLoggedIn)
            {
                uploadPicturesMutexLock.WaitOne();

                try
                {
                    QueryOptions querySubfolders = new QueryOptions();
                    querySubfolders.FolderDepth = FolderDepth.Deep;

                    StorageFolder cacheFolder = KnownFolders.PicturesLibrary;
                    cacheFolder = await cacheFolder.GetFolderAsync(AppSettings.FolderName);
                    var result = cacheFolder.CreateFileQueryWithOptions(querySubfolders);
                    var files = await result.GetFilesAsync();

                    foreach (StorageFile file in files)
                    {
                        string imageName = string.Format(AppSettings.ImageNameFormat, camera, DateTime.Now.ToString("MM_dd_yyyy/HH"), DateTime.UtcNow.Ticks.ToString());
                        try
                        {
                            await uploadPictureToOneDrive(AppSettings.FolderName, imageName, file);
                            numberUploaded++;

                            // uploadPictureToOnedrive should throw an exception if it fails, so it's safe to delete
                            await file.DeleteAsync();
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("UploadPictures(): " + ex.Message);

                            // Log telemetry event about this exception
                            var events = new Dictionary<string, string> { { "OneDrive", ex.Message } };
                            App.Controller.TelemetryClient.TrackEvent("FailedToUploadPicture", events);
                        }
                        this.lastUploadTime = DateTime.Now;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception in UploadPictures() " + ex.Message);

                    // Log telemetry event about this exception
                    var events = new Dictionary<string, string> { { "OneDrive", ex.Message } };
                    App.Controller.TelemetryClient.TrackEvent("FailedToUploadPicture", events);
                }
                finally
                {
                    uploadPicturesMutexLock.ReleaseMutex();
                }
            }
        }
Ejemplo n.º 14
0
        public async void UploadPictures()
        {
            if (oneDriveConnector.isLoggedIn)
            {
                // Stop timer to allow time for uploading pictures in case next timer tick overlaps with this ongoing one
                AppController.uploadPicturesTimer.Stop();

                try
                {
                    QueryOptions querySubfolders = new QueryOptions();
                    querySubfolders.FolderDepth = FolderDepth.Deep;

                    StorageFolder cacheFolder = KnownFolders.PicturesLibrary;
                    cacheFolder = await cacheFolder.GetFolderAsync(AppSettings.FolderName);
                    var result = cacheFolder.CreateFileQueryWithOptions(querySubfolders);
                    var files = await result.GetFilesAsync();

                    foreach (StorageFile file in files)
                    {
                        try
                        {
                            await oneDriveConnector.UploadFileAsync(file, String.Format("{0}/{1}", App.Controller.XmlSettings.OneDriveFolderPath, DateTime.Now.ToString("yyyy_MM_dd")));
                            numberUploaded++;

                            // uploadPictureToOnedrive should throw an exception if it fails, so it's safe to delete
                            await file.DeleteAsync();
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("UploadPictures(): " + ex.Message);

                            // Log telemetry event about this exception
                            var events = new Dictionary<string, string> { { "OneDrive", ex.Message } };
                            TelemetryHelper.TrackEvent("FailedToUploadPicture", events);
                        }
                        this.lastUploadTime = DateTime.Now;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception in UploadPictures() " + ex.Message);

                    // Log telemetry event about this exception
                    var events = new Dictionary<string, string> { { "OneDrive", ex.Message } };
                    TelemetryHelper.TrackEvent("FailedToUploadPicture", events);
                }
                finally
                {
                    AppController.uploadPicturesTimer.Start();
                }
            }
        }
Ejemplo n.º 15
0
        public async void UploadPictures()
        {
            if (oneDriveConnector.isLoggedIn)
            {
                // Stop timer to allow time for uploading pictures in case next timer tick overlaps with this ongoing one
                AppController.uploadPicturesTimer.Stop();

                try
                {
                    QueryOptions querySubfolders = new QueryOptions();
                    querySubfolders.FolderDepth = FolderDepth.Deep;

                    StorageFolder cacheFolder = KnownFolders.PicturesLibrary;
                    cacheFolder = await cacheFolder.GetFolderAsync(AppSettings.FolderName);
                    var result = cacheFolder.CreateFileQueryWithOptions(querySubfolders);
                    var files = await result.GetFilesAsync(0, MaxPictureUpload);

                    foreach (StorageFile file in files)
                    {
                        try
                        {
                            await uploadWithRetry(file);
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("UploadPictures(): " + ex.Message);

                            // Log telemetry event about this exception
                            var events = new Dictionary<string, string> { { "OneDrive", ex.Message } };
                            events.Add("File Failure", "File name: " + file.Name);
                            TelemetryHelper.TrackEvent("FailedToUploadPicture", events);
                            TelemetryHelper.TrackException(ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception in UploadPictures() " + ex.Message);

                    // Log telemetry event about this exception
                    var events = new Dictionary<string, string> { { "OneDrive", ex.Message } };
                    events.Add("Setup routine failure", "Exception thrown getting file list from pictures library");
                    TelemetryHelper.TrackEvent("FailedToUploadPicture", events);
                    TelemetryHelper.TrackException(ex);
                }
                finally
                {
                    AppController.uploadPicturesTimer.Start();
                }
            }
        }
Ejemplo n.º 16
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var queryOptions = new QueryOptions();
            queryOptions.FolderDepth = FolderDepth.Deep;
            queryOptions.IndexerOption = IndexerOption.UseIndexerWhenAvailable;
            queryOptions.SortOrder.Clear();
            var sortEntry = new SortEntry();
            sortEntry.PropertyName = "System.FileName";
            sortEntry.AscendingOrder = true;
            queryOptions.SortOrder.Add(sortEntry);

            var fileQuery = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
            const uint size = 190; // default size for PicturesView mode
            var fileInformationFactory = new FileInformationFactory(fileQuery, ThumbnailMode.PicturesView, size, ThumbnailOptions.UseCurrentScale, true);
            itemsViewSource.Source = fileInformationFactory.GetVirtualizedFilesVector();
        }
Ejemplo n.º 17
0
        private void VideoPanel_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // Acces to Videos libray
            StorageFolder VideosLibrary = KnownFolders.VideosLibrary;

            // Set up file type filter.
            List<string> fileTypeFilter = new List<string>();
            fileTypeFilter.Add(".avi");
            fileTypeFilter.Add(".mkv");
            fileTypeFilter.Add(".m4v");

            // Get the options for selecting
            QueryOptions QueryOption = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);

            // Get folders and Pictures
            GetFoldersAndVideos(VideosLibrary, QueryOption);
        }
Ejemplo n.º 18
0
        public static async void GetVideoList()
        {
            // Create file query for change detection
            var options = new Windows.Storage.Search.QueryOptions
            {
                FolderDepth = Windows.Storage.Search.FolderDepth.Deep
            };

            // Add change detection event listener
            queryResult = videoLibrary.CreateFileQueryWithOptions(options);
            queryResult.ContentsChanged += QueryContentsChanged;

            // Read videos
            storedVideo = await queryResult.GetFilesAsync();

            // // get tumbnails
            UpdateThumbs();
        }
        /// <summary>
        /// helper for all list by functions
        /// </summary>
        async Task GroupByHelperAsync(QueryOptions queryOptions)
        {
            OutputPanel.Children.Clear();

            StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
            StorageFolderQueryResult queryResult = picturesFolder.CreateFolderQueryWithOptions(queryOptions);

            IReadOnlyList<StorageFolder> folderList = await queryResult.GetFoldersAsync();
            foreach (StorageFolder folder in folderList)
            {
                IReadOnlyList<StorageFile> fileList = await folder.GetFilesAsync();
                OutputPanel.Children.Add(CreateHeaderTextBlock(folder.Name + " (" + fileList.Count + ")"));
                foreach (StorageFile file in fileList)
                {
                    OutputPanel.Children.Add(CreateLineItemTextBlock(file.Name));
                }
            }
        }
Ejemplo n.º 20
0
        public async void UploadPictures()
        {
            // Stop timer to allow time for uploading pictures in case next timer tick overlaps with this ongoing one
            AppController.uploadPicturesTimer.Stop();

            try
            {
                var querySubfolders = new QueryOptions();
                querySubfolders.FolderDepth = FolderDepth.Deep;

                var cacheFolder = KnownFolders.PicturesLibrary;
                cacheFolder = await cacheFolder.GetFolderAsync("securitysystem-cameradrop");
                var result = cacheFolder.CreateFileQueryWithOptions(querySubfolders);
                var count = await result.GetItemCountAsync();
                var files = await result.GetFilesAsync();

                foreach (StorageFile file in files)
                {
                    //Image name contains creation time
                    string imageName = string.Format(AppSettings.ImageNameFormat, DateTime.Now.ToString("yyyy_MM_dd/HH"), DateTime.UtcNow.Ticks.ToString());
                    if (file.IsAvailable)
                    {
                        //Upload image to blob storage
                        await uploadPictureToAzure(imageName, file);   
                        //Delete image from local storage after a successful upload                     
                        await file.DeleteAsync();
                    }
                }

                this.lastUploadTime = DateTime.Now;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception in uploadPictures() " + ex.Message);

                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "Azure", ex.Message } };
                TelemetryHelper.TrackEvent("FailedToUploadPicture", events);
            }
            finally
            {
                AppController.uploadPicturesTimer.Start();
            }
        }
Ejemplo n.º 21
0
        public async Task<IEnumerable<LibraryPhoto>> LoadFilesFromPictureLibraryAsync()
        {
            var queryOptions = new QueryOptions(CommonFileQuery.OrderByDate, new[] { ".jpg", ".gif", ".png" });
            var query = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);

            var files = await query.GetFilesAsync();

            var photos = new List<LibraryPhoto>();
            foreach (var file in files)
            {
                photos.Add(new LibraryPhoto
                {
                    Title = file.DisplayName,
                    DateCreated = file.DateCreated.LocalDateTime,
                    Path = file.Path,
                    Thumbnail = await GetThumbnail(file)
                });
            }
            return photos;
        }
Ejemplo n.º 22
0
        /*******************************************************************************************
        * PUBLIC METHODS
        *******************************************************************************************/
        public async void UploadPictures(string camera)
        {
            uploadPicturesMutexLock.WaitOne();

            try
            {
                var querySubfolders = new QueryOptions();
                querySubfolders.FolderDepth = FolderDepth.Deep;

                var cacheFolder = KnownFolders.PicturesLibrary;
                cacheFolder = await cacheFolder.GetFolderAsync("securitysystem-cameradrop");
                var result = cacheFolder.CreateFileQueryWithOptions(querySubfolders);
                var count = await result.GetItemCountAsync();
                var files = await result.GetFilesAsync();

                foreach (StorageFile file in files)
                {
                    //Image name contains creation time
                    string imageName = string.Format(AppSettings.ImageNameFormat, camera, DateTime.Now.ToString("MM_dd_yyyy/HH"), DateTime.UtcNow.Ticks.ToString());
                    if (file.IsAvailable)
                    {
                        //Upload image to blob storage
                        await uploadPictureToAzure(imageName, file);   
                        //Delete image from local storage after a successful upload                     
                        await file.DeleteAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception in uploadPictures() " + ex.Message);

                // Log telemetry event about this exception
                var events = new Dictionary<string, string> { { "Azure", ex.Message } };
                App.Controller.TelemetryClient.TrackEvent("FailedToUploadPicture", events);
            }
            finally
            {
                uploadPicturesMutexLock.ReleaseMutex();
            }
        }
        private async void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            StorageFolder musicFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.MusicLibrary);
            
            List<string> fileTypeFilter = new List<string>();
            fileTypeFilter.Add("*");

            QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, fileTypeFilter);
            //use the user's input to make a query
            queryOptions.UserSearchFilter = InputTextBox.Text;
            StorageFileQueryResult queryResult = musicFolder.CreateFileQueryWithOptions(queryOptions);

            StringBuilder outputText = new StringBuilder();

            //find all files that match the query
            IReadOnlyList<StorageFile> files = await queryResult.GetFilesAsync();
            //output how many files that match the query were found
            if (files.Count == 0)
            {
                outputText.Append("No files found for '" + queryOptions.UserSearchFilter + "'");
            }
            else if (files.Count == 1)
            {
                outputText.Append(files.Count + " file found:\n\n");
            }
            else
            {
                outputText.Append(files.Count + " files found:\n\n");
            }

            //output the name of each file that matches the query
            foreach (StorageFile file in files)
            {
                outputText.Append(file.Name + "\n");
            }

            OutputTextBlock.Text = outputText.ToString();
        }
Ejemplo n.º 24
0
        private async void LoadPhoto()
        {
            var queryOptions = new Windows.Storage.Search.QueryOptions(CommonFileQuery.OrderByDate, null);

            queryOptions.SetThumbnailPrefetch(ThumbnailMode.PicturesView, 100,
                                              ThumbnailOptions.ReturnOnlyIfCached);
            //queryOptions.SetPropertyPrefetch(PropertyPrefetchOptions.ImageProperties, new string[] { "System.Size" });
            queryOptions.SetThumbnailPrefetch(ThumbnailMode.ListView, 80, ThumbnailOptions.ReturnOnlyIfCached);

            StorageFileQueryResult      queryResults = KnownFolders.PicturesLibrary.CreateFileQueryWithOptions(queryOptions);
            IReadOnlyList <StorageFile> files        = await queryResults.GetFilesAsync();

            foreach (var file in files)
            {
                var thumbnail = await file.GetThumbnailAsync(ThumbnailMode.ListView, 40, ThumbnailOptions.ReturnOnlyIfCached);

                thumbnailList.Add(thumbnail);
                debugText.Text = thumbnailList.Count.ToString();
                //BitmapImage bm = new BitmapImage();
                //bm.SetSource(thumbnail);
                //photoList.Add(bm);

                //ImageProperties imageProperties = await file.Properties.GetImagePropertiesAsync();

                //// Do something with the date the image was taken.
                //DateTimeOffset dateTaken = imageProperties.DateTaken;

                //// Performance gains increase with the number of properties that are accessed.
                //IDictionary<String, object> propertyResults =
                //    await file.Properties.RetrievePropertiesAsync(
                //          new string[] { "System.Size" });

                //// Get/Set extra properties here
                //var systemSize = propertyResults["System.Size"];
            }
        }
Ejemplo n.º 25
0
        private async void GetFoldersAndVideos(StorageFolder VideosLibrary, QueryOptions QueryOption)
        {
            StartUpProgressRing.IsActive = true;

            // Clear all the ObservableCollection
            VideoFiles.Clear();
            VideoFolder.Clear();

            QueryOption.FolderDepth = FolderDepth.Shallow;

            // Get Folders and Videos
            Gf = new GetFolders(VideosLibrary);
            Gv = new GetVideos(VideosLibrary, QueryOption);
            await Task.Delay(500);

            ObservableCollection<Folder> Folders = Gf.Folders;
            ObservableCollection<Video> Videos = Gv.Videos;

            // Pluck off meta data from pictures and folders
            PopulateFoldersList(Folders);
            PopulateVideoList(Videos);

            StartUpProgressRing.IsActive = false;
        }
 public void ApplyNewQueryOptions(QueryOptions newQueryOptions) { }
Ejemplo n.º 27
0
        /// <summary>
        /// Finds and displays the first image file on the storage referenced by the device information element.
        /// </summary>
        /// <param name="deviceInfoElement">Contains information about a selected device.</param>
        async private Task GetFirstImageFromStorageAsync(DeviceInformation deviceInfoElement)
        {
            // Convert the selected device information element to a StorageFolder
            var storage = StorageDevice.FromId(deviceInfoElement.Id);
            var storageName = deviceInfoElement.Name;

            // Construct the query for image files
            var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, new List<string> { ".jpg", ".png", ".gif" });
            var imageFileQuery = storage.CreateFileQueryWithOptions(queryOptions);

            // Run the query for image files
            rootPage.NotifyUser("Looking for images on " + storageName + " ...", NotifyType.StatusMessage);
            var imageFiles = await imageFileQuery.GetFilesAsync();
            if (imageFiles.Count > 0)
            {
                var imageFile = imageFiles[0];
                rootPage.NotifyUser("Found " + imageFile.Name + " on " + storageName, NotifyType.StatusMessage);
                await DisplayImageAsync(imageFile);
            }
            else
            {
                rootPage.NotifyUser("No images were found on " + storageName + ". You can use scenario 2 to transfer an image to it", NotifyType.StatusMessage);
            }
        }
Ejemplo n.º 28
0
        public GetVideos(StorageFolder KnownFolders, QueryOptions QueryOptions)
        {
            Videos = new ObservableCollection<Video>();

            GetAllVideos(KnownFolders, QueryOptions);
        }
        /// <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;
            }
        }
        /// <summary>
        /// Finds and displays the first image file on the storage.
        /// </summary>
        /// <param name="storage"></param>
        async private Task GetFirstImageFromStorageAsync(StorageFolder storage)
        {
            var storageName = storage.Name;

            // Construct the query for image files
            var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, new List<string> { ".jpg", ".png", ".gif" });
            var imageFileQuery = storage.CreateFileQueryWithOptions(queryOptions);

            // Run the query for image files
            rootPage.NotifyUser("[Launched by Autoplay] Looking for images on " + storageName + " ...", NotifyType.StatusMessage);
            var imageFiles = await imageFileQuery.GetFilesAsync();
            if (imageFiles.Count > 0)
            {
                var imageFile = imageFiles[0];
                rootPage.NotifyUser("[Launched by Autoplay] Found " + imageFile.Name + " on " + storageName, NotifyType.StatusMessage);
                await DisplayImageAsync(imageFile);
            }
            else
            {
                rootPage.NotifyUser("[Launched by Autoplay] No images were found on " + storageName + ". You can use scenario 2 to transfer an image to it", NotifyType.StatusMessage);
            }
        }
Ejemplo n.º 31
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            var filter = new List<string> { ".pdf" };

            var storageFolders = _sourceService.GetAllAsStorageFoldersAsync().Result;

            foreach (var storageFolder in storageFolders)
            {
                var source = _sourceService.GetByUrl(storageFolder.Path);
                var options = new QueryOptions(CommonFileQuery.OrderByName, filter);
                var ss = storageFolder.CreateItemQueryWithOptions(options);

                //Get all PDF files for storagefolder
                var pdfFiles = ss.GetItemsAsync().GetAwaiter().GetResult();
                for (var i = 0; i < pdfFiles.Count; i++)
                {
                    var progress = Utils.CalculatePercentage(i, 0, pdfFiles.Count);
                    if (Worker.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    var book = new Book
                    {
                        Title = Path.GetFileNameWithoutExtension(pdfFiles[i].Name),
                        Source = source,
                        FileName = Path.GetFileName(pdfFiles[i].Path),
                        FullPathAndFileName = pdfFiles[i].Path,
                        Rating = 0
                    };

                    var book1 = book;
                    var existingBook = _bookService.Exists(book1);

                    if (existingBook == false) // Add Book
                    {
                        var xml = storageFolder.TryGetItemAsync(book.Title + ".xml").GetAwaiter().GetResult();
                        if (xml != null)
                        {
                            book = XmlToBook(xml as StorageFile, book);
                        }
                        else
                        {
                            book = UseIsbn(pdfFiles[i] as StorageFile, book);
                        }



                        var cover = new Cover();
                        var coverPath = _pdfCover.GenerateCoverImage(book, 0, _sourcerepo, storageFolder, pdfFiles[i] as StorageFile).Result;
                        cover.FileName = Path.GetFileName(coverPath);

                        
                        book.Cover = cover;
                        book = _bookService.Add(book);
                        Worker.ReportProgress(progress, book);
                    }
                    else
                    {
                        Tuple<Book, string> exists = new Tuple<Book, string>(book, "Exists");
                        Worker.ReportProgress(progress, exists);
                    }
                }
            }
        }
Ejemplo n.º 32
0
        async private void LoadMediaFiles()
        {
            try
            {
                StorageFolder mediaServerFolder = mediaServers[dmsSelect.SelectedIndex];

                var queryOptions = new QueryOptions();
                queryOptions.FolderDepth = FolderDepth.Deep;
                queryOptions.UserSearchFilter = "System.Kind:=video";

                if (mediaServerFolder.AreQueryOptionsSupported(queryOptions))
                {
                    var queryFolder = mediaServerFolder.CreateFileQueryWithOptions(queryOptions);
                    mediaFiles = await queryFolder.GetFilesAsync(0, 25);
                    mediaSelect.Items.Clear();
                    if (mediaFiles.Count == 0)
                    {
                        rootPage.NotifyUser("No Media Files found ", NotifyType.StatusMessage);
                    }
                    else
                    {
                        foreach (StorageFile file in mediaFiles)
                        {
                            mediaSelect.Items.Add(file.DisplayName);
                        }
                        rootPage.NotifyUser("Media files retrieved", NotifyType.StatusMessage);
                    }
                }
                else
                {
                    List<StorageFile> lstMediaItems = new List<StorageFile>();
                    var countOfVideoFilesFound = await BrowseForVideoFiles(mediaServerFolder, lstMediaItems, 25);
                    mediaFiles = lstMediaItems;

                    if (countOfVideoFilesFound > 0)
                    {
                        rootPage.NotifyUser("Media files retrieved", NotifyType.StatusMessage);
                    }
                    else
                    {
                        rootPage.NotifyUser("No Media Files found ", NotifyType.StatusMessage);
                    }
                }
            }
            catch (Exception e)
            {
                rootPage.NotifyUser("Error locating media files " + e.Message, NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 33
0
 private Task GroupByHelperAsync(QueryOptions queryOptions)
 {
     throw new NotImplementedException();
 }