// create or open local file private async void CreateOrOpenFile() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; sampleFile = await storageFolder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); }
public static async Task <Windows.Data.Xml.Dom.XmlDocument> LoadXmlFile(String folder, String file) { Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(folder); Windows.Storage.StorageFile storageFile = await storageFolder.GetFileAsync(file); Windows.Data.Xml.Dom.XmlLoadSettings loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings(); loadSettings.ProhibitDtd = false; loadSettings.ResolveExternals = false; return(await Windows.Data.Xml.Dom.XmlDocument.LoadFromFileAsync(storageFile, loadSettings)); }
private async void LoadTrades_Click(object sender, RoutedEventArgs e) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); var trademodels = await TradeProcessor.LoadTrades(); using (StreamWriter streamW = new StreamWriter(sampleFile.Path, true)) { streamW.WriteLine($"{DateTime.Now} Wczytano 300 tradow"); } Price.Text = $"Cena: {trademodels[0].R}"; Amoundof.Text = $"Ilosc: {trademodels[0].A}"; Time.Text = $"Czas: {trademodels[0].T}"; Type.Text = $"Typ: {trademodels[0].Ty}"; Id.Text = $"Id: {trademodels[0].Id}"; using (StreamWriter streamW = new StreamWriter(sampleFile.Path, true)) { streamW.WriteLine($"{DateTime.Now} Wyświetlono ostatni trade"); } var trades = new List <Trade>(); foreach (var trade in trademodels) { trades.Add(trade.ToTrade()); } TraderContext context = null; try { context = new TraderContext(); foreach (var trade in trades) { if (!context.Trades.Any(t => t.Tid == trade.Tid)) { context.Trades.Add(trade); using (StreamWriter streamW = new StreamWriter(sampleFile.Path, true)) { streamW.WriteLine($"{DateTime.Now} Dodano do bazy trade {trade}"); } } } context.SaveChanges(); } finally { if (context != null) { context.Dispose(); } } }
private async void initInfomation() { await DBmanager.ConnectDatabase(); Windows.Storage.StorageFolder storageFolder = Windows.Storage.KnownFolders.PicturesLibrary; Windows.Storage.StorageFile dataFile = await storageFolder.CreateFileAsync("dat.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); await Windows.Storage.FileIO.WriteTextAsync(dataFile, Windows.Storage.ApplicationData.Current.LocalFolder.Path); }
public async static Task <string> ReadFile(string file_name) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync(file_name); string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile); return(text); }
internal static async Task <WinStorageFile> GetFileAsync( StoragePath fullPath, CancellationToken cancellationToken ) { try { return(await WinStorageFile.GetFileFromPathAsync(fullPath).AsAwaitable(cancellationToken)); } catch (FileNotFoundException ex) { // FileNotFoundException might be thrown if the parent directory does not exist. // Specification requires DirectoryNotFoundException in such cases. // Some folder operations might call this method though. In such cases, we might not // have a parent path. In that case, just go with the FileNotFoundException. if (fullPath.Parent is null) { throw; } try { await WinStorageFolder.GetFolderFromPathAsync(fullPath.Parent).AsAwaitable(cancellationToken); } catch { // Getting the parent folder failed. throw new DirectoryNotFoundException(ExceptionStrings.StorageFile.ParentFolderDoesNotExist(), ex); } // At this point we know that the parent folder exists, but the file doesn't. // We can go with the FileNotFoundException. throw; } catch (ArgumentException ex) { // An ArgumentException might indicate that a conflicting folder exists at this location. // Try to get a folder. If that succeedes, we can be certain and throw the IOException // which is required by specification. try { await WinStorageFolder.GetFolderFromPathAsync(fullPath).AsAwaitable(cancellationToken); } catch { // Getting the folder failed too. Rethrow the ArgumentException from before. ExceptionDispatchInfo.Throw(ex); } // At this point, getting the folder succeeded. We must manually throw to fulfill the specification. throw new IOException(ExceptionStrings.StorageFile.ConflictingFolderExistsAtFileLocation(), ex); } }
public async void LoadMusic() { player = new MediaPlayer(); Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets"); Windows.Storage.StorageFile file = await folder.GetFileAsync("bg_music.mp3"); player.Source = MediaSource.CreateFromStorageFile(file); player.IsLoopingEnabled = true; player.Play(); }
// // // // //FAILS... /* * protected async static Task<StorageItemThumbnail> GetFileThumbnailAsync( StorageFile fle ) * { * StorageItemThumbnail tn = null; * * try * { * tn = await fle.GetThumbnailAsync( ThumbnailMode.SingleItem ); //.PicturesView ); * } * catch( System.IO.FileNotFoundException e ) * { * //NOT EXIST... * } * * return tn; * } */ protected async static Task <Windows.Storage.StorageFile> CreateFileAsync(Windows.Storage.StorageFolder fldr, string sFileName) { Windows.Storage.StorageFile fle = null; // // FAILS!!! - Not implemented. // fle = await fldr.CreateFileAsync(sFileName, Windows.Storage.CreationCollisionOption.FailIfExists); //CreationCollisionOption.ReplaceExisting); return(fle); }
LoadImageAsync(Windows.Storage.StorageFile file) { Windows.Storage.FileProperties.ImageProperties imgProp = await file.Properties.GetImagePropertiesAsync(); using (var imgStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { var bitmap = new Windows.UI.Xaml.Media.Imaging.WriteableBitmap((int)imgProp.Width, (int)imgProp.Height); bitmap.SetSource(imgStream); return(bitmap); } }
//reading name file to dashboard public async void ReadNameFileAsync() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile Name = await storageFolder.GetFileAsync("helloname.txt"); string name2 = await Windows.Storage.FileIO.ReadTextAsync(Name); helloLabel.Text = "Hello " + name2 + ","; }
protected override void PrepareWriter() { IAsyncOperation <Windows.Storage.StorageFile> task = Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("localStorage.log", Windows.Storage.CreationCollisionOption.GenerateUniqueName); Windows.Storage.StorageFile file = task.GetAwaiter().GetResult(); m_stream = file.OpenStreamForWriteAsync().Result; QuietWriter = new log4net.Util.QuietTextWriter(new StreamWriter(m_stream, Encoding.UTF8), ErrorHandler); WriteHeader(); }
private async void cargarMusikita() { Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets"); Windows.Storage.StorageFile file = await folder.GetFileAsync("cancion.mp3"); player.AutoPlay = false; player.Source = MediaSource.CreateFromStorageFile(file); player.Play(); player.Volume = 0.3; }
private async void PlayWinningMusic() { Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets"); Windows.Storage.StorageFile file = await folder.GetFileAsync("I can't believe you done this.mp3"); songPlayer.AutoPlay = false; songPlayer.Source = MediaSource.CreateFromStorageFile(file); songPlayer.Play(); }
private async void Reference_Click(object sender, RoutedEventArgs e) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Resources/merdog_grammar.txt")); this.Editor.Text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile); SetLineNo(Editor.Text); SFileName.Text = "参考手册"; }
public void SaveTokenToLocalStorage(string token) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = storageFolder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult(); Windows.Storage.FileIO.WriteTextAsync(sampleFile, token).GetAwaiter().GetResult(); }
public NoteFile() { this.InitializeComponent(); string contentFile = DateTime.Now.ToString("yyyy-MM-dd-hh-mm"); Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile tokenFile = storageFolder.CreateFileAsync(contentFile + ".txt", Windows.Storage.CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult(); Windows.Storage.FileIO.WriteTextAsync(tokenFile, contentFile).GetAwaiter().GetResult(); Debug.WriteLine(tokenFile.Path); }
public async Task <JsonArray> UploadChanges(Windows.Storage.StorageFile zip) { using (FileStream file = new FileStream(zip.Path, FileMode.Open, FileAccess.Read)) { // no compression, as we compress the zip file instead HttpResponseMessage resp = await Request("uploadChanges", file, 0); JsonObject jresp = JsonObject.Parse(await resp.Content.ReadAsStringAsync()); return(DataOnly(jresp, new JsonArray())); } }
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { if (this.name.Text == "" && this.description.Text == "" && this.thumbnail.Text == "" && this.link.Text == "") { this.checkErrorAll.Text = "Du lieu khong duoc bo trong"; } else if (this.name.Text == "") { this.checkErrorName.Text = "Ten khong duoc bo trong"; } else if (this.name.Text.Length >= 50) { this.checkErrorName.Text = "Ten khong duoc dai qua 50 ki tu"; } else if (Regex.IsMatch(this.link.Text, ".mp3$") == false) { this.checkerrorMp3.Text = "Link khong dung dinh dang"; } else if (this.thumbnail.Text == "") { Debug.WriteLine("Thumnail khong duoc de trong"); } else if (this.link.Text == "") { this.checkerrorMp3.Text = "Link khong duoc de trong"; } else { this.checkerrorMp3.Text = ""; this.checkErrorName.Text = ""; this.checkErrorAll.Text = ""; var song = new Song { name = this.name.Text, description = this.description.Text, singer = this.singer.Text, author = this.author.Text, thumbnail = this.thumbnail.Text, link = this.link.Text }; Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = storageFolder.GetFileAsync("sample.txt").GetAwaiter().GetResult(); var token = Windows.Storage.FileIO.ReadTextAsync(sampleFile).GetAwaiter().GetResult(); var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + token); HttpContent content = new StringContent(JsonConvert.SerializeObject(song), Encoding.UTF8, "application/json"); Task <HttpResponseMessage> httpRequestMessage = httpClient.PostAsync(ApiUrl, content); String responseContent = httpRequestMessage.Result.Content.ReadAsStringAsync().Result; Debug.WriteLine("Response: " + responseContent); } }
private async void getDBAddress() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile configFile = await storageFolder.GetFileAsync("config.txt"); string text = await Windows.Storage.FileIO.ReadTextAsync(configFile); dbAddress = text; System.Diagnostics.Debug.WriteLine(text); }
private async void buttonSave_ClickAsync(object sender, RoutedEventArgs e) { // // Get all strokes on the InkCanvas. IReadOnlyList <InkStroke> currentStrokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes(); if (currentStrokes.Count > 0) { // Use a file picker to identify ink file. Windows.Storage.Pickers.FileSavePicker savePicker = new Windows.Storage.Pickers.FileSavePicker(); savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; savePicker.FileTypeChoices.Add( "GIF with embedded ISF", new List <string>() { ".gif" }); savePicker.DefaultFileExtension = ".gif"; savePicker.SuggestedFileName = "InkSample"; // Show the file picker. Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync(); // When selected, picker returns a reference to the file. if (file != null) { // Prevent updates to the file until updates are // finalized with call to CompleteUpdatesAsync. Windows.Storage.CachedFileManager.DeferUpdates(file); // Open a file stream for writing. IRandomAccessStream stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); // Write the ink strokes to the output stream. using (IOutputStream outputStream = stream.GetOutputStreamAt(0)) { await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(outputStream); await outputStream.FlushAsync(); } stream.Dispose(); // Finalize write so other apps can update file. Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) { // File saved. } } } }
private async void Want_To_Click(object sender, RoutedEventArgs e) { Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets\Musics\\Dua Lipa"); Windows.Storage.StorageFile file = await folder.GetFileAsync("Want To.mp3"); SoundOfMusic.AutoPlay = false; SoundOfMusic.Source = MediaSource.CreateFromStorageFile(file); SoundOfMusic.Play(); }
private async void Club_Cant_Handle_Me_Click(object sender, RoutedEventArgs e) { Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets\Musics\Flo-Rida"); Windows.Storage.StorageFile file = await folder.GetFileAsync("Club Can't Handle Me.mp3"); SoundOfMusic.AutoPlay = false; SoundOfMusic.Source = MediaSource.CreateFromStorageFile(file); SoundOfMusic.Play(); }
private void Button_Click(object sender, RoutedEventArgs e) { var note = this.note.Text; var path = DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt"; Debug.WriteLine(path); Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = storageFolder.CreateFileAsync(path, Windows.Storage.CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult(); Windows.Storage.FileIO.WriteTextAsync(sampleFile, note).GetAwaiter().GetResult(); }
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting); NavigationService.Navigate(typeof(Views.MainPage)); await Task.CompletedTask; }
private async void Button_Click_3(object sender, RoutedEventArgs e) { this.Frame.Navigate(typeof(About)); Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets"); Windows.Storage.StorageFile file = await folder.GetFileAsync("soundEffect.mp3"); player.AutoPlay = false; player.Source = MediaSource.CreateFromStorageFile(file); player.Play(); }
public async Task <bool> CheckSubbedDifferenceByJSONAsync(List <Establishment> new_establishments) { string json = JsonConvert.SerializeObject(new_establishments.ToArray()); Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("subscribed.txt"); string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile); return(text.Equals(json)); }
private async void button_Click(object sender, RoutedEventArgs e) { Windows.Storage.StorageFile restFile = await storageFolder.CreateFileAsync(restrictionPath, Windows.Storage.CreationCollisionOption.OpenIfExists); Windows.Storage.StorageFile dispFile = await storageFolder.CreateFileAsync(displayPath, Windows.Storage.CreationCollisionOption.OpenIfExists); string restStream = filename_textbox.Text; string selected = comboBox.SelectedItem.ToString(); string displayStream = filename_textbox.Text; byte perm = 0; switch (selected) { case (noaccess): perm = 0; break; case (readOnly): perm = 1; break; case (writeOnly): perm = 5; break; case (completeAccess): perm = 7; break; default: perm = 0; break; } // :perm:filepath; restStream = ":" + perm + ":" + restStream + ";\r\n"; displayStream = "\"" + displayStream + "\"" + " => PERMISSION: " + selected; listbox.Items.Add(displayStream); displayStream += "\r\n"; System.Diagnostics.Debug.Write(restStream); await Windows.Storage.FileIO.AppendTextAsync(restFile, restStream); await Windows.Storage.FileIO.AppendTextAsync(dispFile, displayStream); listbox.Items.Add(displayStream); System.Diagnostics.Debug.Write(foo(5)); }
//---------------------------- Music Functions --------------------------- private async void PlayLosingMusic() { Windows.Storage.StorageFolder folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync(@"Assets"); Windows.Storage.StorageFile file = await folder.GetFileAsync("Price is Right Losing Horn.mp3"); songPlayer.AutoPlay = false; songPlayer.Source = MediaSource.CreateFromStorageFile(file); songPlayer.Play(); }
private async void FileWrite_Default(Windows.Storage.StorageFolder storageFolder) { // Un Recommanded //Windows.Storage.StorageFolder storageFolder = // Windows.Storage.ApplicationData.Current.LocalFolder; //Windows.Storage.StorageFolder storageFolder = // Windows.ApplicationModel.Package.Current.InstalledLocation; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("DefaultWrite.txt"); await Windows.Storage.FileIO.WriteTextAsync(sampleFile, "DefaultWrite"); }
/// <summary> /// 将文件转换为字节数组 /// </summary> /// <param name="file"></param> /// <returns></returns> public static async Task <byte[]> AsByteArray(this Windows.Storage.StorageFile file) { Windows.Storage.Streams.IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read); var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0)); await reader.LoadAsync((uint)fileStream.Size); byte[] pixels = new byte[fileStream.Size]; reader.ReadBytes(pixels); return(pixels); }
//writing todo to file private async void WriteFile() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile PlannerStore = await storageFolder.CreateFileAsync("PlannerStore.txt", Windows.Storage.CreationCollisionOption.OpenIfExists); await Windows.Storage.FileIO.AppendTextAsync(PlannerStore, addToDoBox.Text + "\n"); }
internal async void startButton_Click(object sender, RoutedEventArgs e) { try { await initializeCamera(); string PHOTO_FILE_NAME = string.Format("img-{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg", DateTime.Now); m_photoStorageFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(PHOTO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg(); await m_mediaCaptureMgr.CapturePhotoToStorageFileAsync(imageProperties, m_photoStorageFile); if (debug) statusListBox.Items.Add(PHOTO_FILE_NAME + " saved"); } catch (Exception exception) { if (debug) statusListBox.Items.Add("error occurred"); } }
public async void OpenFileClick(object sender, RoutedEventArgs e) { var filePicker = new Windows.Storage.Pickers.FileOpenPicker(); filePicker.FileTypeFilter.Add(".txt"); filePicker.FileTypeFilter.Add(".doc"); fileToUse = await filePicker.PickSingleFileAsync(); if (fileToUse != null) { try { var text = await Windows.Storage.FileIO.ReadTextAsync(fileToUse); FileContents.Text = text; } catch (Exception) { new Windows.UI.Popups.MessageDialog("Something went wrong").ShowAsync(); } } }
/// <summary> /// Creates an instance of pkpassHelpers. /// </summary> /// <param name="file">The .pkpass file to be processed.</param> public pkpassHelpers(Windows.Storage.StorageFile file) { sourceFile = file; }
internal StorageFile(Windows.Storage.StorageFile file) { _file = file; }
async private Task captureImage() { try { //initialize the camera await initializeCamera(); //capture the image string PHOTO_FILE_NAME = string.Format("img-{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg", DateTime.Now); m_photoStorageFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(PHOTO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg(); await m_mediaCaptureMgr.CapturePhotoToStorageFileAsync(imageProperties, m_photoStorageFile); //write to the status box statusListBox.Invoke(new MethodInvoker(() => statusListBox.Items.Add(PHOTO_FILE_NAME + " saved"))); } catch (Exception exception) { if (debug) statusListBox.Items.Add(exception); else statusListBox.Invoke(new MethodInvoker(() => statusListBox.Items.Add("Error capturing image..."))); } }
private async void StartRecord() { try { ShowStatusMessage("Starting Record"); String fileName; fileName = VIDEO_FILE_NAME; m_recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create record file successful"); MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto); await m_mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, m_recordStorageFile); m_bRecording = true; btnStartStopRecord1.IsEnabled = true; btnStartStopRecord1.Content = "StopRecord"; ShowStatusMessage("Start Record successful"); } catch (Exception exception) { ShowExceptionMessage(exception); } }
internal async void btnTakePhoto_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) { try { ShowStatusMessage("Taking photo"); btnTakePhoto1.IsEnabled = false; if (!m_mediaCaptureMgr.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported) { //if camera does not support record and Takephoto at the same time //disable Record button when taking photo btnStartStopRecord1.IsEnabled = false; } m_photoStorageFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(PHOTO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create photo file successful"); ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg(); await m_mediaCaptureMgr.CapturePhotoToStorageFileAsync(imageProperties, m_photoStorageFile); btnTakePhoto1.IsEnabled = true; ShowStatusMessage("Photo taken"); if (!m_mediaCaptureMgr.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported) { //if camera does not support record and Takephoto at the same time //enable Record button after taking photo btnStartStopRecord1.IsEnabled = true; } var photoStream = await m_photoStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); ShowStatusMessage("File open successful"); var bmpimg = new BitmapImage(); bmpimg.SetSource(photoStream); imageElement1.Source = bmpimg; ShowStatusMessage(this.m_photoStorageFile.Path); } catch (Exception exception) { ShowExceptionMessage(exception); btnTakePhoto1.IsEnabled = true; } }
private async void btnSaveToFile_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) { try { m_selectedIndex = ThumbnailGrid.SelectedIndex; if (m_selectedIndex > -1) { m_photoStorageFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(PHOTOSEQ_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName); if (null == m_photoStorageFile) rootPage.NotifyUser("PhotoFile creation fails", NotifyType.ErrorMessage); var OutStream = await m_photoStorageFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite); if (null == OutStream) rootPage.NotifyUser("PhotoStream creation fails", NotifyType.ErrorMessage); var ContentStream = m_framePtr[m_selectedIndex].CloneStream(); await Windows.Storage.Streams.RandomAccessStream.CopyAndCloseAsync(ContentStream.GetInputStreamAt(0), OutStream.GetOutputStreamAt(0)); ShowStatusMessage("Photo save complete"); } else { rootPage.NotifyUser("Please select a photo to display", NotifyType.ErrorMessage); } } catch (Exception exception) { ShowExceptionMessage(exception); } }
internal async void btnStartStopRecord_Click(Object sender, Windows.UI.Xaml.RoutedEventArgs e) { try { String fileName; EnableButton(false, "StartStopRecord"); if (!m_bRecording) { ShowStatusMessage("Starting Record"); fileName = AUDIO_FILE_NAME; m_recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create record file successful"); MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateM4a(Windows.Media.MediaProperties.AudioEncodingQuality.Auto); await m_mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, this.m_recordStorageFile); m_bRecording = true; SwitchRecordButtonContent(); EnableButton(true, "StartStopRecord"); ShowStatusMessage("Start Record successful"); } else { ShowStatusMessage("Stopping Record"); await m_mediaCaptureMgr.StopRecordAsync(); m_bRecording = false; EnableButton(true, "StartStopRecord"); SwitchRecordButtonContent(); ShowStatusMessage("Stop record successful"); if (!m_bSuspended) { var stream = await m_recordStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); ShowStatusMessage("Record file opened"); ShowStatusMessage(this.m_recordStorageFile.Path); playbackElement3.AutoPlay = true; playbackElement3.SetSource(stream, this.m_recordStorageFile.FileType); playbackElement3.Play(); } } } catch (Exception exception) { EnableButton(true, "StartStopRecord"); ShowExceptionMessage(exception); m_bRecording = false; } }
private async Task StartRecord() { try { //StartPreview(); ShowStatusMessage("Starting Record"); videoStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(VIDEO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create record file successful"); MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto); await mediaCaptureMgr.StartRecordToStorageFileAsync(recordProfile, videoStorageFile); //m_bRecording = true; ShowStatusMessage("Start Record successful"); } catch (Exception exception) { ShowExceptionMessage(exception); } }
private async Task OpenControlsFile() { var descr = new FileOpenPicker(); descr.FileTypeFilter.Add(".utpcontrol"); controlFileDescr = await descr.PickSingleFileAsync(); }
public LocalImageFileInfo (Windows.Storage.StorageFile file) { storageFile = file; loadImage(); }
internal async void radRecord_Checked(Object sender, Windows.UI.Xaml.RoutedEventArgs e) { try { if (!m_bRecording) { //if camera does not support lowlag record and lowlag photo at the same time //disable all buttons while preparing lowlag record btnTakePhoto2.IsEnabled = false; btnStartStopRecord2.IsEnabled = false; //uncheck TakePhoto Mode radTakePhoto.IsChecked = false; //disable check option while preparing lowlag record radTakePhoto.IsEnabled = false; radRecord.IsEnabled = false; if (m_bLowLagPrepared) { //if camera does not support lowlag record and lowlag photo at the same time //but lowlag photo is already prepared, un-prepare lowlag photo first, before preparing lowlag record await m_lowLagPhoto.FinishAsync(); m_bLowLagPrepared = false; //prepare lowlag record PrepareForVideoRecording(); m_recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(VIDEO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create record file successful"); MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto); m_lowLagRecord = await m_mediaCaptureMgr.PrepareLowLagRecordToStorageFileAsync(recordProfile, m_recordStorageFile); btnStartStopRecord2.IsEnabled = true; m_bRecording = true; btnStartStopRecord2.Content = "StartRecord"; //re-enable check option, after lowlag record finish preparing radTakePhoto.IsEnabled = true; radRecord.IsEnabled = true; } else //(!m_bLowLagPrepared) { //if camera does not support lowlag record and lowlag photo at the same time //lowlag photo is not prepared, go ahead to prepare lowlag record PrepareForVideoRecording(); m_recordStorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(VIDEO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create record file successful"); MediaEncodingProfile recordProfile = null; recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto); m_lowLagRecord = await m_mediaCaptureMgr.PrepareLowLagRecordToStorageFileAsync(recordProfile, m_recordStorageFile); btnStartStopRecord2.IsEnabled = true; m_bRecording = true; btnStartStopRecord2.Content = "StartRecord"; //re-enable check option, after lowlag record finish preparing radTakePhoto.IsEnabled = true; radRecord.IsEnabled = true; } } } catch (Exception exception) { ShowExceptionMessage(exception); } }
private async void loadFile(string fileType) // Opens the file picker to let the user chose a todo or done file. // Stores the choice in the app's settings store. { Windows.Storage.Pickers.FileOpenPicker openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; openPicker.FileTypeFilter.Add(".txt"); switch (fileType) { case "todo": todoFile = await openPicker.PickSingleFileAsync(); try { if (todoFile != null) { todoFileToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(todoFile, todoFile.Name); localSettings.Values["todoFileToken"] = todoFileToken; updateTodoFile(); } } catch (FileNotFoundException) { //filenotefound } break; case "done": doneFile = await openPicker.PickSingleFileAsync(); doneFileToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(doneFile, doneFile.Name); localSettings.Values["doneFileToken"] = doneFileToken; break; } }
private async void loadFileFromToken(string fileType) // Tries to open a todo or done file from a token previously stored in the settings store. { bool done = false; switch (fileType) { case "todo": try { todoFile = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(todoFileToken); done = true; } catch (FileNotFoundException) { Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog("todo.txt file not found. Specify a new one in the Settings.", "todo.txt file not found"); dialog.ShowAsync(); } if (done) { updateTodoFile(); } break; case "done": try { doneFile = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(doneFileToken); done = true; } catch (FileNotFoundException) { Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog("done.txt file not found. Specify a new one in the Settings.", "done.txt file not found"); dialog.ShowAsync(); } break; } }
//private async Task<bool> generatePass (JObject o) //{ // //do stuff // if (card != null) // { // //await Task.Run(() => { txtInfo.Text = "Creating .mswallet file..."; }); // var passType = ""; // switch (card.Kind.ToString()) // { // case "BoardingPass": passType = "boardingPass"; break; // case "Deal": passType = "coupon"; break; // case "Ticket": passType = "eventTicket"; break; // case "MembershipCard": passType = "storeCard"; break; // default: passType = "generic"; break; // } // try // { // card.BodyColor = HelperMethods.getColorFromRGBString(o["backgroundColor"].Value<string>()); // card.BodyFontColor = HelperMethods.getColorFromRGBString(o["foregroundColor"].Value<string>()); // card.HeaderColor = card.BodyColor; // card.HeaderFontColor = HelperMethods.getColorFromRGBString(o["labelColor"].Value<string>()); // card.IssuerDisplayName = o["organizationName"].Value<string>(); // IReadOnlyList<Windows.Storage.StorageFile> files = await Windows.Storage.ApplicationData.Current.TemporaryFolder.GetFilesAsync(); // //txtInfo.Text = "Loading image files..."; // card.Logo99x99 = files.Where(x => x.Name == "icon.png").First(); // card.Logo159x159 = card.Logo336x336 = card.Logo99x99; // card.HeaderBackgroundImage = files.Where(x => x.Name == "logo.png").First(); // try // { // card.BodyBackgroundImage = files.Where(x => x.Name == "background.png").First(); // } // catch (Exception) { txtInfo.Text = "No background image found!"; }; // int i = 0; // //Primary Fields // if (o[passType]["primaryFields"] != null) // { // foreach (JObject jo in o[passType]["primaryFields"]) // { // WalletItemCustomProperty prop = new WalletItemCustomProperty(jo["label"].Value<string>(), jo["value"].Value<string>()); // if (i == 0) prop.DetailViewPosition = WalletDetailViewPosition.PrimaryField1; // else if (i == 1) prop.DetailViewPosition = WalletDetailViewPosition.PrimaryField2; // else throw new InvalidDataException(); // card.DisplayProperties[jo["key"].Value<string>()] = prop; // i++; // } // } // //Secondary fields // i = 0; // if (o[passType]["secondaryFields"] != null) // { // foreach (JObject jo in o[passType]["secondaryFields"]) // { // WalletItemCustomProperty prop = new WalletItemCustomProperty(jo["label"].Value<string>(), jo["value"].Value<string>()); // if (i == 0) prop.DetailViewPosition = WalletDetailViewPosition.SecondaryField1; // else if (i == 1) prop.DetailViewPosition = WalletDetailViewPosition.SecondaryField2; // else if (i == 2) prop.DetailViewPosition = WalletDetailViewPosition.SecondaryField3; // else if (i == 3) prop.DetailViewPosition = WalletDetailViewPosition.SecondaryField4; // else if (i == 4) prop.DetailViewPosition = WalletDetailViewPosition.SecondaryField5; // else throw new InvalidDataException(); // card.DisplayProperties[jo["key"].Value<string>()] = prop; // i++; // } // } // //Auxiliary fields // i = 0; // if (o[passType]["auxiliaryFields"] != null) // { // foreach (JObject jo in o[passType]["auxiliaryFields"]) // { // WalletItemCustomProperty prop = new WalletItemCustomProperty(jo["label"].Value<string>(), jo["value"].Value<string>()); // if (i == 0) prop.DetailViewPosition = WalletDetailViewPosition.FooterField1; // else if (i == 1) prop.DetailViewPosition = WalletDetailViewPosition.FooterField2; // else if (i == 2) prop.DetailViewPosition = WalletDetailViewPosition.FooterField3; // else if (i == 3) prop.DetailViewPosition = WalletDetailViewPosition.FooterField4; // else throw new InvalidDataException(); // card.DisplayProperties[jo["key"].Value<string>()] = prop; // i++; // } // } // //Header fields // i = 0; // if (o[passType]["headerFields"] != null) // { // foreach (JObject jo in o[passType]["headerFields"]) // { // WalletItemCustomProperty prop = new WalletItemCustomProperty(jo["label"].Value<string>(), jo["value"].Value<string>()); // if (i == 0) prop.DetailViewPosition = WalletDetailViewPosition.HeaderField1; // else if (i == 1) prop.DetailViewPosition = WalletDetailViewPosition.HeaderField2; // else throw new InvalidDataException(); // card.DisplayProperties[jo["key"].Value<string>()] = prop; // i++; // } // } // //Header fields // if (o[passType]["backFields"] != null) // { // foreach (JObject jo in o[passType]["backFields"]) // { // WalletItemCustomProperty prop = new WalletItemCustomProperty(jo["label"].Value<string>(), jo["value"].Value<string>()); // prop.SummaryViewPosition = WalletSummaryViewPosition.Hidden; // card.DisplayProperties[jo["key"].Value<string>()] = prop; // } // } // if (o["barcode"] != null) // { // WalletBarcodeSymbology sym = new WalletBarcodeSymbology(); // switch (o["barcode"]["format"].Value<string>()) // { // case "PKBarcodeFormatQR": sym = WalletBarcodeSymbology.Qr; break; // case "PKBarcodeFormatPDF417": sym = WalletBarcodeSymbology.Pdf417; break; // case "PKBarcodeFormatAztec": sym = WalletBarcodeSymbology.Aztec; break; // default: throw new InvalidDataException(); // } // card.Barcode = new WalletBarcode(sym, o["barcode"]["message"].Value<string>()); // } // if (o["locations"] != null) // { // i = 0; // foreach (JObject jo in o["locations"]) // { // WalletRelevantLocation location = new WalletRelevantLocation(); // location.DisplayMessage = jo["relevantText"].Value<string>(); // var position = new Windows.Devices.Geolocation.BasicGeoposition(); // position.Latitude = jo["latitude"].Value<double>(); // position.Longitude = jo["longitude"].Value<double>(); // try { // position.Altitude = jo["altitude"].Value<double>(); // } // catch(Exception) // { // System.Diagnostics.Debug.WriteLine("An altitude does not exist for location " + location.DisplayMessage); // } // location.Position = position; // //Check one doesn't already exist. // if (card.RelevantLocations.Where(x => x.Key == i.ToString()) != null) // i++; // else // card.RelevantLocations.Add(i.ToString(), location); // i++; // } // } // if (o["relevantDate"] != null) // { // card.RelevantDate = DateTime.Parse(o["relevantDate"].Value<string>()); // } // if (o["expirationDate"] != null) // { // card.ExpirationDate = DateTime.Parse(o["expirationDate"].Value<string>()); // } // return true; // } // catch (Exception) // { // card = null; // return false; // } // } // else return false; //} /// <summary> /// This is the method that will process the pkpass file. /// </summary> /// <param name="file"></param> //private async Task<bool> processPass(Windows.Storage.StorageFile file) //{ // bool success = false; // txtInfo.Text = "Preparing for processing..."; // Windows.Storage.StorageFolder folder = Windows.Storage.ApplicationData.Current.TemporaryFolder; // txtInfo.Text = "Extracting the .PKPASS file..."; // //ZipFile.ExtractToDirectory(file.Path.ToString(), folder.Path.ToString()); // await Task.Run(() => { ZipFile.ExtractToDirectory(file.Path.ToString(), folder.Path.ToString()); }); // IReadOnlyList<Windows.Storage.StorageFile> files = await Windows.Storage.ApplicationData.Current.TemporaryFolder.GetFilesAsync(); // txtInfo.Text = "Reading pass.json..."; // using (StreamReader reader = File.OpenText(files.Where(x => x.Name == "pass.json").First().Path.ToString())) // { // JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader)); // if(o["boardingPass"]!= null) // { // card = new WalletItem(WalletItemKind.BoardingPass, o["description"].Value<string>()); // } // else if (o["coupon"] != null) // { // card = new WalletItem(WalletItemKind.Deal, o["description"].Value<string>()); // } // else if (o["eventTicket"] != null) // { // card = new WalletItem(WalletItemKind.Ticket, o["description"].Value<string>()); // } // else if (o["storeCard"] != null) // { // card = new WalletItem(WalletItemKind.MembershipCard, o["description"].Value<string>()); // } // else if (o["generic"] != null) // { // card = new WalletItem(WalletItemKind.General, o["description"].Value<string>()); // } // success = await generatePass(o); // if(!success) // { // MessageDialog msgbox = new MessageDialog("Invalid pass.json.", "Error"); // await msgbox.ShowAsync(); // progRing.IsActive = false; // btnCancel.Visibility = Visibility.Collapsed; // success = false; // } // else // { // WalletItemStore wallet = await WalletManager.RequestStoreAsync(); // txtInfo.Text = "Saving to wallet..."; // string cardId = o["serialNumber"].Value<string>(); // if (await wallet.GetWalletItemAsync(cardId) != null) // { // MessageDialog msgbox = new MessageDialog("Would you like to overwrite this item?", "An item with the same ID exists!"); // UICommand uiYes = new UICommand("Yes"); // UICommand uiNo = new UICommand("No"); // msgbox.Commands.Add(uiYes); // msgbox.Commands.Add(uiNo); // msgbox.DefaultCommandIndex = 0; // msgbox.CancelCommandIndex = 1; // if (await msgbox.ShowAsync() == uiYes) // { // try // { // await wallet.DeleteAsync(cardId); // await wallet.AddAsync(cardId, card); // success = true; // txtInfo.Text = "Saved! Press the button below to return to the home screen."; // } // catch (Exception) // { // success = false; // txtInfo.Text = "There was a problem saving the card to the wallet."; // } // } // else // { // success = false; // txtInfo.Text = "You cancelled the creation."; // } // } // else // { // await wallet.AddAsync(cardId, card); // txtInfo.Text = "Saved! Press the button below to return to the home screen."; // } // btnReturn.Visibility = Visibility.Visible; // progRing.IsActive = false; // btnCancel.Visibility = Visibility.Collapsed; // HelperMethods.clearTempFiles(); // if (success) // await wallet.ShowAsync(cardId); // } // } // return success; //} protected async override void OnNavigatedTo(NavigationEventArgs e) { if (e.Parameter is string) { //paramPass = (e.Parameter as Windows.Storage.StorageFile); if ((e.Parameter as String) == "fileToken") { paramPass = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync("passFileToken"); HelperMethods.clearTempFiles(); } else this.Frame.GoBack(); } }
internal async void SurfaceTapped(object sender, TappedRoutedEventArgs e) { try { ShowStatusMessage("Taking photo"); if (!mediaCaptureMgr.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported) { //if camera does not support record and Takephoto at the same time //disable Record button when taking photo } photoStorageFile = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(PHOTO_FILE_NAME, Windows.Storage.CreationCollisionOption.GenerateUniqueName); ShowStatusMessage("Create photo file successful"); ImageEncodingProperties imageProperties = ImageEncodingProperties.CreateJpeg(); await mediaCaptureMgr.CapturePhotoToStorageFileAsync(imageProperties, photoStorageFile); ShowStatusMessage("Photo taken"); //if (!mediaCaptureMgr.MediaCaptureSettings.ConcurrentRecordAndPhotoSupported) //{ // //if camera does not support record and Takephoto at the same time // //enable Record button after taking photo // btnStartStopRecord1.IsEnabled = true; //} //var photoStream = await photoStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); //ShowStatusMessage("File open successful"); //WriteableBitmap bmpimg; //bmpimg.SetSource(photoStream); //videoSurface.Source = bmpimg;//videoSurface should be replaced with image //ShowStatusMessage("Photo Loaded!"); //photoClean.Interval = new TimeSpan(0, 0, 2); //photoClean.Start(); //photoClean.Tick += RestorePreview; ShowStatusMessage(photoStorageFile.Path); } catch (Exception exception) { ShowExceptionMessage(exception); } }