Esempio n. 1
0
        private async Task<IReadOnlyList<IFile>> OpenFilesAsync( OpenFileInteraction openFile )
        {
            Contract.Requires( openFile != null );
            Contract.Ensures( Contract.Result<Task<IReadOnlyList<IFile>>>() != null );

            var saveButton = openFile.DefaultCommand;
            var dialog = new FileOpenPicker();

            dialog.FileTypeFilter.AddRange( openFile.FileTypeFilter.FixUpExtensions() );
            dialog.SuggestedStartLocation = SuggestedStartLocation;
            dialog.ViewMode = ViewMode;

            if ( !string.IsNullOrEmpty( SettingsIdentifier ) )
                dialog.SettingsIdentifier = SettingsIdentifier;

            if ( saveButton != null )
                dialog.CommitButtonText = saveButton.Name;

            if ( openFile.Multiselect )
                return ( await dialog.PickMultipleFilesAsync() ).Select( f => f.AsFile() ).ToArray();

            var file = await dialog.PickSingleFileAsync();

            if ( file != null )
                return new[] { file.AsFile() };

            return new IFile[0];
        }
 private async void OpenFile()
 {
     FileOpenPicker openPicker = new FileOpenPicker();
     openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
     openPicker.FileTypeFilter.Add(".uvu");
     var file = await openPicker.PickSingleFileAsync();
     if (file != null)
     {
         adaptivePlugin.DownloaderPlugin = new Microsoft.Media.AdaptiveStreaming.Dash.CffOfflineDownloaderPlugin(file);
         player.Source = new Uri(string.Format("ms-sstr://local/{0}", file.Name)); // create a dummy url, this can actually be anything.
     }
 }
Esempio n. 3
0
		public async Task<UploadViewModel> ShowChooser()
		{
			UploadViewModel uploadViewModel = null;
#if ANDROID
		    var uiContext = new Services.UiContext();            
            var mediaPicker = new Xamarin.Media.MediaPicker(uiContext.CurrentContext);
#elif IOS
            var mediaPicker = new Xamarin.Media.MediaPicker();
#endif
#if __MOBILE__
            try
            {
                var mediaFile = await mediaPicker.PickPhotoAsync().ConfigureAwait(false);

                if (mediaFile != null)
                {
                    uploadViewModel = new UploadViewModel();
                    uploadViewModel.PictureStream = mediaFile.GetStream();
                    uploadViewModel.ImageIdentifier = Guid.NewGuid() + Path.GetExtension(mediaFile.Path);
                }
            }
			catch (TaskCanceledException ex)
			{
				// Happens if they don't select an image and press the 
				// back button. Just continue as it is an expected
				// exception.
				Insights.Report(ex);
			}
#else
            var openPicker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary };
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            openPicker.FileTypeFilter.Add(".bmp");
            var file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                uploadViewModel = new UploadViewModel();
                uploadViewModel.PictureFile = file;
                uploadViewModel.PictureStream = await file.OpenReadAsync();
                uploadViewModel.ImageIdentifier = Guid.NewGuid() + file.FileType;
            }
#endif
			return uploadViewModel;
		}
Esempio n. 4
0
        private async void EditPhoto_Click(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker();

            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.FileTypeFilter.AddRange(Constants.PhotoTypes);

            var file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                var dialog       = new EditYourPhotoView(file);
                var dialogResult = await dialog.ShowAsync();

                if (dialogResult == ContentDialogBaseResult.OK)
                {
                    ViewModel.EditPhotoCommand.Execute(dialog.Result);
                }
            }
        }
        private async void PickPhotoBtn_Click(object sender, RoutedEventArgs e)
        {
            var fileDialog = new FileOpenPicker();

            fileDialog.FileTypeFilter.Add(".jpeg");
            fileDialog.FileTypeFilter.Add(".png");
            fileDialog.FileTypeFilter.Add(".jpg");
            fileDialog.ViewMode               = PickerViewMode.Thumbnail;
            fileDialog.CommitButtonText       = "Aceptar";
            fileDialog.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

            var pickerResult = await fileDialog.PickSingleFileAsync();

            if (pickerResult != null)
            {
                var copyResult = await pickerResult.CopyAsync(ApplicationData.Current.LocalFolder, pickerResult.Name, NameCollisionOption.ReplaceExisting);

                PhotoImg.Source = new BitmapImage(new Uri(copyResult.Path));
                photoRoute      = copyResult.Path;
            }
        }
