Пример #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.
     }
 }
Пример #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;
		}
Пример #4
0
        private void OpenFiles( OpenFileInteraction interaction )
        {
            Contract.Requires( interaction != null );

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

            dialog.ContinuationData.AddRange( interaction.ContinuationData );
            dialog.FileTypeFilter.AddRange( interaction.FileTypeFilter.FixUpExtensions() );
            dialog.SuggestedStartLocation = SuggestedStartLocation;
            dialog.ViewMode = ViewMode;

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

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

            if ( interaction.Multiselect )
                dialog.PickMultipleFilesAndContinue();
            else
                dialog.PickSingleFileAndContinue();
        }
Пример #5
0
        private async void Theme_Click(object sender, RoutedEventArgs e)
        {
            if (Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift).HasFlag(CoreVirtualKeyStates.Down))
            {
                var remove = await FileUtils.TryGetTempItemAsync("theme.xaml");

                if (remove != null)
                {
                    await remove.DeleteAsync();

                    Theme.Current.Update();
                    App.RaiseThemeChanged();
                }

                return;
            }

            var picker = new FileOpenPicker();

            picker.FileTypeFilter.Add(".xaml");

            var file = await picker.PickSingleFileAsync();

            if (file != null)
            {
                var result = await FileUtils.CreateTempFileAsync("theme.xaml");

                await file.CopyAndReplaceAsync(result);

                Theme.Current.Update();
                App.RaiseThemeChanged();

                //var text = await FileIO.ReadTextAsync(file);

                //var dictionary = XamlReader.Load(text) as ResourceDictionary;
                //if (dictionary == null)
                //{
                //    return;
                //}

                //var accent = App.Current.Resources.MergedDictionaries.FirstOrDefault(x => x.Source.AbsoluteUri.EndsWith("Accent.xaml"));
                //if (accent == null)
                //{
                //    return;
                //}

                //foreach (var theme in dictionary.ThemeDictionaries)
                //{
                //    var item = theme.Value as ResourceDictionary;
                //    if (accent.ThemeDictionaries.TryGetValue(theme.Key, out object value))
                //    {
                //        var pair = value as ResourceDictionary;
                //        if (pair == null)
                //        {
                //            continue;
                //        }

                //        foreach (var key in item)
                //        {
                //            if (pair.ContainsKey(key.Key))
                //            {
                //                try
                //                {
                //                    pair[key.Key] = key.Value;
                //                }
                //                catch
                //                {
                //                    Debug.WriteLine("Theme: unable to apply " + key.Key);
                //                }
                //            }
                //        }
                //    }
                //}

                //App.RaiseThemeChanged();
            }
        }
Пример #6
0
        /// <summary>
        /// This is the main scenario worker.
        /// </summary>
        /// <param name="Algorithm">
        /// Comression algorithm to use. If no value is provided compressor will be created using
        /// Compressor(IInputStream) constructor, otherwise extended version will be used:
        /// Compressor(IInputStream, CompressAlgorithm, uint)
        /// </param>
        private async void DoScenario(CompressAlgorithm?Algorithm)
        {
            try
            {
                Progress.Text = "";

                // This scenario uses File Picker which doesn't work in snapped mode - try unsnap first
                // and fail gracefully if we can't
                if ((ApplicationView.Value == ApplicationViewState.Snapped) &&
                    !ApplicationView.TryUnsnap())
                {
                    throw new NotSupportedException("Sample doesn't work in snapped mode");
                }

                rootPage.NotifyUser("Working...", NotifyType.StatusMessage);

                var picker = new FileOpenPicker();
                picker.FileTypeFilter.Add("*");
                var originalFile = await picker.PickSingleFileAsync();

                if (originalFile == null)
                {
                    throw new OperationCanceledException("No file has been selected");
                }

                Progress.Text += String.Format("\"{0}\" has been picked\n", originalFile.Name);

                var compressedFilename = originalFile.Name + ".compressed";
                var compressedFile     = await KnownFolders.DocumentsLibrary.CreateFileAsync(compressedFilename, CreationCollisionOption.GenerateUniqueName);

                Progress.Text += String.Format("\"{0}\" has been created to store compressed data\n", compressedFile.Name);

                // ** DO COMPRESSION **
                // Following code actually performs compression from original file to the newly created
                // compressed file. In order to do so it:
                // 1. Opens input for the original file.
                // 2. Opens output stream on the file to be compressed and wraps it into Compressor object.
                // 3. Copies original stream into Compressor wrapper.
                // 4. Finalizes compressor - it puts termination mark into stream and flushes all intermediate
                //    buffers.
                using (var originalInput = await originalFile.OpenReadAsync())
                    using (var compressedOutput = await compressedFile.OpenAsync(FileAccessMode.ReadWrite))
                        using (var compressor = !Algorithm.HasValue ?
                                                new Compressor(compressedOutput.GetOutputStreamAt(0)) :
                                                new Compressor(compressedOutput.GetOutputStreamAt(0), Algorithm.Value, 0))
                        {
                            Progress.Text += "All streams wired for compression\n";
                            var bytesCompressed = await RandomAccessStream.CopyAsync(originalInput, compressor);

                            var finished = await compressor.FinishAsync();

                            Progress.Text += String.Format("Compressed {0} bytes into {1}\n", bytesCompressed, compressedOutput.Size);
                        }

                var decompressedFilename = originalFile.Name + ".decompressed";
                var decompressedFile     = await KnownFolders.DocumentsLibrary.CreateFileAsync(decompressedFilename, CreationCollisionOption.GenerateUniqueName);

                Progress.Text += String.Format("\"{0}\" has been created to store decompressed data\n", decompressedFile.Name);

                // ** DO DECOMPRESSION **
                // Following code performs decompression from the just compressed file to the
                // decompressed file. In order to do so it:
                // 1. Opens input stream on compressed file and wraps it into Decompressor object.
                // 2. Opens output stream from the file that will store decompressed data.
                // 3. Copies data from Decompressor stream into decompressed file stream.
                using (var compressedInput = await compressedFile.OpenSequentialReadAsync())
                    using (var decompressor = new Decompressor(compressedInput))
                        using (var decompressedOutput = await decompressedFile.OpenAsync(FileAccessMode.ReadWrite))
                        {
                            Progress.Text += "All streams wired for decompression\n";
                            var bytesDecompressed = await RandomAccessStream.CopyAsync(decompressor, decompressedOutput);

                            Progress.Text += String.Format("Decompressed {0} bytes of data\n", bytesDecompressed);
                        }

                rootPage.NotifyUser("All done", NotifyType.StatusMessage);
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
            }
        }