Esempio n. 6
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker picker = new FileOpenPicker();

            picker.ViewMode = PickerViewMode.Thumbnail;

            picker.FileTypeFilter.Add(".mp4");
            picker.FileTypeFilter.Add(".mp3");
            StorageFile file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                mediaplayer.SetSource(stream, file.ContentType);
            }
            else
            {
                return;
            }
        }
Esempio n. 7
0
        private async void OpenBeatFile_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add(".txt");

            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                // Application now has read/write access to the picked file
                System.Diagnostics.Debug.WriteLine("Picked file: " + file.Name);
                this.Frame.Navigate(typeof(ShowFileData), file);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Operation cancelled.");
            }
        }
Esempio n. 8
0
        public async void UploadFile()
        {
            FileOpenPicker pick = new FileOpenPicker();

            pick.FileTypeFilter.Add(".jpg");
            StorageFile file = await pick.PickSingleFileAsync();

            QnUploadImage uploadImage = new QnUploadImage(file)
            {
                Accound = Accound
            };

            uploadImage.OnUploaded += (s, e) =>
            {
                if (e)
                {
                    Address = uploadImage.Url;
                }
            };
            uploadImage.UploadImage();
        }
Esempio n. 9
0
        private async void SubirVideoAsync(object sender, RoutedEventArgs e)
        {
            fileOpenPicker = GetFileOpenPicker(new List <string> {
                ".avi", ".mp4", ".wmv"
            }, PickerLocationId.VideosLibrary);
            this.pickedVideoFile = await fileOpenPicker.PickSingleFileAsync();

            this.pickedVideoFiles = new List <StorageFile> {
                pickedVideoFile
            };
            this.filePath = pickedVideoFiles[0].Path;

            try
            {
                await Task.Run(UploadTheFile);
            }
            catch (AggregateException ex)
            {
                Debug.Write("Error: " + ex.Message);
            }
        }
Esempio n. 10
0
        private async void UploadButton_Click(object sender, RoutedEventArgs e)
        {
            //error handling
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".png");

            StorageFile file = await picker.PickSingleFileAsync();

            //handle cancel from picker

            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
            {
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(fileStream);

                SelectedImage.Source = bitmapImage;
            }

            /*
             * //dangerous to specify it in production
             * var rekognitionServices =
             *  new RekognitionServices("AKIARHH6DIMRTNVRA2S2", "pnz3ym+xyPBEpA623bzkff+tJLpeAOxE8t9ZFRgG");
             *
             * try
             * {
             *  IsLoading.Visibility = Visibility.Visible;
             *  ResultTb.Text = await rekognitionServices.RegisterUser(file.Path, file.Name);
             * }
             * finally
             * {
             *  IsLoading.Visibility = Visibility.Collapsed;
             * }*/
        }
        /// <summary>
        /// Open video picker to select file and copy to local storage
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnChooseVideo_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
        {
            try
            {
                // show Open dialog
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
                openPicker.FileTypeFilter.Add(".mp4");
                openPicker.FileTypeFilter.Add(".webm");
                openPicker.FileTypeFilter.Add(".mpeg");
                openPicker.FileTypeFilter.Add(".3gp");
                openPicker.FileTypeFilter.Add(".mkv");

                StorageFile file = await openPicker.PickSingleFileAsync();

                if (file != null)
                {
                    // Copy file to local settings
                    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                    loadingPanel.Visibility = Visibility.Visible;
                    await file.CopyAsync(localFolder, file.Name, NameCollisionOption.ReplaceExisting);

                    loadingPanel.Visibility = Visibility.Collapsed;
                    progressRing.IsActive   = false;

                    // Update video name on setting
                    txtVideoUri.Text = file.Name;
                    localSettings.Values["video_uri"] = file.Name;
                }
                else
                {
                    txtVideoUri.Text = "Select any Video file!";
                }
            }
            catch (Exception ex)
            {
                MainController.ShowMessageBox("Error!", ex.Message);
            }
        }
Esempio n. 12
0
        private async void OpenButton_Click(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker();

            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeFilter.Add(".xml");
            picker.FileTypeFilter.Add(".zip");

            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                return;
            }

            var mru = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList;

            _ = mru.Add(file, file.Name);

            var stream = await file.OpenStreamForReadAsync();

            switch (Path.GetExtension(file.Name))
            {
            case ".xml":
                // Read the file
                var docXml = CopticInterpreter.ReadDocXml(stream);
                Docs.Add(docXml);
                MainTabControl.SelectedIndex = Docs.Count - 1;
                return;

            case ".zip":
                // Read the set
                var set = CopticInterpreter.ReadSet(stream, file.Name, Windows.Storage.ApplicationData.Current.TemporaryFolder.Path);
                Docs.Clear();
                set.IncludedDocs.ForEach(d => Docs.Add(d));
                MainTabControl.SelectedIndex = 0;
                CurrentStanza = (set.IncludedDocs[0].Translations[0].Content[0] as Stanza)?.Text;
                return;
            }
        }
Esempio n. 13
0
        async private void openFile_Click(object sender, RoutedEventArgs e)
        {
            var openPicker = new FileOpenPicker();

            openPicker.FileTypeFilter.Add(".wmv");
            openPicker.FileTypeFilter.Add(".mp4");
            openPicker.FileTypeFilter.Add(".wma");
            openPicker.FileTypeFilter.Add(".mp3");

            var file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                var stream = await file.OpenAsync(FileAccessMode.Read);

                mediaPlayer.SetSource(stream, file.ContentType);
                ellstoryBoard.Stop();

                if (file.FileType == ".mp3")
                {
                    picture.Visibility     = Visibility.Visible;
                    mediaPlayer.Visibility = Visibility.Collapsed;

                    /*var thumbnail = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 500, ThumbnailOptions.UseCurrentScale);
                     * BitmapImage bitmapImage = new BitmapImage();
                     * InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                     * await RandomAccessStream.CopyAsync(thumbnail, randomAccessStream);
                     * randomAccessStream.Seek(0);
                     * bitmapImage.SetSource(randomAccessStream);
                     * image.ImageSource = bitmapImage;*/
                }
                else
                {
                    picture.Visibility     = Visibility.Collapsed;
                    mediaPlayer.Visibility = Visibility.Visible;
                }

                //mediaPlayer.Play();
            }
        }
Esempio n. 14
0
        private async void selectPhotoButton_Click(object sender, RoutedEventArgs e)
        {
            var filePicker = new FileOpenPicker();

            filePicker.FileTypeFilter.Add(".jpg");
            filePicker.FileTypeFilter.Add(".jpeg");
            filePicker.FileTypeFilter.Add(".png");

            var file = await filePicker.PickSingleFileAsync();

            if (file != null)
            {
                _selectedImageFile            = file;
                SelectedPhotoPathTextBox.Text = file.Path;
                using (var stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    _currentImage = new BitmapImage();
                    await _currentImage.SetSourceAsync(stream);
                }
                if (_currentImage.PixelHeight > 4096 || _currentImage.PixelWidth > 4096)
                {
                    var dialog = new MessageDialog("Image size is too large! Must be smaller than 4096 x 4096");
                    await dialog.ShowAsync();

                    AnalyzeButton.IsEnabled = false;
                }
                else
                {
                    if (Pivot.SelectedItem == AnalysisItem)
                    {
                        AnalysisImage.Source = _currentImage;
                    }
                    if (Pivot.SelectedItem == OcrItem)
                    {
                        OcrImage.Source = _currentImage;
                    }
                    AnalyzeButton.IsEnabled = true;
                }
            }
        }
Esempio n. 15
0
        /*
         * ----< Function > FileSelector
         * ----< Description >
         * Open a file, depending on type passed in the file selector will be filtered.
         * ----< Description >
         * @Param Extension extension -- The extension type for the file we are looking for
         * @Return None
         */
        private async void FileSelector(Extension extension)
        {
            FileOpenPicker openPicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.List,
                SuggestedStartLocation = PickerLocationId.Desktop
            };

            if (extension == Extension.DLL)
            {
                openPicker.FileTypeFilter.Add(".dll");
                IReadOnlyList <StorageFile> files = await openPicker.PickMultipleFilesAsync();

                if (files.Count > 0)
                {
                    StringBuilder output = new StringBuilder("Selected DLLs: \n");

                    foreach (StorageFile file in files)
                    {
                        output.Append(file.DisplayName + "\n");
                        fileList.Add(file);
                    }
                }
                else
                {
                }
            }
            else if (extension == Extension.JSON)
            {
                openPicker.FileTypeFilter.Add(".json");
                StorageFile storageFile = await openPicker.PickSingleFileAsync();

                if (storageFile != null)
                {
                    Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(storageFile);
                    logger.AddOpenFileMessage(storageFile.DisplayName + ".json", storageFile.Path);
                    AddDLLsToGUI(storageFile);
                }
            }
        }
        public async Task <ImageFile> ImportTemporaryImageFileAsync(IEnumerable <string> fileTypes)
        {
            var picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            foreach (var fileType in fileTypes)
            {
                picker.FileTypeFilter.Add(fileType);
            }

            var file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                return(null);
            }

            var backgroundThemeTmpFolder =
                await ApplicationData.Current.LocalCacheFolder.CreateFolderAsync("BackgroundThemeTmp",
                                                                                 CreationCollisionOption.OpenIfExists);

            if (backgroundThemeTmpFolder == null)
            {
                return(null);
            }

            var item = await backgroundThemeTmpFolder.TryGetItemAsync(file.Name);

            if (item == null)
            {
                var storageFile = await file.CopyAsync(backgroundThemeTmpFolder, file.Name);

                return(new ImageFile(storageFile.DisplayName, storageFile.FileType,
                                     $@"{backgroundThemeTmpFolder.Path}\{storageFile.Name}"));
            }

            return(new ImageFile(file.DisplayName, file.FileType, $@"{backgroundThemeTmpFolder.Path}\{item.Name}"));
        }