Пример #7
0
        private async void UploadFile()
        {
            if (this.liveClient == null)
            {
                this.ShowMessage("Please sign in first.");
                return;
            }

            try
            {
                string folderPath = this.tbUrl.Text;
                var    picker     = new FileOpenPicker
                {
                    ViewMode = PickerViewMode.Thumbnail,
                    SuggestedStartLocation = PickerLocationId.PicturesLibrary
                };
                picker.FileTypeFilter.Add("*");

                StorageFile file = await picker.PickSingleFileAsync();

                if (file != null)
                {
                    using (IInputStream inStream = await file.OpenReadAsync().AsTask())
                    {
                        this.progressBar.Value = 0;
                        this.ShowProgress();
                        var progressHandler = new Progress <LiveOperationProgress>(
                            (progress) => { this.progressBar.Value = progress.ProgressPercentage; });

                        this.cts = new CancellationTokenSource();
                        LiveOperationResult result =
                            await this.liveClient.BackgroundUploadAsync(
                                folderPath,
                                file.Name,
                                inStream,
                                OverwriteOption.Rename,
                                this.cts.Token,
                                progressHandler);

                        if (result != null)
                        {
                            this.progressBar.Value = 0;
                            dynamic fileData    = result.Result;
                            string  downloadUrl = fileData.id + "/picture";
                            this.tbUrl.Text = downloadUrl;

                            this.ShowMessage("Upload completed.");
                        }
                        else
                        {
                            this.ShowMessage("Upload failed.");
                        }
                    }
                }
            }
            catch (TaskCanceledException)
            {
                this.ShowMessage("User has cancelled the operation.");
            }
            catch (Exception exp)
            {
                this.ShowMessage(exp.ToString());
            }
        }
Пример #8
0
        private async void StartMultipleFilesUpload(FileOpenPicker picker, Uri uri)
        {
            IReadOnlyList <StorageFile> files = await picker.PickMultipleFilesAsync();

            UploadMultipleFiles(uri, files);
        }
Пример #9
0
        private async void loadFileDialogAsync(FolderLocations folderLocation, int maxWidth, int maxHeight, string[] fileTypes, StreamLoadedCallbackMethod streamLoadedCallback)
                #endif
        {
                        #if WINDOWS_PHONE
            WinRTPlugin.Dispatcher.BeginInvoke(async delegate()
                        #elif UNITY_WP_8_1
            await WinRTPlugin.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, delegate()
                        #else
            await WinRTPlugin.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async delegate()
                        #endif
            {
                Stream stream = null;
                try
                {
                                        #if WINDOWS_PHONE
                    if (folderLocation == FolderLocations.Pictures)
                    {
                        photoChooser            = new PhotoChooserTask();
                        photoChooser.ShowCamera = false;
                        photoChooser.Completed += photoChooserTask_Completed;
                        photoChooserTask_StreamLoadedCallback = streamLoadedCallback;
                        photoChooserTask_fileTypes            = fileTypes;
                        photoChooserTask_maxWidth             = maxWidth;
                        photoChooserTask_maxHeight            = maxHeight;
                        photoChooser.Show();
                        return;
                    }
                                        #endif

                    var picker = new FileOpenPicker();
                    if (fileTypes != null)
                    {
                        foreach (var fileType in fileTypes)
                        {
                            picker.FileTypeFilter.Add(fileType);
                        }
                    }

                    picker.SuggestedStartLocation = getFolderType(folderLocation);
                                        #if UNITY_WP_8_1
                    LoadFileDialog_picker = picker;
                    LoadFileDialog_streamLoadedCallback = streamLoadedCallback;
                    LoadFileDialog_maxWidth             = maxWidth;
                    LoadFileDialog_maxHeight            = maxHeight;
                    picker.PickSingleFileAndContinue();
                                        #else
                    var file = await picker.PickSingleFileAsync();
                    if (file != null)
                    {
                        if (maxWidth == 0 || maxHeight == 0)
                        {
                            stream = await file.OpenStreamForReadAsync();
                            streamLoadedCallback(stream, true);
                        }
                        else
                        {
                                                        #if UNITY_METRO
                            using (var tempStream = await file.OpenStreamForReadAsync())
                            {
                                                                #if UNITY_METRO_8_0
                                using (var outputStream = new MemoryStream().AsOutputStream())
                                {
                                    await RandomAccessStream.CopyAsync(tempStream.AsInputStream(), outputStream);
                                    stream = await resizeImageStream((IRandomAccessStream)outputStream, maxWidth, maxHeight);
                                }
                                                                #else
                                stream = await resizeImageStream(tempStream.AsRandomAccessStream(), maxWidth, maxHeight);
                                                                #endif
                            }

                            streamLoadedCallback(stream, true);
                                                        #endif
                        }
                    }
                    else
                    {
                        streamLoadedCallback(null, false);
                    }
                                        #endif
                }
                catch (Exception e)
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                    Debug.LogError(e.Message);
                    streamLoadedCallback(null, false);
                }
            });
        }
Пример #10
0
        private async void getSettings_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker fp = new FileOpenPicker();

            fp.ViewMode = PickerViewMode.Thumbnail;
            fp.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            fp.FileTypeFilter.Add(".txt");

            StorageFile file = await fp.PickSingleFileAsync();

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

                using (var reader = new StreamReader(stream.AsStream()))
                {
                    string temp1 = await reader.ReadToEndAsync();

                    App.add_value_list(ref App.settingsData, temp1);

                    if (App.settingsData != "")
                    {
                        App.loaded_settings(ref App.loadSettings, 1);
                    }

                    stream.Dispose();
                    reader.Dispose();
                }

                if (App.loadSettings)
                {
                    if (page1.get_string(App.settingsData, "duborsub:-", "-").ToLower() != "")
                    {
                        if (page1.get_string(App.settingsData, "duborsub:-", "-").ToLower() == "dub")
                        {
                            dub.IsChecked = true;
                        }

                        if (page1.get_string(App.settingsData, "duborsub:-", "-").ToLower() == "sub")
                        {
                            sub.IsChecked = true;
                        }
                    }

                    if (page1.get_string(App.settingsData, "quality:-", "-").ToLower() != "")
                    {
                        if (page1.get_string(App.settingsData, "quality:-", "-").ToLower() == "1080p")
                        {
                            quality_1080p.IsChecked = true;
                        }

                        if (page1.get_string(App.settingsData, "quality:-", "-").ToLower() == "720p")
                        {
                            quality_720p.IsChecked = true;
                        }

                        if (page1.get_string(App.settingsData, "quality:-", "-").ToLower() == "480p")
                        {
                            quality_480p.IsChecked = true;
                        }
                    }
                }
            }
        }
        public void pick(JObject options, IPromise promise)
        {
            try
            {
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.Thumbnail;
                openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                // Get file type array options
                var fileTypeArray = options.Value <JArray>(OPTION_TYPE);
                var cache         = options.Value <Boolean>(CACHE_TYPE);
                // Init file type filter
                if (fileTypeArray != null && fileTypeArray.Count > 0)
                {
                    foreach (String typeString in fileTypeArray)
                    {
                        List <String> types = typeString.Split(' ').ToList();
                        foreach (String type in types)
                        {
                            if (Regex.Match(type, "(^[.]+[A-Za-z0-9]*$)|(^[*]$)").Success)
                            {
                                openPicker.FileTypeFilter.Add(type);
                            }
                        }
                    }
                }
                else
                {
                    openPicker.FileTypeFilter.Add("*");
                }

                RunOnDispatcher(async() =>
                {
                    try
                    {
                        if (_isInForeground)
                        {
                            var isMultiple = options.Value <bool>(OPTION_MULIPLE);
                            if (isMultiple)
                            {
                                await PickMultipleFileAsync(openPicker, cache, promise);
                            }
                            else
                            {
                                await PickSingleFileAsync(openPicker, cache, promise);
                            }
                        }
                        else
                        {
                            _pendingPicker = openPicker;
                        }
                    }
                    catch (Exception ex)
                    {
                        promise.Reject(E_FAILED_TO_SHOW_PICKER, ex.Message);
                    }
                });
            }
            catch (Exception ex) {
                promise.Reject(E_UNEXPECTED_EXCEPTION, ex.Message);
            }
        }
        private void Load_Click(object sender, RoutedEventArgs e)

        {
            var picker = new FileOpenPicker()
            {
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                FileTypeFilter = { ".jpg", ".jpeg", ".png" },
            };

            picker.PickSingleFileAndContinue();

        }
Пример #13
0
        private async void ButtonLoad_Click(object sender, RoutedEventArgs e)
        {
            if (map.MapElements.Count() != 0)
            {
                return;
            }


            if (!int.TryParse(tbMaxNumber.Text, out maxNumberLines))
            {
                tbMaxNumber.Text = "8000"; // max 88253 for TRA.geojson file
                maxNumberLines   = 8000;
            }

            featureList = new List <MapElement>();

            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".geojson");


            StorageFile file = await openPicker.PickSingleFileAsync();

            prRing.IsActive = true;


            string text = await Windows.Storage.FileIO.ReadTextAsync(file);

            var responseStatus = Newtonsoft.Json.JsonConvert.DeserializeObject <Rootobject>(text);

            Feature [] featureArr = responseStatus.features;

            int i = 0;


            foreach (var feature in featureArr)
            {
                var mapPolyline = new MapPolyline

                {
                    Path = new Geopath(new List <BasicGeoposition> {
                        new BasicGeoposition()
                        {
                            Latitude = feature.geometry.coordinates[0][1], Longitude = feature.geometry.coordinates[0][0]
                        },
                        new BasicGeoposition()
                        {
                            Latitude = feature.geometry.coordinates[1][1], Longitude = feature.geometry.coordinates[1][0]
                        },
                    }),
                    StrokeColor     = Colors.DarkBlue,
                    StrokeThickness = 1,
                    StrokeDashed    = true,
                };

                map.MapElements.Add(mapPolyline);


                if (i++ > maxNumberLines)
                {
                    break;
                }
            }

            prRing.IsActive = false;
        }
Пример #14
0
        private async void SelectFile_Tapped(object sender, TappedRoutedEventArgs e)
        {
            EventColor onColor;
            EventColor offColor;
            int        frameTime;
            int        maxFrames;

            try
            {
                // Grab video reconstruction settings from GUI
                // Will throw a FormatException if input is invalid (negative numbers or input has letters)
                (frameTime, maxFrames, onColor, offColor) = ParseFrameSettings();
            }
            catch (FormatException)
            {
                await invaldVideoSettingsDialog.ShowAsync();

                return;
            }

            // Select AEDAT file to be converted to video
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            picker.FileTypeFilter.Add(".AEDAT");


            // Select AEDAT file to be converted
            IReadOnlyList <StorageFile> files = await picker.PickMultipleFilesAsync();

            if (files == null)
            {
                showLoading.IsActive      = false;
                backgroundTint.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                return;
            }

            var picker2 = new FolderPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            picker2.FileTypeFilter.Add("*");

            // Select AEDAT file to be converted
            StorageFolder folder = await picker2.PickSingleFolderAsync();

            if (folder == null)
            {
                showLoading.IsActive      = false;
                backgroundTint.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                return;
            }

            foreach (var file in files)
            {
                var headerData = await AedatUtilities.GetHeaderData(file);

                var aedatFile = (await file.OpenReadAsync()).AsStreamForRead();
                aedatFile.Seek(headerData.Item1, SeekOrigin.Begin);                 //Skip over header.

                CameraParameters cam = headerData.Item2;
                if (cam == null)
                {
                    await invalidCameraDataDialog.ShowAsync();

                    return;
                }
                showLoading.IsActive      = true;
                backgroundTint.Visibility = Windows.UI.Xaml.Visibility.Visible;


                StorageFolder folder2 = await folder.CreateFolderAsync(file.Name.Replace(".aedat", "") + (playbackType.IsOn ? " time based" : " event based") + " Frames");

                if (playbackType.IsOn)
                {
                    await TimeBasedReconstruction(aedatFile, cam, onColor, offColor, frameTime, maxFrames, folder2, file.Name.Replace(".aedat", ""));
                }
                else
                {
                    int numOfEvents = Int32.Parse(numOfEventInput.Text);
                    await EventBasedReconstruction(aedatFile, cam, onColor, offColor, numOfEvents, maxFrames, folder2, file.Name.Replace(".aedat", ""));
                }
            }
            showLoading.IsActive      = false;
            backgroundTint.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }
Пример #15
0
        private async void OpenFile_Click(object sender, RoutedEventArgs e)
        {
            if (Run.Content.ToString() == "运行程序")
            {
                MessageFontColoer = "Black";
                string str = "打开文件";
                Warning = str;
                setting.StopMusicasync(str);

                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.List;
                openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                openPicker.FileTypeFilter.Add(".nc");
                openPicker.FileTypeFilter.Add(".txt");
                openPicker.FileTypeFilter.Add(".iso");
                openPicker.FileTypeFilter.Add(".dxf");
                StorageFile file = await openPicker.PickSingleFileAsync();

                if (file != null)
                {
                    // Application now has read/write access to the picked file
                    Warning = "Picked photo: " + file.Name;
                }
                else
                {
                    Warning = "Operation cancelled.";
                }
                try
                {
                    Stream streamfile = await file.OpenStreamForReadAsync();

                    StreamReader dxfFilm = new StreamReader(streamfile);

                    await ReadDxfFilm(dxfFilm);

                    dxfFilm.Dispose();
                    streamfile.Dispose();
                }
                catch (Exception)
                {
                }



                //FolderPicker.pickSingleFolderAsync().then(function(folder) {
                //    if (folder)
                //    {
                //        // Process picked folder

                //        // Store folder for future access
                //        var folderToken = Windows.Storage.AccessCache.StorageApplicationPermissions.futureAccessList.add(folder);
                //    }
                //    else
                //    {
                //        // The user didn't pick a folder
                //    }
                //});
            }
            else
            {
            }
        }
Пример #16
0
        private async void AddFile_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker Picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.ComputerFolder,
                ViewMode = PickerViewMode.Thumbnail
            };

            Picker.FileTypeFilter.Add("*");

            IReadOnlyList <StorageFile> FileList = await Picker.PickMultipleFilesAsync();

            if (FileList.Count > 0)
            {
                ActivateLoading(true, true);

                Cancellation = new CancellationTokenSource();

                try
                {
                    foreach (StorageFile File in FileList)
                    {
                        if ((await File.EncryptAsync(SecureFolder, FileEncryptionAesKey, AESKeySize, Cancellation.Token).ConfigureAwait(true)) is StorageFile EncryptedFile)
                        {
                            SecureCollection.Add(new FileSystemStorageItemBase(EncryptedFile, await EncryptedFile.GetSizeRawDataAsync().ConfigureAwait(true), new BitmapImage(new Uri("ms-appx:///Assets/LockFile.png")), await EncryptedFile.GetModifiedTimeAsync().ConfigureAwait(true)));

                            try
                            {
                                await File.DeleteAsync(StorageDeleteOption.Default);
                            }
                            catch
                            {
                            }
                        }
                        else
                        {
                            QueueContentDialog Dialog = new QueueContentDialog
                            {
                                Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                Content         = Globalization.GetString("QueueDialog_EncryptError_Content"),
                                CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                            };

                            _ = await Dialog.ShowAsync().ConfigureAwait(true);

                            break;
                        }
                    }
                }
                catch (TaskCanceledException cancelException)
                {
                    LogTracer.Log(cancelException, "Import items to SecureArea have been cancelled");
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "An error was threw when importing file");
                }
                finally
                {
                    Cancellation.Dispose();
                    Cancellation = null;

                    await Task.Delay(1500).ConfigureAwait(true);

                    ActivateLoading(false);
                }
            }
        }