Esempio n. 17
0
        /// <summary>
        ///     Handles the ClickAsync event of the loadFile control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param>
        private async void loadFile_ClickAsync(object sender, RoutedEventArgs e)
        {
            var filePicker = new FileOpenPicker {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };

            filePicker.FileTypeFilter.Add(".csv");
            filePicker.FileTypeFilter.Add(".txt");

            var chosenFile = await filePicker.PickSingleFileAsync();

            if (chosenFile == null)
            {
                this.summaryTextBox.Text = "No file was chosen.";
            }
            else
            {
                var fileParser = new WeatherFileParser();

                int.TryParse(this.lowerBoundTextBox.Text, out this.lowerBound);
                int.TryParse(this.upperBoundTextBox.Text, out this.upperBound);
                var reportBuilder = new WeatherReportBuilder(this.lowerBound, this.upperBound);

                var newWeatherCollection = await fileParser.ParseTemperatureFileAsync(chosenFile);

                if (this.currentWeatherCollection == null)
                {
                    this.currentWeatherCollection = newWeatherCollection;
                }
                else
                {
                    await this.handleNewFileWithExistingFile(newWeatherCollection);
                }

                this.errors = fileParser.ErrorMessages;
                var report = reportBuilder.CreateReport(this.currentWeatherCollection, this.getBucketSize());
                this.summaryTextBox.Text = report + this.errors;
            }
        }
Esempio n. 18
0
        private async void Button_OnClick(object sender, RoutedEventArgs e)
        {
            var rejairJate = new HttpClient();
            var sairlallilarRaibedoYertousebow = "http://localhost:62435/api/XaseYinairtraiSeawhallkous/";

            var casnisHoubou         = new MultipartFormDataContent();
            var taykiHerniCeawerenel = new StringContent("文件名");

            casnisHoubou.Add(taykiHerniCeawerenel, "Name");
            var henocoRowrarlarVegonirnis = await GetFile();

            var tobemmanuCamuCaivi = new StreamContent(henocoRowrarlarVegonirnis);

            casnisHoubou.Add(tobemmanuCamuCaivi, "File", "BardelCairdallChodiMestebarnai");

            try
            {
                var tizicheLouru =
                    await rejairJate.PostAsync(sairlallilarRaibedoYertousebow + "UploadFile", casnisHoubou);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
            }

            async Task <Stream> GetFile()
            {
                var lisNailallkear = new FileOpenPicker()
                {
                    FileTypeFilter =
                    {
                        ".png"
                    }
                };

                var whejowNoukiru = await lisNailallkear.PickSingleFileAsync();

                return(await whejowNoukiru.OpenStreamForReadAsync());
            }
        }
Esempio n. 19
0
        private async void OpenLocalFile(object sender, RoutedEventArgs e)
        {
            FileOpenPicker filePicker = new FileOpenPicker();

            filePicker.ViewMode = PickerViewMode.Thumbnail;
            filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
            filePicker.FileTypeFilter.Add("*");

            // Show file picker so user can select a file
            StorageFile file = await filePicker.PickSingleFileAsync();

            if (file != null)
            {
                currentFile = file;
                mediaElement.Stop();

                // Open StorageFile as IRandomAccessStream to be passed to FFmpegInteropMSS
                IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);

                try
                {
                    // Instantiate FFmpegInteropMSS using the opened local file stream

                    FFmpegMSS = await FFmpegInteropMSS.CreateFromStreamAsync(readStream, Config);

                    if (AutoCreatePlaybackItem)
                    {
                        CreatePlaybackItemAndStartPlaybackInternal();
                    }
                    else
                    {
                        playbackItem = null;
                    }
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex.Message);
                }
            }
        }