Пример #17
0
        private async void StartMultipartUpload_Click(object sender, RoutedEventArgs e)
        {
            // By default 'serverAddressField' is disabled and URI validation is not required. When enabling the text
            // box validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri uri;

            if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
            {
                rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            FileOpenPicker picker = new FileOpenPicker();

            picker.FileTypeFilter.Add("*");
            IReadOnlyList <StorageFile> files = await picker.PickMultipleFilesAsync();

            if (files.Count == 0)
            {
                rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
                return;
            }

            ulong totalFileSize = 0;

            for (int i = 0; i < files.Count; i++)
            {
                BasicProperties properties = await files[i].GetBasicPropertiesAsync();
                totalFileSize += properties.Size;

                if (totalFileSize > maxUploadFileSize)
                {
                    rootPage.NotifyUser(String.Format(CultureInfo.CurrentCulture,
                                                      "Size of selected files exceeds max. upload file size ({0} MB).",
                                                      maxUploadFileSize / (1024 * 1024)), NotifyType.ErrorMessage);
                    return;
                }
            }

            List <BackgroundTransferContentPart> parts = new List <BackgroundTransferContentPart>();

            for (int i = 0; i < files.Count; i++)
            {
                BackgroundTransferContentPart part = new BackgroundTransferContentPart("File" + i, files[i].Name);
                part.SetFile(files[i]);
                parts.Add(part);
            }

            BackgroundUploader uploader = new BackgroundUploader();
            UploadOperation    upload   = await uploader.CreateUploadAsync(uri, parts);

            String fileNames = files[0].Name;

            for (int i = 1; i < files.Count; i++)
            {
                fileNames += ", " + files[i].Name;
            }

            Log(String.Format(CultureInfo.CurrentCulture, "Uploading {0} to {1}, {2}", fileNames, uri.AbsoluteUri,
                              upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
        private async void loadImage_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker fileOpenPicker = new FileOpenPicker();

            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileOpenPicker.FileTypeFilter.Add(".jpg");
            fileOpenPicker.ViewMode = PickerViewMode.Thumbnail;

            var inputFile = await fileOpenPicker.PickSingleFileAsync();

            if (inputFile == null)
            {
                // The user cancelled the picking operation
                return;
            }

            SoftwareBitmap softwareBitmap;

            using (IRandomAccessStream stream = await inputFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                // Create the decoder from the stream
                BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

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

            if (softwareBitmap.BitmapPixelFormat != BitmapPixelFormat.Bgra8 || softwareBitmap.BitmapAlphaMode == BitmapAlphaMode.Straight)
            {
                softwareBitmap = SoftwareBitmap.Convert(softwareBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
            }

            var source = new SoftwareBitmapSource();
            await source.SetBitmapAsync(softwareBitmap);

            imageControl.Source = source;

            var device = CanvasDevice.GetSharedDevice();
            var image  = default(CanvasBitmap);

            using (var s = await inputFile.OpenReadAsync())
            {
                image = await CanvasBitmap.LoadAsync(device, s);
            }

            var offscreen = new CanvasRenderTarget(device, (float)image.Bounds.Width, (float)image.Bounds.Height, 96);

            using (var ds = offscreen.CreateDrawingSession())
            {
                ds.DrawImage(image, 0, 0);
                ds.DrawText("Hello note", 10, 400, Colors.Aqua);
            }


            var displayInformation = DisplayInformation.GetForCurrentView();
            var savepicker         = new FileSavePicker();

            savepicker.FileTypeChoices.Add("png", new List <string> {
                ".png"
            });
            var destFile = await savepicker.PickSaveFileAsync();

            using (var s = await destFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, s);

                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    (uint)offscreen.Size.Width,
                    (uint)offscreen.Size.Height,
                    displayInformation.LogicalDpi,
                    displayInformation.LogicalDpi,
                    offscreen.GetPixelBytes());
                await encoder.FlushAsync();
            }
        }
        private async void PickWebLogo(object sender, RoutedEventArgs e)
        {
            try
            {
                FileOpenPicker Picker = new FileOpenPicker
                {
                    SuggestedStartLocation = PickerLocationId.ComputerFolder,
                    ViewMode = PickerViewMode.List
                };
                Picker.FileTypeFilter.Add(".ico");
                Picker.FileTypeFilter.Add(".png");
                Picker.FileTypeFilter.Add(".jpg");
                Picker.FileTypeFilter.Add(".bmp");

                if (await Picker.PickSingleFileAsync() is StorageFile ExecuteFile)
                {
                    StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting);

                    if (await ExecuteFile.OpenReadAsync() is IRandomAccessStream LogoStream)
                    {
                        try
                        {
                            BitmapImage Image = new BitmapImage();
                            Icon.Source = Image;
                            await Image.SetSourceAsync(LogoStream);

                            LogoStream.Seek(0);

                            using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync())
                            {
                                await LogoStream.AsStreamForRead().CopyToAsync(FileStream);
                            }
                        }
                        finally
                        {
                            LogoStream.Dispose();
                        }
                    }
                    else
                    {
                        Uri PageUri = AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png");

                        StorageFile PageFile = await StorageFile.GetFileFromApplicationUriAsync(PageUri);

                        using (IRandomAccessStream PageStream = await PageFile.OpenAsync(FileAccessMode.Read))
                        {
                            BitmapImage Image = new BitmapImage();
                            Icon.Source = Image;
                            await Image.SetSourceAsync(PageStream);

                            PageStream.Seek(0);

                            using (Stream TransformStream = PageStream.AsStreamForRead())
                                using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync())
                                {
                                    await TransformStream.CopyToAsync(FileStream);
                                }
                        }
                    }

                    ImageFile = FileThumbnail;
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex);
                FailureTips.IsOpen = true;
            }
        }
        private async void PickWin32_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FileOpenPicker Picker = new FileOpenPicker
                {
                    SuggestedStartLocation = PickerLocationId.ComputerFolder,
                    ViewMode = PickerViewMode.List
                };

                Picker.FileTypeFilter.Add(".exe");
                Picker.FileTypeFilter.Add(".lnk");
                Picker.FileTypeFilter.Add(".msc");

                if (await Picker.PickSingleFileAsync() is StorageFile ExecuteFile)
                {
                    IDictionary <string, object> PropertiesDictionary = await ExecuteFile.Properties.RetrievePropertiesAsync(new string[] { "System.FileDescription" });

                    string ExtraAppName = string.Empty;

                    if (PropertiesDictionary.TryGetValue("System.FileDescription", out object DescriptionRaw))
                    {
                        ExtraAppName = Convert.ToString(DescriptionRaw);
                    }

                    DisplayName.Text = string.IsNullOrEmpty(ExtraAppName) ? ExecuteFile.DisplayName : ExtraAppName;

                    Protocol.Text = ExecuteFile.Path;

                    StorageFile FileThumbnail = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("FileThumbnail.png", CreationCollisionOption.ReplaceExisting);

                    if (await ExecuteFile.GetThumbnailRawStreamAsync() is IRandomAccessStream ThumbnailStream)
                    {
                        try
                        {
                            BitmapDecoder Decoder = await BitmapDecoder.CreateAsync(ThumbnailStream);

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

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

                                        BitmapImage Image = new BitmapImage();
                                        Icon.Source = Image;
                                        await Image.SetSourceAsync(ResizeBitmapStream);

                                        ResizeBitmapStream.Seek(0);
                                        using (Stream TransformStream = ResizeBitmapStream.AsStreamForRead())
                                            using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync())
                                            {
                                                await TransformStream.CopyToAsync(FileStream);
                                            }
                                    }
                        }
                        finally
                        {
                            ThumbnailStream.Dispose();
                        }
                    }
                    else
                    {
                        Uri PageUri = AppThemeController.Current.Theme == ElementTheme.Dark ? new Uri("ms-appx:///Assets/Page_Solid_White.png") : new Uri("ms-appx:///Assets/Page_Solid_Black.png");

                        StorageFile PageFile = await StorageFile.GetFileFromApplicationUriAsync(PageUri);

                        using (IRandomAccessStream PageStream = await PageFile.OpenAsync(FileAccessMode.Read))
                        {
                            BitmapImage Image = new BitmapImage();
                            Icon.Source = Image;
                            await Image.SetSourceAsync(PageStream);

                            PageStream.Seek(0);

                            using (Stream TransformStream = PageStream.AsStreamForRead())
                                using (Stream FileStream = await FileThumbnail.OpenStreamForWriteAsync())
                                {
                                    await TransformStream.CopyToAsync(FileStream);
                                }
                        }
                    }

                    ImageFile = FileThumbnail;
                }
            }
            catch (Exception ex)
            {
                LogTracer.Log(ex);
                FailureTips.IsOpen = true;
            }
        }
        private async void addImgGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (((CommunityImageList)e.ClickedItem).imgName == "CommunityAddImg.png")
            {
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                openPicker.FileTypeFilter.Add(".png");
                openPicker.FileTypeFilter.Add(".jpg");
                openPicker.FileTypeFilter.Add(".bmp");
                openPicker.ContinuationData["Operation"] = "img";
                IReadOnlyList <StorageFile> files = await openPicker.PickMultipleFilesAsync();

                if (files.Count + imageList.Count > 10)
                {
                    Utils.Message("哦吼~最多只能上传9张图哦");
                }
                else
                {
                    if (files != null)
                    {
                        foreach (var item in imageList)
                        {
                            foreach (var file in files)
                            {
                                if (item.imgPath == file.Path)
                                {
                                    Utils.Message("此图片已添加,换一张吧 ^_^");
                                    return;
                                }
                            }
                        }
                        foreach (var file in files)
                        {
                            file2SoftwareBitmapSource(file, imageList.Count - 1);
                        }
                        if (files.Count + imageList.Count >= 10)
                        {
                            imageList.RemoveAt(imageList.Count - 1);
                        }
                    }
                }
            }
            else
            {
                var dig   = new MessageDialog("是否删除此照片", "哎呀~你要删了我么?");
                var btnOk = new UICommand("是的,不要了");
                dig.Commands.Add(btnOk);
                var btnCancel = new UICommand("不,我还要");
                dig.Commands.Add(btnCancel);
                var result = await dig.ShowAsync();

                if (null != result && result.Label == "是的,不要了")
                {
                    imageList.Remove((CommunityImageList)e.ClickedItem);
                    if (imageList.Count == 8)
                    {
                        StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///../Assets/CommunityAddImg.png"));

                        if (file != null)
                        {
                            file2SoftwareBitmapSource(file, imageList.Count);
                        }
                    }
                }
                else if (null != result && result.Label == "不,我还要")
                {
                }
            }
        }
        private async void SelectFile_Tapped(object sender, TappedRoutedEventArgs e)
        {
            int frameTime;
            int maxFrames;

            try
            {
                // Grab video reconstruction settings from GUI
                // Will throw a FormatException if input is invalid (negative numbers or input has letters)
                (frameTime, maxFrames) = ParseVideoSettings();
            }
            catch (FormatException)
            {
                await invaldVideoSettingsDialog.ShowAsync();

                return;
            }

            // Select AEDAT file to be converted to video
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            picker.FileTypeFilter.Add(".AEDAT");


            // Select AEDAT file to be converted
            IReadOnlyList <StorageFile> files = await picker.PickMultipleFilesAsync();

            if (files == null)
            {
                showLoading.IsActive      = false;
                backgroundTint.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                return;
            }


            var picker2 = new FolderPicker
            {
                ViewMode = PickerViewMode.Thumbnail,
                SuggestedStartLocation = PickerLocationId.PicturesLibrary
            };

            picker2.FileTypeFilter.Add("*");
            // Select AEDAT file to be converted
            StorageFolder folder = await picker2.PickSingleFolderAsync();

            if (folder == null)
            {
                showLoading.IsActive      = false;
                backgroundTint.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                return;
            }


            foreach (StorageFile file in files)
            {
                byte[] aedatFile = await AedatUtilities.ReadToBytes(file);

                // Determine camera type from AEDAT header
                string           cameraTypeSearch = AedatUtilities.FindLineInHeader(AedatUtilities.hardwareInterfaceCheck, ref aedatFile);
                CameraParameters cam = AedatUtilities.ParseCameraModel(cameraTypeSearch);
                if (cam == null)
                {
                    await invalidCameraDataDialog.ShowAsync();

                    return;
                }
                showLoading.IsActive      = true;
                backgroundTint.Visibility = Windows.UI.Xaml.Visibility.Visible;

                StorageFolder folder2 = await folder.CreateFolderAsync(file.Name.Replace(".aedat", "") + " Event Chunks");

                if (playbackType.IsOn)
                {
                    await TimeBasedReconstruction(aedatFile, cam, frameTime, maxFrames, folder2, file.Name.Replace(".aedat", ""));
                }
                else
                {
                    int numOfEvents = Int32.Parse(numOfEventInput.Text);
                    await EventBasedReconstruction(aedatFile, cam, numOfEvents, maxFrames, folder2, file.Name.Replace(".aedat", ""));
                }
            }
            showLoading.IsActive      = false;
            backgroundTint.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }
Пример #23
0
 private void PickImage(FileOpenPicker openPicker)
 {
     openPicker.PickSingleFileAndContinue();
 }
Пример #24
0
        private async void AddFile_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker Picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.ComputerFolder,
                ViewMode = PickerViewMode.Thumbnail
            };

            Picker.FileTypeFilter.Add("*");

            IReadOnlyList <StorageFile> FileList = await Picker.PickMultipleFilesAsync();

            if (FileList.Count > 0)
            {
                ActivateLoading(true, true);

                Cancellation = new CancellationTokenSource();

                try
                {
                    foreach (string OriginFilePath in FileList.Select((Item) => Item.Path))
                    {
                        if (await FileSystemStorageItemBase.OpenAsync(OriginFilePath).ConfigureAwait(true) is FileSystemStorageFile File)
                        {
                            if (await File.EncryptAsync(SecureFolder.Path, EncryptionAESKey, AESKeySize, Cancellation.Token).ConfigureAwait(true) is FileSystemStorageFile EncryptedFile)
                            {
                                SecureCollection.Add(EncryptedFile);

                                await File.DeleteAsync(false).ConfigureAwait(true);
                            }
                            else
                            {
                                QueueContentDialog Dialog = new QueueContentDialog
                                {
                                    Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                                    Content         = Globalization.GetString("QueueDialog_EncryptError_Content"),
                                    CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                                };

                                _ = await Dialog.ShowAsync().ConfigureAwait(true);
                            }
                        }
                    }
                }
                catch (TaskCanceledException cancelException)
                {
                    LogTracer.Log(cancelException, "Import items to SecureArea have been cancelled");
                }
                catch (Exception ex)
                {
                    LogTracer.Log(ex, "An exception was threw when importing file");

                    QueueContentDialog Dialog = new QueueContentDialog
                    {
                        Title           = Globalization.GetString("Common_Dialog_ErrorTitle"),
                        Content         = Globalization.GetString("QueueDialog_EncryptError_Content"),
                        CloseButtonText = Globalization.GetString("Common_Dialog_CloseButton")
                    };

                    _ = await Dialog.ShowAsync().ConfigureAwait(true);
                }
                finally
                {
                    Cancellation.Dispose();
                    Cancellation = null;

                    await Task.Delay(1500).ConfigureAwait(true);

                    ActivateLoading(false);
                }
            }
        }
        /// <summary>
        /// Convert the slides to images and update the layout
        /// </summary>
        private async Task Render()
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
            openPicker.FileTypeFilter.Add(".pptx");
            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file == null)
            {
                if (!_isWindowsPhone)
                {
                    TempThumbNailScrollViewer.Visibility = Visibility.Collapsed;
                    ThumbNailScrollViewer.Visibility     = Visibility.Visible;
                    MainViewImageGrid.Visibility         = Visibility.Visible;
                    loadingRing.IsActive   = false;
                    loadingRing.Visibility = Visibility.Collapsed;
                }
                return;
            }
            if (!_isWindowsPhone)
            {
                CancelRunningTask();
                _currentIndex = -1;
                ThumbNailScrollViewer.ChangeView(null, 1, null);
            }
            if (_isWindowsPhone)
            {
                ThumbNailScrollViewer.Visibility = Visibility.Collapsed;
                ThumbNailScrollViewer.ChangeView(null, 1, null);
                loadingRing.Visibility = Visibility.Visible;
                loadingRing.IsActive   = true;
            }
            Dispose();
            _isTaskRunning = true;
            //Open the presentation stream and retrieve it in the presentation instance.
            Stream pptxStream = file.OpenStreamForReadAsync().Result;

            TitleTextBlock.Text = file.Name;
            LoadPresentation(pptxStream);
            if (!_isWindowsPhone)
            {
                foreach (ISlide slide in _presentation.Slides)
                {
                    if (_cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    string filePath = await ConvertSlide(slide);

                    RowDefinition row = new RowDefinition();
                    ThumbnailGrid.RowDefinitions.Add(row);
                    if (_cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    if (_presentation.Slides[0].SlideNumber == 0)
                    {
                        UpdateThumbnailGrid(filePath, slide.SlideNumber + 1, _cancellationToken);
                    }
                    else
                    {
                        UpdateThumbnailGrid(filePath, slide.SlideNumber, _cancellationToken);
                    }
                    if ((_presentation.Slides.Count >= 5 && slide.SlideNumber == 5) || _presentation.Slides.Count < 5)
                    {
                        TempThumbNailScrollViewer.Visibility = Visibility.Collapsed;
                        ThumbNailScrollViewer.Visibility     = Visibility.Visible;
                        MainViewImageGrid.Visibility         = Visibility.Visible;
                        loadingRing.IsActive   = false;
                        loadingRing.Visibility = Visibility.Collapsed;
                    }
                }
            }
            else if (_isWindowsPhone)
            {
                if (_cancellationToken.IsCancellationRequested)
                {
                    return;
                }
                LoadingStatusCanvas.Visibility = Visibility.Collapsed;
                int renderedSlides = 0;
                for (int i = 0; i < _slideCount; i++)
                {
                    ISlide slide = _presentation.Slides[i];
                    if (_cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }
                    await ConvertSlide(slide);

                    renderedSlides++;
                    if (renderedSlides == 4 || slide.SlideNumber == _slideCount)
                    {
                        for (int j = slide.SlideNumber - (renderedSlides - 1); j <= slide.SlideNumber; j++)
                        {
                            await AddMobileThumbnailView(j);
                        }
                        renderedSlides = 0;
                    }
                    if ((_slideCount >= 4 && slide.SlideNumber == 4) || _slideCount < 4)
                    {
                        loadingRing.Visibility           = Visibility.Collapsed;
                        loadingRing.IsActive             = false;
                        ThumbNailScrollViewer.Visibility = Visibility.Visible;
                        LoadingStatusCanvas.Visibility   = Visibility.Visible;
                    }
                }
                LoadingStatusCanvas.Visibility = Visibility.Collapsed;
            }
            pptxStream.Dispose();
            _isTaskRunning = false;
        }
Пример #26
0
        private async void OnImport(object parameter)
        {
            DialogResult result       = DialogResult.None;
            bool         repeatResult = false;
            //if (EnsureUnsnapped())
            {
                FileOpenPicker fileDialog = new FileOpenPicker();
                fileDialog.CommitButtonText = "Import";
                fileDialog.FileTypeFilter.Add(".xml");

                var files = await fileDialog.PickMultipleFilesAsync();

                if (files != null)
                {
                    foreach (var file in files)
                    {
                        StorageFolder installedLocation = ApplicationData.Current.RoamingFolder;
                        if (!string.IsNullOrEmpty(SubFolder))
                        {
                            installedLocation = await installedLocation.GetFolderAsync(SubFolder);
                        }
                        bool        fileExist = false;
                        StorageFile newFile   = null;
                        var         fs        = await installedLocation.GetFilesAsync();

                        foreach (var f in fs)
                        {
                            if (f.Name == file.Name)
                            {
                                newFile   = f;
                                fileExist = true;
                            }
                        }
                        if (fileExist)
                        {
                            if (!repeatResult)
                            {
                                ReplaceFilesDialog replaceDialog = new ReplaceFilesDialog();
                                replaceDialog.FileName = " " + file.Name + ".xml";
                                result = await ShowDialog(replaceDialog);

                                repeatResult = replaceDialog.Repeat;
                            }
                            switch (result)
                            {
                            case DialogResult.Cancel:
                                return;

                            case DialogResult.No:
                                continue;

                            case DialogResult.Yes:
                                await file.CopyAndReplaceAsync(newFile);

                                break;
                            }
                        }
                        else
                        {
                            newFile = await file.CopyAsync(installedLocation, file.Name);

                            ObservableCollection <FileItem> items =
                                fileList.DataContext as ObservableCollection <FileItem>;
                            items.Add(new FileItem()
                            {
                                Name = newFile.DisplayName, Load = this.Load
                            });
                        }
                    }
                }
            }
        }
Пример #27
0
        private async void StartSingleFileUpload(FileOpenPicker picker, Uri uri)
        {
            StorageFile file = await picker.PickSingleFileAsync();

            UploadSingleFile(uri, file);
        }
Пример #28
0
        public async void AddPass()
        {
            FileOpenPicker filePicker = new FileOpenPicker();

            filePicker.FileTypeFilter.Add(".pkpass");
            StorageFile pkpassFile = await filePicker.PickSingleFileAsync();

            //If user hasn't closed the open dialog window
            if (pkpassFile != null)
            {
                ZipArchive pkpassFileStream = null;

                await Task.Run(() =>
                {
                    //Autorização para abrir arquivos de qualquer pasta
                    StorageApplicationPermissions.FutureAccessList.AddOrReplace("pkpass", pkpassFile);

                    //Open .pkpass file as a ZipArchive
                    pkpassFileStream = ZipFile.OpenRead(pkpassFile.Path);
                });

                //Checks if pass.json and manifest.json exists in .pkass, open and read
                if (pkpassFileStream.GetEntry("pass.json").Name == "pass.json" && pkpassFileStream.GetEntry("manifest.json").Name == "manifest.json")
                {
                    var passjsonFile     = pkpassFileStream.GetEntry("pass.json").Open();
                    var manifestjsonFile = pkpassFileStream.GetEntry("manifest.json").Open();

                    using (var reader = new StreamReader(passjsonFile))
                    {
                        passFile = JsonConvert.DeserializeObject(reader.ReadToEnd());

                        passjsonFile.Dispose();
                    }

                    using (var reader = new StreamReader(manifestjsonFile))
                    {
                        manifestFile = JsonConvert.DeserializeObject(reader.ReadToEnd());
                        passID       = manifestFile["pass.json"];

                        manifestjsonFile.Dispose();
                    }

                    //Checks if pass folder already exists (if pass was already added)
                    if (!Directory.Exists(localFolder.Path + "/" + passID))
                    {
                        //Creates pass folder and extract pass files there
                        await Task.Run(() =>
                        {
                            pkpassFileStream.ExtractToDirectory(localFolder.Path + "/" + passID);
                        });

                        //Reads the pass, write info in config.json and refresh the PassListView
                        InsertPass();
                        RefreshPassList();
                    }
                    else
                    {
                        //Error message
                        var dialog = new MessageDialog("Arquivo já adicionado.");
                        await dialog.ShowAsync();
                    }
                }
                else
                {
                    //Error message
                    var dialog = new MessageDialog("Arquivo corrompido ou incompatível. Por favor, entre em contato com o nosso suporte.");
                    await dialog.ShowAsync();
                }
            }
        }
        /// <summary>
        ///  ロック画面に設定するアイテムをFilePickerで選択して登録する.
        /// </summary>
        private async void PickAndAddItemsAsync()
        {
            var picker = new FileOpenPicker();

            picker.FileTypeFilter.Add(".png");
            picker.FileTypeFilter.Add(".jpg");
            picker.FileTypeFilter.Add(".jpeg");
            picker.FileTypeFilter.Add(".bmp");
            picker.ViewMode         = PickerViewMode.Thumbnail;
            picker.CommitButtonText = App.MyResource["FilePickerOpenCommitButtonText"];

            var files = await picker.PickMultipleFilesAsync();

            if (files == null)
            {
                return;
            }

            bool emptyBefore = App.Current.LockscreenItemList.IsEmpty;

            this.IsItemChanging = true;
            List <StorageFile> failedFiles = new List <StorageFile>();

            using (this.cancellationTokenSource = new System.Threading.CancellationTokenSource())
            {
                try
                {
                    foreach (var file in files)
                    {
                        // 画像ファイル以外を排除
                        var properties = await file.Properties.GetImagePropertiesAsync();

                        if ((properties.Width == 0) || (properties.Height == 0))
                        {
                            continue;
                        }

                        if (!await App.Current.AddFileAsync(file, false, this.cancellationTokenSource.Token))
                        {
                            failedFiles.Add(file);
                        }
                    }

                    if (failedFiles.Count != 0)
                    {
                        var msg = String.Format(App.MyResource["ErrorMessageAddFiles"], failedFiles.Count);
                        var dlg = new Windows.UI.Popups.MessageDialog(msg);
                        await dlg.ShowAsync();
                    }
                }
                catch (TaskCanceledException ex)
                {
                    // 知らないキャンセルはCrashさせる
                    if (ex.CancellationToken != this.cancellationTokenSource.Token)
                    {
                        throw;
                    }
                }
            }
            this.cancellationTokenSource = null;

            this.IsItemChanging = false;

            // empty -> not empty
            //   updatereg
            if (emptyBefore && !App.Current.LockscreenItemList.IsEmpty)
            {
                App.Current.UpdateBackgroundTaskRegistration();
            }
        }