Esempio n. 20
0
        private async void Click50n(object sender, RoutedEventArgs e)
        {
            if (Image50n == null)
            {
                FileOpenPicker pickerWallpaper = new FileOpenPicker();
                pickerWallpaper.ViewMode = PickerViewMode.Thumbnail;
                pickerWallpaper.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                pickerWallpaper.FileTypeFilter.Add(".jpeg");
                pickerWallpaper.FileTypeFilter.Add(".jpg");
                pickerWallpaper.FileTypeFilter.Add(".png");
                pickerWallpaper.FileTypeFilter.Add(".bmp");
                pickerWallpaper.FileTypeFilter.Add(".jfif");
                pickerWallpaper.FileTypeFilter.Add(".dib");
                pickerWallpaper.FileTypeFilter.Add(".jpe");
                pickerWallpaper.FileTypeFilter.Add(".gif");
                pickerWallpaper.FileTypeFilter.Add(".tif");
                pickerWallpaper.FileTypeFilter.Add(".tiff");
                pickerWallpaper.FileTypeFilter.Add(".wdp");
                StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                await localFolder.CreateFolderAsync("9mabt17s", CreationCollisionOption.OpenIfExists);

                StorageFolder temp = await localFolder.GetFolderAsync("9mabt17s");

                StorageFile fileName = await pickerWallpaper.PickSingleFileAsync();

                if (fileName != null)
                {
                    Image50n = await fileName.CopyAsync(temp, "50n" + fileName.FileType);

                    Button18.Content = fileName.Name;
                }
            }
            else
            {
                await Image50n.DeleteAsync();

                Image50n         = null;
                Button18.Content = "Night";
            }
        }
Esempio n. 21
0
    private async void btnClick_Click(object sender, RoutedEventArgs e)
    {
        FileOpenPicker picker = new FileOpenPicker();

        picker.ViewMode = PickerViewMode.Thumbnail;
        picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
        picker.FileTypeFilter.Add(".txt");
        StorageFile file = await picker.PickSingleFileAsync();

        if (file != null)
        {
            var stream = await file.OpenAsync(FileAccessMode.Read);

            using (StreamReader reader = new StreamReader(stream.AsStream()))
            {
                items = new List <Item>();
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (line.StartsWith("---"))
                    {
                        //listbox.Items.Add(line);
                        //Instead of adding a line, add an item instance
                        items.Add(new Item
                        {
                            Name = line
                        });
                    }
                    else if (line != string.Empty) //if it is not the empty line then add it to the last item's url
                    {
                        if (items.LastOrDefault() != null)
                        {
                            items.LastOrDefault().URL = line;
                        }
                    }
                }
                listbox.ItemsSource = items;
            }
        }
    }
Esempio n. 22
0
        //打开媒体文件
        private async void openMedia_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker mediaPicker = new FileOpenPicker();

            mediaPicker.FileTypeFilter.Add(".mp3");

            mediaPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;

            var file = await mediaPicker.PickSingleFileAsync();

            if (file != null)
            {
                //设置媒体播放源
                IRandomAccessStream ir = await file.OpenAsync(FileAccessMode.Read);

                MediaSource mediaSource = MediaSource.CreateFromStorageFile(file);
                MainPage.Current.setMediaSource(ir, " ");

                string type = file.FileType;
                string userBGM;

                //保存音乐文件名
                userBGM = file.Name;
                try
                {
                    //由该音乐创建拥有相同名字的新文件,存放在LocalFolder
                    await file.CopyAsync(ApplicationData.Current.LocalFolder, userBGM);
                }
                catch (Exception ee)
                {
                    //已经有同名文件存在,则替换
                    await file.CopyAndReplaceAsync(await ApplicationData.Current.LocalFolder.GetFileAsync(userBGM));
                }

                ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
                localSettings.Values["BGM"] = userBGM;

                bgmName.Text = "当前BGM:" + userBGM;
            }
        }
Esempio n. 23
0
        private async void OpenAndLoadAsync()
        {
            var openPicker = new FileOpenPicker();

            openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.VideosLibrary;
            openPicker.FileTypeFilter.Add(".wmv");
            openPicker.FileTypeFilter.Add(".mp4");
            openPicker.FileTypeFilter.Add(".mp3");
            openPicker.FileTypeFilter.Add(".wma");

            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                var mediaSource = MediaSource.CreateFromStorageFile(file);
                mediaSource.OpenOperationCompleted += MediaSource_OpenOperationCompleted;
                ViewModel.MediaPlayer.Source        = mediaSource;
                if (file.FileType == ".mp3" || file.FileType == ".wma")
                {
                    //
                    StateChange(false);
                    using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 300))
                    {
                        if (thumbnail != null && thumbnail.Type == ThumbnailType.Image)
                        {
                            var bitmapImage = new BitmapImage();
                            bitmapImage.SetSource(thumbnail);
                            var imageBrush = new ImageBrush();
                            imageBrush.ImageSource        = bitmapImage;
                            _compositionCanvas.Background = imageBrush;
                        }
                    }
                }
                else
                {
                    StateChange(true);
                }
                Begin();
            }
        }
        /// <summary>
        /// Launch file picker for user to select a picture file and return a VideoFrame
        /// </summary>
        /// <returns>VideoFrame instanciated from the selected image file</returns>
        public static IAsyncOperation <VideoFrame> LoadVideoFrameFromFilePickedAsync()
        {
            return(AsyncInfo.Run(async(token) =>
            {
                // Trigger file picker to select an image file
                FileOpenPicker fileOpenPicker = new FileOpenPicker
                {
                    SuggestedStartLocation = PickerLocationId.PicturesLibrary
                };
                fileOpenPicker.FileTypeFilter.Add(".jpg");
                fileOpenPicker.FileTypeFilter.Add(".png");
                fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;
                StorageFile selectedStorageFile = await fileOpenPicker.PickSingleFileAsync();

                if (selectedStorageFile == null)
                {
                    return null;
                }

                // Decoding image file content into a SoftwareBitmap, and wrap into VideoFrame
                VideoFrame resultFrame = null;
                SoftwareBitmap softwareBitmap = null;
                using (IRandomAccessStream stream = await selectedStorageFile.OpenAsync(FileAccessMode.Read))
                {
                    // Create the decoder from the stream
                    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                    // Get the SoftwareBitmap representation of the file in BGRA8 format
                    softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                    // Convert to friendly format for UI display purpose
                    softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                }

                // Encapsulate the image in a VideoFrame instance
                resultFrame = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);

                return resultFrame;
            }));
        }
Esempio n. 25
0
    public async Task <uint> OpenAsync()
    {
        uint pages = 0;

        try
        {
            _document = null;
            FileOpenPicker picker = new FileOpenPicker()
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeFilter.Add(".pdf");
            StorageFile open = await picker.PickSingleFileAsync();

            if (open != null)
            {
                _document = await PdfDocument.LoadFromFileAsync(open);
            }
            if (_document != null)
            {
                if (_document.IsPasswordProtected)
                {
                    Show("Password Protected PDF Document", app_title);
                }
                pages = _document.PageCount;
            }
        }
        catch (Exception ex)
        {
            if (ex.HResult == unchecked ((int)0x80004005))
            {
                Show("Invalid PDF Document", app_title);
            }
            else
            {
                Show(ex.Message, app_title);
            }
        }
        return(pages);
    }
        /// <summary>
        /// 播放列表添加
        /// </summary>
        private async void openMedia()
        {
            // 文件对话框
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
            openPicker.FileTypeFilter.Add(".mp4");
            openPicker.FileTypeFilter.Add(".mkv");
            openPicker.FileTypeFilter.Add(".avi");

            // 文件对象
            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                // 创建缩略图
                var thumbnail = await file.GetScaledImageAsThumbnailAsync(ThumbnailMode.VideosView);

                WriteableBitmap            writeableBitmap    = new WriteableBitmap(100, 64);
                InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                await RandomAccessStream.CopyAsync(thumbnail, randomAccessStream);

                randomAccessStream.Seek(0);
                writeableBitmap.SetSource(randomAccessStream);
                //UserSettings.saveThubnail(writeableBitmap, file.DisplayName + ".jpg");

                // 媒体对象
                MediaModel media = new MediaModel(file)
                {
                    canSync          = true,
                    Title            = file.Name,
                    ArtUri           = writeableBitmap,
                    PlaybackPosition = TimeSpan.Parse("00:00:00"),
                    PlaybackHistory  = DateTime.Now
                };
                pVLis.Items.Add(media);
                playbackList.Items.Add(media.MediaPlaybackItem);
            }
        }
Esempio n. 27
0
        private async void Upload_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker open = new FileOpenPicker();

            open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            open.ViewMode = PickerViewMode.Thumbnail;

            // Filter to include a sample subset of file types
            open.FileTypeFilter.Clear();
            open.FileTypeFilter.Add(".bmp");
            open.FileTypeFilter.Add(".png");
            open.FileTypeFilter.Add(".jpeg");
            open.FileTypeFilter.Add(".jpg");

            // Open a stream for the selected file
            StorageFile file = await open.PickSingleFileAsync();

            // Ensure a file was selected
            if (file != null)
            {
                // Ensure the stream is disposed once the image is loaded
                using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
                {
                    BitmapImage bitmapImage = new BitmapImage();
                    await bitmapImage.SetSourceAsync(fileStream);

                    fileStream.AsStream().CopyTo(stream);
                    //img.Source = bitmapImage;
                }
            }

            Uri uri = new Uri(serverAddressField.Text);

            Windows.Web.Http.HttpClient client        = new Windows.Web.Http.HttpClient();
            HttpStreamContent           streamContent = new HttpStreamContent(stream.AsInputStream());

            Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, uri);
            request.Content = streamContent;
            Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(uri, streamContent).AsTask(cts.Token);
        }
Esempio n. 28
0
        async private void CopyBitmap(bool isDelayRendered)
        {
            rootPage.NotifyUser("", NotifyType.StatusMessage);

            var imagePicker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                FileTypeFilter         = { ".jpg", ".png", ".bmp", ".gif", ".tif" }
            };

            var imageFile = await imagePicker.PickSingleFileAsync();

            if (imageFile != null)
            {
                var dataPackage = new DataPackage();

                string message;
                if (isDelayRendered)
                {
                    dataPackage.SetDataProvider(StandardDataFormats.Bitmap, request => OnDeferredImageRequestedHandler(request, imageFile));
                    message = "Image has been copied using delayed rendering";
                }
                else
                {
                    dataPackage.SetBitmap(RandomAccessStreamReference.CreateFromFile(imageFile));
                    message = "Image has been copied";
                }

                if (Clipboard.SetContentWithOptions(dataPackage, null))
                {
                    rootPage.NotifyUser(message, NotifyType.StatusMessage);
                }
                else
                {
                    // Copying data to Clipboard can potentially fail - for example, if another application is holding Clipboard open
                    rootPage.NotifyUser("Error copying content to clipboard.", NotifyType.ErrorMessage);
                }
            }
        }
Esempio n. 29
0
        private async void ProjectOpen_ExecuteRequested(XamlUICommand sender,
                                                        ExecuteRequestedEventArgs args)
        {
            // Prompt user to save unsaved changes (if applicable)
            if (await ProceedAfterPromptToSaveChanges() == false)
            {
                return;
            }

            ActiveProject = null;
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.Desktop,
                CommitButtonText       = "Open",
                FileTypeFilter         = { ".mbp" }
            };

            var file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                return;
            }

            ActiveProject = await Project.Load(file);

            var title      = AppTitleText;
            var mediaFiles = ActiveProject.GetAllMediaFiles <MediaTreeFile>() as MediaTreeFile[] ??
                             ActiveProject.GetAllMediaFiles <MediaTreeFile>().ToArray();

            // Get each file from its storage location
            for (var i = 0; i < mediaFiles.Length; i++)
            {
                await mediaFiles[i].GetFileFromPathAsync();
                AppTitleText = $"{title} - Loading ({mediaFiles.Length - i} files remaining)";
            }

            AppTitleText = title;
        }
Esempio n. 30
0
        private async void GetThumbnailButton_Click(object sender, RoutedEventArgs e)
        {
            rootPage.ResetOutput(ThumbnailImage, OutputTextBlock);

            if (rootPage.EnsureUnsnapped())
            {
                // Pick a music file
                FileOpenPicker openPicker = new FileOpenPicker();
                foreach (string extension in FileExtensions.Music)
                {
                    openPicker.FileTypeFilter.Add(extension);
                }

                StorageFile file = await openPicker.PickSingleFileAsync();

                if (file != null)
                {
                    const ThumbnailMode thumbnailMode = ThumbnailMode.MusicView;
                    const uint          size          = 100;
                    using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, size))
                    {
                        // Also verify the type is ThumbnailType.Image (album art) instead of ThumbnailType.Icon
                        // (which may be returned as a fallback if the file does not provide album art)
                        if (thumbnail != null && thumbnail.Type == ThumbnailType.Image)
                        {
                            // Display the thumbnail
                            MainPage.DisplayResult(ThumbnailImage, OutputTextBlock, thumbnailMode.ToString(), size, file, thumbnail, false);
                        }
                        else
                        {
                            rootPage.NotifyUser(Errors.NoAlbumArt, NotifyType.StatusMessage);
                        }
                    }
                }
                else
                {
                    rootPage.NotifyUser(Errors.Cancel, NotifyType.StatusMessage);
                }
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Picks a video from the default gallery
        /// </summary>
        /// <returns>Media file of video or null if canceled</returns>
        public async Task <MediaFile> PickVideoAsync()
        {
            var picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.VideosLibrary,
                ViewMode = PickerViewMode.Thumbnail
            };

            foreach (var filter in SupportedVideoFileTypes)
            {
                picker.FileTypeFilter.Add(filter);
            }

            var result = await picker.PickSingleFileAsync();

            if (result == null)
            {
                return(null);
            }

            var         aPath = result.Path;
            var         path  = result.Path;
            StorageFile copy  = null;

            //copy local
            try
            {
                var fileNameNoEx = Path.GetFileNameWithoutExtension(aPath);
                copy = await result.CopyAsync(ApplicationData.Current.LocalFolder,
                                              fileNameNoEx + result.FileType, NameCollisionOption.GenerateUniqueName);

                path = copy.Path;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("unable to save to app directory:" + ex);
            }

            return(new MediaFile(path, () => copy != null ? copy.OpenStreamForReadAsync().Result : result.OpenStreamForReadAsync().Result, aPath));
        }
        /// <summary>
        /// This method signature is for computers, the distinct difference being it being asynchronous.
        /// </summary>
        private async void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
#endif
            // Set up a file picker
            FileOpenPicker picker = new FileOpenPicker();
            // Add file extensions
            picker.FileTypeFilter.Add(".png");
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            // Set the view mode to thumbnail so they can see them
            picker.ViewMode = PickerViewMode.Thumbnail;
            // And put them in the pictures directory since that's probably where they want to go
            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            // This gives a name to this picker so it doesn't default to other pickers' last locations
            picker.SettingsIdentifier = "AvatarPicker";
            picker.CommitButtonText   = "Set as avatar";

#if WINDOWS_PHONE_APP
            // For a phone we just do this, and it redirects to the continue method above when finished
            picker.PickSingleFileAndContinue();
#else
            // On a computer we're able to continue here; we use await because it will pause for the file to be selected
            StorageFile file = await picker.PickSingleFileAsync();

            // Check if they selected a file
            if (file != null)
            {
                StorageFile copiedFile = await file.CopyAsync(await ApplicationData.Current.RoamingFolder.CreateFolderAsync("MemberPhotos", CreationCollisionOption.OpenIfExists), "temp.png", NameCollisionOption.ReplaceExisting);

                // Open the copied file into a bitmap
                BitmapImage image = new BitmapImage();
                // Set the source to the file's read stream
                image.SetSource(await copiedFile.OpenReadAsync());

                // And finally load it into the image
                imgMemberPicture.Source = image;
                imageSelected           = true;
            }
#endif
        }
        /// <summary>
        /// Click handler for the "Select a media file" button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OpenFileButton_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker fileOpenPicker = new FileOpenPicker();

            // Filter to include a sample subset of file types
            fileOpenPicker.FileTypeFilter.Add(".wmv");
            fileOpenPicker.FileTypeFilter.Add(".mp4");
            fileOpenPicker.FileTypeFilter.Add(".mp3");
            fileOpenPicker.FileTypeFilter.Add(".wma");
            fileOpenPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;

            StorageFile file = await fileOpenPicker.PickSingleFileAsync();

            // Ensure a file was selected
            if (file != null)
            {
                MediaPlaybackType mediaPlaybackType;
                if ((file.FileType == ".mp4") || (file.FileType == ".wmv"))
                {
                    mediaPlaybackType = MediaPlaybackType.Video;
                }
                else
                {
                    mediaPlaybackType = MediaPlaybackType.Music;
                }

                // Inform the system transport controls of the media information
                if (!(await systemMediaControls.DisplayUpdater.CopyFromFileAsync(mediaPlaybackType, file)))
                {
                    //  Problem extracting metadata- just clear everything
                    systemMediaControls.DisplayUpdater.ClearAll();
                }
                systemMediaControls.DisplayUpdater.Update();

                IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);

                // Set the selected file as the MediaElement's source
                Scenario6MediaElement.SetSource(stream, file.ContentType);
            }
        }