async void ProcessPhotoAsync() { #if !UNITY_EDITOR Windows.Storage.StorageFolder storageFolder = Windows.Storage.KnownFolders.CameraRoll; Windows.Storage.StorageFile file = await storageFolder.GetFileAsync("terminator_analysis.jpg"); if (file != null) { Debug.Log("File exists!!"); } else { Debug.Log("File does not exists!!"); } //convert filestream to byte array byte[] fileBytes; using (var fileStream = await file.OpenStreamForReadAsync()) { var binaryReader = new BinaryReader(fileStream); fileBytes = binaryReader.ReadBytes((int)fileStream.Length); } HttpClient client = new HttpClient(); //Ip Address of the server running face recognition service client.BaseAddress = new Uri("http://192.168.137.1:5000/"); MultipartFormDataContent form = new MultipartFormDataContent(); HttpContent content = new StringContent("file"); form.Add(content, "file"); var stream = await file.OpenStreamForReadAsync(); content = new StreamContent(stream); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = file.Name }; form.Add(content); String face = null; try { var response = await client.PostAsync("facerec", form); face = response.Content.ReadAsStringAsync().Result; Debug.Log(response.Content.ReadAsStringAsync().Result); Hello.text = response.Content.ReadAsStringAsync().Result; } catch (Exception e) { Debug.Log(e); } //Hello.text = face; #endif }
private async void HyperlinkButton_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { try { string uri = file.Path; base64img = "data:" + file.ContentType + ";base64,"; // var tempfile = await RescaleImage(file, 128, 128); base64img += Convert.ToBase64String(await filetobytes(file)); BitmapImage img = new BitmapImage(); GuildIconRect.Opacity = 0; using (var fileStream = await file.OpenStreamForReadAsync()) { await img.SetSourceAsync(fileStream.AsRandomAccessStream()); } GuildIcon.ImageSource = img; GuildIconRect.Fade(1, 300).Start(); deleteImage.Content = App.GetString("/Dialogs/CancelIconMod"); deleteImage.Visibility = Visibility.Visible; } catch { } } }
async public static Task UnZipFile(StorageFile file, StorageFolder extractFolder = null) { using (var zipStream = await file.OpenStreamForReadAsync()) { using (MemoryStream zipMemoryStream = new MemoryStream((int)zipStream.Length)) { await zipStream.CopyToAsync(zipMemoryStream); using (var archive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Read)) { foreach (ZipArchiveEntry entry in archive.Entries) { if (entry.Name != "") { using (Stream fileData = entry.Open()) { StorageFile outputFile = await extractFolder.CreateFileAsync(entry.Name, CreationCollisionOption.ReplaceExisting); using (Stream outputFileStream = await outputFile.OpenStreamForWriteAsync()) { await fileData.CopyToAsync(outputFileStream); await outputFileStream.FlushAsync(); } } } } } } } }
private async Task <Emotion[]> GetEmotions() { try { Emotion[] emotionResult; Windows.Storage.StorageFile file = await KnownFolders.PicturesLibrary.GetFileAsync(pictureName); if (file != null) { // Open a stream for the selected file. // The 'using' block ensures the stream is disposed // after the image is loaded. using (Stream fileStream = await file.OpenStreamForReadAsync()) { emotionResult = await emotionServiceClient.RecognizeAsync(fileStream); return(emotionResult); } } else { return(null); } } catch (Exception ex) { SolidColorBrush brush = new SolidColorBrush(Windows.UI.Colors.Red); Status.Foreground = brush; Status.Text = "Error reading Emotion : " + ex.Message; return(null); } }
public static async Task UnzipFromStorage(StorageFile pSource, StorageFolder pDestinationFolder, IEnumerable<string> pIgnore) { using (var stream = await pSource.OpenStreamForReadAsync()) { await UnzipFromStream(stream, pDestinationFolder,pIgnore.ToList()); } }
private static async Task <List <InkSample> > ReadInCSVData() { List <InkSample> records = new List <InkSample>(); StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation; StorageFolder assetsFolder = await StorageFolder.GetFolderFromPathAsync( Windows.ApplicationModel.Package.Current.InstalledLocation.Path + @"\Assets"); Windows.Storage.StorageFile sampleFile = await assetsFolder.GetFileAsync("RandomEnglishInkSamples_2018_07_01.csv"); var stream = await sampleFile.OpenStreamForReadAsync(); using (TextReader fileReader = new StreamReader(stream)) { List <ICsvLine> rows = CsvReader.Read(fileReader).ToList(); foreach (var row in rows) { if (row.ColumnCount < 3) { continue; } records.Add(new InkSample(row[0], row[1], row[2])); } return(records); } }
public static async Task<string> UploadImageToBlobStorage(StorageFile image, string targetUrl) { //Upload image with HttpClient to the blob service using the generated item.SAS // TODO - add BusyDisposer using (new BusyDisposer()) using (var client = new HttpClient()) { //Get a stream of the media just captured using (var fileStream = await image.OpenStreamForReadAsync()) { var content = new StreamContent(fileStream); content.Headers.Add("Content-Type", image.ContentType); content.Headers.Add("x-ms-blob-type", "BlockBlob"); using (var uploadResponse = await client.PutAsync(new Uri(targetUrl), content)) { if (uploadResponse.StatusCode != HttpStatusCode.Created) { throw new Exception(string.Format("Upload Failed {0}", uploadResponse.ToString())); } // remove the SAS querystring from the insert result return targetUrl.Substring(0, targetUrl.IndexOf('?')); } } } }
private async Task <FaceRectangle[]> UploadAndDetectFaces(string imageFilePath) { try { Windows.Storage.StorageFile file = await KnownFolders.PicturesLibrary.GetFileAsync(imageFilePath); if (file != null) { // Open a stream for the selected file. // The 'using' block ensures the stream is disposed // after the image is loaded. using (Stream fileStream = await file.OpenStreamForReadAsync()) { var faces = await faceServiceClient.DetectAsync(fileStream); var faceRects = faces.Select(face => face.FaceRectangle); return(faceRects.ToArray()); } } else { return(new FaceRectangle[0]); } } catch (Exception ex) { SolidColorBrush brush = new SolidColorBrush(Windows.UI.Colors.Red); Status.Foreground = brush; Status.Text = "Error Loading picture : " + ex.Message; return(null); } }
public async Task<FavoriteRoute> LoadFromFile(StorageFile file) { var serializer = new XmlSerializer(typeof(gpxType)); Stream stream = await file.OpenStreamForReadAsync(); gpxType objectFromXml = (gpxType)serializer.Deserialize(stream); stream.Dispose(); Name = (objectFromXml.metadata.name == null) ? "" : objectFromXml.metadata.name; Description = (objectFromXml.metadata.desc == null) ? "" : objectFromXml.metadata.desc; Timestamp = (objectFromXml.metadata.time == null) ? DateTime.Now : objectFromXml.metadata.time; Symbol = (objectFromXml.metadata.extensions.symbol == null) ? "" : objectFromXml.metadata.extensions.symbol; /*Address = (objectFromXml.metadata.extensions.address == null) ? "" : objectFromXml.metadata.extensions.address;*/ StartPoint = new BasicLocation() { Location = new Geopoint(new BasicGeoposition() { Latitude = (double)objectFromXml.wpt[0].lat, Longitude = (double)objectFromXml.wpt[0].lon, Altitude = (double)objectFromXml.wpt[0].ele }) }; Track = objectFromXml.trk[0].trkseg[0].trkpt.Select(pos => new BasicGeoposition() { Latitude = (double)pos.lat, Longitude = (double)pos.lon, Altitude = (double)pos.ele }).ToList(); return this; }
/// <summary> /// Deserialises the XML file contents and loads the instance of the Im-Memory Context /// It is called from the <see cref="Infrastructure.Repositories.PersistenceRepository"/>. /// </summary> /// <param name="UnitOfWork">The instance of the Music Collection being loaded</param> /// <param name="datafile">The instance of the XML source file.</param> /// <returns>A Task so that the call can be awaited.</returns> /// <remarks> /// The UnitOfWork which represents the Music Collection is passed by reference so updats /// reflect in the supplied instance. This instance is injected by the IoC container /// therefore no new instances of it should be created. /// </remarks> public static async Task Deserialise(IUnitOfWork UnitOfWork, StorageFile datafile) { // Deserialise the data from the file. using (StreamReader reader = new StreamReader(await datafile.OpenStreamForReadAsync())) { // Check for an empty stream, exceptions will occur if it is. if (!reader.EndOfStream) { // Set up the types for deserialising Type[] extraTypes = new Type[11]; extraTypes[0] = typeof(List<Album>); extraTypes[1] = typeof(List<Track>); extraTypes[2] = typeof(List<Artist>); extraTypes[3] = typeof(List<Genre>); extraTypes[4] = typeof(List<PlayList>); extraTypes[5] = typeof(Track); extraTypes[6] = typeof(Artist); extraTypes[7] = typeof(Genre); extraTypes[8] = typeof(PlayList); extraTypes[9] = typeof(Wiki); extraTypes[10] = typeof(Image); // Create the XMLSerialiser instance XmlSerializer serializer = new XmlSerializer(typeof(List<Album>), extraTypes); // Deserialise the Albums collection, that's the only collection persisted as // it contains the complete object graph. UnitOfWork.Albums = (List<Album>)serializer.Deserialize(reader); } } }
public static async Task <List <string> > getCollectionAsync() { if (collection.Any()) { return(collection); } var roamingFolder = Windows.Storage.ApplicationData.Current.RoamingFolder; // Create the file in the local folder, or if it already exists, just open it Windows.Storage.StorageFile collectionFile = await roamingFolder.CreateFileAsync("Collected.txt", CreationCollisionOption.OpenIfExists); Stream collectionStream = await collectionFile.OpenStreamForReadAsync(); using (StreamReader reader = new StreamReader(collectionStream)) { string collectedCommand; while ((collectedCommand = reader.ReadLine()) != null) { collection.Add(collectedCommand); // Add to list. } } return(collection); }
public static async void InitLoadSet() { string fileContent; Uri uri = new Uri("ms-appx:///Data/Sets.txt"); file = await StorageFile.GetFileFromApplicationUriAsync(uri); StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync()); fileContent = await sRead.ReadLineAsync(); KeyValuePair<int, object> res = Type(fileContent); ListWords currentListWords = new ListWords(); while (res.Key != -1) { if (res.Key == 0) { currentListWords.Name = (string)res.Value; SetsNames.Add((string)res.Value); } if (res.Key == 1) { currentListWords.Add((Word)res.Value); } if (res.Key == 2) { SetsWords.Add(currentListWords.Name, currentListWords); currentListWords = new ListWords(); } fileContent = sRead.ReadLineAsync().Result; res = Type(fileContent); } MainPage.CurrentListWords = SetsWords["None"]; sRead.Dispose(); }
public static IFlightRawDataExtractor CreateFlightRawDataExtractor(StorageFile file, FlightParameters parameters) { if (file == null) return null; var readStreamTask = file.OpenStreamForReadAsync(); readStreamTask.Wait(); MemoryStream stream = new MemoryStream(102400); byte[] bytes = new byte[readStreamTask.Result.Length]; readStreamTask.Result.Read(bytes, 0, Convert.ToInt32(readStreamTask.Result.Length)); stream.Write(bytes, 0, Convert.ToInt32(readStreamTask.Result.Length)); //Task temp1 = readStreamTask.AsTask(); //temp1.Wait(); //var temp2 = readStreamTask.GetResults(); BinaryReader reader = new BinaryReader(stream); //temp2.AsStreamForRead(1024000)); //readStreamTask.Result); var handler = new FlightDataReadingHandler(reader); //if (parameters != null) //{ // handler.Definition = CreateDefinition(handler.Definition, parameters); //} return handler; }
private static async Task Inflate(StorageFile zipFile, StorageFolder destFolder) { if (zipFile == null) { throw new Exception("StorageFile (zipFile) passed to Inflate is null"); } else if (destFolder == null) { throw new Exception("StorageFolder (destFolder) passed to Inflate is null"); } Stream zipStream = await zipFile.OpenStreamForReadAsync(); using (ZipArchive zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Read)) { //Debug.WriteLine("Count = " + zipArchive.Entries.Count); foreach (ZipArchiveEntry entry in zipArchive.Entries) { //Debug.WriteLine("Extracting {0} to {1}", entry.FullName, destFolder.Path); try { await InflateEntryAsync(entry, destFolder); } catch (Exception ex) { Debug.WriteLine("Exception: " + ex.Message); } } } }
private async static Task<MemoryStream> CopyToMemoryStream(StorageFile file) { var memoryStream = new MemoryStream(); using (var stream = await file.OpenStreamForReadAsync()) { stream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); } return memoryStream; }
public static async Task<String> CreatePageWithImage(string token, string apiRoute, string content, StorageFile file) { // This is the file that was saved by the user as a gif (see previous blog post) Stream fileStream = await file.OpenStreamForReadAsync(); var client = new HttpClient(); // Note: API only supports JSON return type. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // I'm passsing in the token here because I get it when the user logs in but you can easily get it using the LiveIdAuth class: // await LiveIdAuth.GetAuthToken() client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); string imageName = file.DisplayName; string date = DateTime.Now.ToString(); string simpleHtml = "<html>" + "<head>" + "<title>" + date + ": " + imageName + "</title>" + "<meta name=\"created\" content=\"" + date + "\" />" + "</head>" + "<body>" + "<p>" + content + "<p>" + "<img src=\"name:" + imageName + "\" alt=\"" + imageName + "\" width=\"700\" height=\"700\" />" + "</body>" + "</html>"; HttpResponseMessage response; // Create the image part - make sure it is disposed after we've sent the message in order to close the stream. using (var imageContent = new StreamContent(fileStream)) { imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/gif"); // Post request to create a page in the Section "Jots" https://www.onenote.com/api/v1.0/pages?sectionName=Jots var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "pages?sectionName=" + WebUtility.UrlEncode("Jots")) { Content = new MultipartFormDataContent { {new StringContent(simpleHtml, Encoding.UTF8, "text/html"), "Presentation"}, {imageContent, imageName} } }; // Must send the request within the using block, or the image stream will have been disposed. response = await client.SendAsync(createMessage); imageContent.Dispose(); } return response.StatusCode.ToString(); }
//导航到此页面时,根据书籍的来源(书架/书库)加载书籍内容 protected override async void OnNavigatedTo(NavigationEventArgs e) { string[] book = e.Parameter as string[]; type = book[0]; chapters = ChapterItemViewModels.GetViewModel(); if (type == "0") { chapters.ChapterItems.Clear(); title = book[1]; //Debug.WriteLine(title); pages = book[2]; id = book[3]; StorageFolder localFolder = ApplicationData.Current.LocalFolder; StorageFolder bookFolder = await localFolder.GetFolderAsync("books"); file = await bookFolder.GetFileAsync(title + ".txt"); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var encoding = Encoding.GetEncoding(0); //encoding = Encoding.UTF8; x = encoding; using (Stream stream = await file.OpenStreamForReadAsync()) { using (StreamReader reader = new StreamReader(stream, encoding, false)) { string text = reader.ReadToEnd(); numOfPage = text.Length / wordsOnePage + 1; currentPage = int.Parse(pages); string result = text.Substring((currentPage - 1) * wordsOnePage, wordsOnePage); B1.Text = result; } } } if (type == "1") { bookId = (string)book[1]; try { List <string> chapterStrs = await BookService.GetChapterList(bookId); chapters.add(chapterStrs); nowChapter = (string)book[2]; content = (string)book[3]; string text = content; numOfPage = text.Length / wordsOnePage + 1; currentPage = 1; string result = text.Substring((currentPage - 1) * wordsOnePage, wordsOnePage); B1.Text = result; } catch (Exception exception) { B1.Text = "无法获得对应的书籍!"; } } }
protected static async Task<Stream> GetStreamBasedOnDirection(StorageFile file, TransferDirection direction) { switch (direction) { case TransferDirection.Up: return await file.OpenStreamForReadAsync(); case TransferDirection.Down: return await file.OpenStreamForWriteAsync(); } return null; }
public static IFlightRawDataExtractor CreateFlightRawDataExtractor(StorageFile file) { if (file == null) return null; var readStreamTask = file.OpenStreamForReadAsync(); readStreamTask.Wait(); BinaryReader reader = new BinaryReader(readStreamTask.Result); return new FlightDataReadingHandler(reader); }
private async void LoadEntriesByDate() { EntriesListView.Items.Add(MainCalendar.SelectedDates[0].ToString()); String ymfolder = YMDDate.Substring(0, 7); if (Directory.Exists(Path.Combine(appHomeFolder.Path, ymfolder))) { String[] allCurrentFiles = Directory.GetFiles( Path.Combine(appHomeFolder.Path, ymfolder), String.Format("{0}*.rtf", YMDDate), SearchOption.TopDirectoryOnly); if (allCurrentFiles.Length > 0) { StorageFolder subStorage = await appHomeFolder.GetFolderAsync(ymfolder); Windows.Storage.StorageFile currentFile = await subStorage.GetFileAsync(Path.GetFileName(allCurrentFiles[0])); Stream s = await currentFile.OpenStreamForReadAsync(); MainRichEdit.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, s.AsRandomAccessStream()); s.Dispose(); allCurrentFiles = allCurrentFiles.Skip(1).ToArray(); foreach (String f in allCurrentFiles) { PivotItem pi = new PivotItem(); var entryText = String.Format("Entry{0}", rootPivot.Items.Count + 1); pi.Header = entryText; RichEditBox reb = new RichEditBox(); reb.HorizontalAlignment = HorizontalAlignment.Stretch; reb.VerticalAlignment = VerticalAlignment.Stretch; currentJournalEntries.Add( new JournalEntry(reb, Path.Combine(appHomeFolder.Path), YMDDate, entryText)); pi.Content = reb; pi.Loaded += PivotItem_Loaded; rootPivot.Items.Add(pi); rootPivot.SelectedIndex = 0; } } } else { AddDefaultEntry(); } }
/// <summary> /// Implements reading ini data from a file. /// </summary> /// <param name="file"> /// Path to the file /// </param> /// <param name="fileEncoding"> /// File's encoding. /// </param> public async Task<IniData> ReadFile(StorageFile file, Encoding fileEncoding) { try { var stream = await file.OpenStreamForReadAsync(); using (StreamReader sr = new StreamReader(stream, fileEncoding)) { return ReadData(sr); } } catch (IOException ex) { throw new ParsingException(String.Format("Could not parse file {0}", file), ex); } }
public async Task<LibraryPropertyFile> LoadAsync(StorageFile libraryFile) { if (libraryFile == null) { return null; } Stream libraryFileStream = await libraryFile.OpenStreamForReadAsync(); XmlSerializer libraryXmlSerializer = new XmlSerializer(typeof(LibraryPropertyFile)); LibraryPropertyFile libraryPropertyFile = libraryXmlSerializer.Deserialize(libraryFileStream) as LibraryPropertyFile; libraryFileStream.Dispose(); return libraryPropertyFile; }
private async Task LoadCBRComic(StorageFile storageFile) { try { using (var zipStream = await storageFile.OpenStreamForReadAsync()) using (var memoryStream = new MemoryStream((int)zipStream.Length)) { await zipStream.CopyToAsync(memoryStream); memoryStream.Position = 0; var rarArchive = RarArchive.Open(memoryStream); if (rarArchive == null) return; var comic = new DisplayComic { File = storageFile, FullPath = storageFile.Name, Name = storageFile.DisplayName, Pages = rarArchive.Entries.Count }; foreach(var entry in rarArchive.Entries) { if (IsValidEntry(entry)) continue; using (var entryStream = new MemoryStream((int)entry.Size)) { entry.WriteTo(entryStream); entryStream.Position = 0; using (var binaryReader = new BinaryReader(entryStream)) { var bytes = binaryReader.ReadBytes((int)entryStream.Length); comic.CoverageImageBytes = bytes; break; } } } comics.Add(comic); } } catch (Exception ex) { // Do nothing } }
private async void captureButton_Click(object sender, RoutedEventArgs e) { if (cameraCapture != null) { file = await cameraCapture.CapturePhoto(); IRandomAccessStream imageStream = (await file.OpenStreamForReadAsync()).AsRandomAccessStream(); BitmapImage image = new BitmapImage(); image.SetSource(imageStream); previewField.Source = image; await cameraCapture.StopPreview(); captureField.Source = null; cameraCapture.Dispose(); } }
public async Task<Message> OpenTnef(StorageFile datFile) { var message = new MimeMessage(); var bodyFile = default(StorageFile); var targetFilesCollection = new List<FileInfo>(); using (var stream = await datFile.OpenStreamForReadAsync()) { using (var tnefReader = new TnefReader(stream)) { message = ExtractTnefMessage(tnefReader); if (message.Sender == null) { message.Sender = new MailboxAddress(string.Empty, "Sender unknown"); } foreach (MimePart mimePart in message.Attachments) { var isoFile = await LastExtractedFilesProvider.WriteFileToIsoStorage(mimePart.FileName, mimePart.ContentObject.Open()); var basicProperties = await isoFile.GetBasicPropertiesAsync(); var thumb = this.GetVectorThumbnailByType(isoFile.FileType); var size = FileSizeString((double)basicProperties.Size); targetFilesCollection.Add(new FileInfo(isoFile, thumb, size, datFile.DisplayName)); } var body = Enumerable.FirstOrDefault<TextPart>(Enumerable.OfType<TextPart>(message.BodyParts)); if (body != null && !String.IsNullOrEmpty(body.Text)) { string bodyFileName = "Message_Body."; if (body.IsHtml) { bodyFileName += "html"; } else if (body.IsPlain) { bodyFileName += "txt"; } else if (body.IsRichText) { bodyFileName += "rtf"; } bodyFile = await LastExtractedFilesProvider.WriteFileToIsoStorage(bodyFileName, body.Text); } } } var targetMessage = new Message(message.Subject, message.Sender.ToString(), string.Empty, message.Date.ToString(), bodyFile, targetFilesCollection); return targetMessage; }
private async void LoadFileFromStorage(String ymfolder, String entryFileName, RichEditBox reb) { StorageFolder subStorage = await appHomeFolder.GetFolderAsync(ymfolder); Windows.Storage.StorageFile currentFile = await subStorage.GetFileAsync(entryFileName); Stream s = await currentFile.OpenStreamForReadAsync(); reb.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.FormatRtf, s.AsRandomAccessStream()); s.Dispose(); }
/// <summary> /// Asynchronously loads contacts. /// </summary> /// <param name="fileToRead">The file.</param> /// <returns>a <see cref="ContactList"/>.</returns> static async Task<ContactList> LoadContactsAsync(StorageFile fileToRead) { using (var stream = await fileToRead.OpenStreamForReadAsync()) { using (StreamReader streamReader = new StreamReader(stream)) { string xml = streamReader.ReadToEnd(); var contactList = await Task.Run(() => { return Serializer.Deserialize<ContactList>(xml); }); await SetPictureUri(contactList); return contactList; } } }
private async void read() { try { file = await ApplicationData.Current.LocalFolder.GetFileAsync(filename); using (Stream stream = await file.OpenStreamForReadAsync()) { collection = (ObservableCollection<Music>) new DataContractJsonSerializer(typeof(ObservableCollection<Music>)) .ReadObject(stream); } } catch { } }
//Enrollment audio requirements //https://westus.dev.cognitive.microsoft.com/docs/services/563309b6778daf02acc0a508/operations/5645c3271984551c84ec6797 private async void enrollBtn_Click(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads; picker.FileTypeFilter.Add(".wav"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { // Application now has read/write access to the picked file txtBoxOutput.Text = "Picked: " + file.Name; } else { //User has cancelled operation return; } //Convert to stream var audioStream = await file.OpenStreamForReadAsync(); Guid speakerId = new Guid(txtBoxGuid.Text.ToString()); try { Enrollment response = await voiceServiceClient.EnrollAsync(audioStream, speakerId); if (response.EnrollmentStatus == Microsoft.ProjectOxford.SpeakerRecognition.Contract.EnrollmentStatus.Enrolled) { // enrollment successful LogMessage($"Enrolled."); } if (response.EnrollmentStatus == Microsoft.ProjectOxford.SpeakerRecognition.Contract.EnrollmentStatus.Enrolling) { // enrollment successful LogMessage($"Enrolling."); } } catch (Exception error) { LogMessage($"{error.Message}"); } }
private static async Task UnZipFileHelper(StorageFile zipFile, StorageFolder destinationFolder) { if (zipFile == null || destinationFolder == null || !Path.GetExtension(zipFile.Name).Equals(".zip", StringComparison.OrdinalIgnoreCase) ) { throw new ArgumentException("Invalid argument..."); } Stream zipMemoryStream = await zipFile.OpenStreamForReadAsync(); // Create zip archive to access compressed files in memory stream using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Read)) { // Unzip compressed file iteratively. foreach (ZipArchiveEntry entry in zipArchive.Entries) { await UnzipZipArchiveEntryAsync(entry, entry.FullName, destinationFolder); } } }
private async Task <HttpResponseMessage> uploadingPic(double scale) { try { MultipartFormDataContent form = new MultipartFormDataContent(); form.Add(new StreamContent(await photoFile.OpenStreamForReadAsync()), "user_file[]", "W8-" + DateTime.UtcNow.ToString("yyyy-MM-dd HHmmss") + ".jpg"); // name for upload if (App.FbParameters != null) { form.Add(new StringContent(App.FbParameters.Id), "fb_application_id"); form.Add(new StringContent(App.FbParameters.Token), "fb_access_token"); } form.Add(new StringContent(String.Format(new CultureInfo("en-US"), "{0}", scale)), "scale_factor"); if (loc != null) { form.Add(new StringContent(String.Format(new CultureInfo("en-US"), "{0}", loc.Latitude)), "lat"); form.Add(new StringContent(String.Format(new CultureInfo("en-US"), "{0}", loc.Longitude)), "lon"); } if (sensorRead != null) { form.Add(new StringContent(String.Format(new CultureInfo("en-US"), "{0,5:0.00}", sensorRead.YawDegrees)), "yaw"); form.Add(new StringContent(String.Format(new CultureInfo("en-US"), "{0,5:0.00}", sensorRead.PitchDegrees)), "pitch"); form.Add(new StringContent(String.Format(new CultureInfo("en-US"), "{0,5:0.00}", sensorRead.RollDegrees)), "roll"); } string resourceAddress = helper.getFromResourceFile("UploadPhotoUrl01_part01") + App.ZoomLoc.LastSelectedOldPic.Id.ToString() + helper.getFromResourceFile("UploadPhotoUrl01_part02"); HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, form); return(response); } catch (HttpRequestException hre) { showBasicDialog(hre.Message); return(null); } catch (TaskCanceledException) { //MessageDialog dialog = new MessageDialog("Katkestati."); //dialog.ShowAsync(); return(null); } finally { //Helpers.ScenarioCompleted(StartButton, CancelButton); } }
public static async Task<string> UploadImage(StorageFile file, string href, string access_token) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //client.BaseAddress = new Uri(href); MultipartFormDataContent form = new MultipartFormDataContent(); HttpContent content = new StringContent("fileToUpload"); form.Add(content, "fileToUpload"); var stream = await file.OpenStreamForReadAsync(); content = new StreamContent(stream); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "fileToUpload", FileName = file.Name }; form.Add(content); var response = await client.PostAsync(href, form); return response.Content.ReadAsStringAsync().Result; }
public async Task ExtractZip(StorageFile source, StorageFolder baseFolder) { using (var fileStream = await source.OpenStreamForReadAsync()) { ZipArchive archive = new ZipArchive(fileStream); foreach (ZipArchiveEntry file in archive.Entries) { string completeFileName = Path.Combine(baseFolder.Path, file.FullName); if (file.Name == "") { // Assuming Empty for Directory Directory.CreateDirectory(Path.GetDirectoryName(completeFileName)); continue; } file.ExtractToFile(completeFileName, true); } } }
public async static Task<List<Place>> GetData(StorageFile file) { if (allPlaces != null) return allPlaces; string jsonText = await FileIO.ReadTextAsync(file); //StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appdata:///places.json")); var fileStream = await file.OpenStreamForReadAsync(); var serializer = new DataContractJsonSerializer(typeof(List<Place>)); allPlaces = (List<Place>)serializer.ReadObject(fileStream); return allPlaces; }
/// <summary> /// Uploads a file in the current user's OneDrive root folder from this applications local folder /// using its specified itemId and filename. /// </summary> /// <param name="itemId">Unique item identifier within a DriveItem (folder/file).</param> /// <param name="filename">Name of the datafile.</param> /// <returns>A DriveItem representing the newly uploaded file.</returns> public static async Task <DriveItem> UploadFileToOneDriveAsync(string itemId, string filename) { try { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync(filename); var stream = await sampleFile.OpenStreamForReadAsync(); return(await GraphClient.Me.Drive.Items[itemId].ItemWithPath(filename).Content .Request() .PutAsync <DriveItem>(stream)); } catch (ServiceException ex) { Console.WriteLine($"Service Expception, Error uploading file to signed-in users one drive: {ex.Message}"); throw; } }
private async void InitializeData() { Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder; Windows.Storage.StorageFile file = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists); if (null != file) { using (var stream = await file.OpenStreamForReadAsync()) { using (var reader = new StreamReader(stream)) { var content = reader.ReadToEnd(); if (null != content && !"".Equals(content)) { var mod = cellGrid.Model; JsonArray array = JsonArray.Parse(content); foreach (var jsonValue in array) { var value = JsonObject.Parse(jsonValue.Stringify()); string ID = value.GetNamedString("ID"); string LastName = value.GetNamedString("LastName"); string FamilyName = value.GetNamedString("FamilyName"); string EmployeeNumber = value.GetNamedString("EmployeeNumber"); string Title = value.GetNamedString("Title"); string Dep = value.GetNamedString("Dep"); string Remark = value.GetNamedString("Remark"); mod[int.Parse(ID), 1].CellValue = LastName; mod[int.Parse(ID), 2].CellValue = FamilyName; mod[int.Parse(ID), 3].CellValue = EmployeeNumber; mod[int.Parse(ID), 4].CellValue = Title; mod[int.Parse(ID), 5].CellValue = Dep; mod[int.Parse(ID), 6].CellValue = Remark; } } } } } }
private async void Button_Click_3(object sender, RoutedEventArgs e) { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; picker.FileTypeFilter.Add(".xml"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); var stream = await file.OpenStreamForReadAsync(); XmlDocument doc = new XmlDocument(); doc.Load(stream); foreach (XmlNode node in doc.DocumentElement) { CsvRowsListView.Items.Add(node.InnerText); foreach (XmlNode child in node.ChildNodes) { } } }
private async Task<IEnumerable<Photo>> UploadAsync(StorageFile file) { using (var client = new HttpClient()) { using (var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture))) { using (var fileStream = await file.OpenStreamForReadAsync()) { //on pourrait uploader plusieurs images en même temps. Par simplicité je n'en uploade qu'une. content.Add(new StreamContent(fileStream), "NouveauFichier", file.Name); //using ( // var message = HttpResponseMessage result = await client.PostAsync("http://*****:*****@"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null; //} } } } }
private async void validateBtn_Click(object sender, RoutedEventArgs e) { try { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads; picker.FileTypeFilter.Add(".wav"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { // Application now has read/write access to the picked file txtBoxOutput.Text = "Picked: " + file.Name; } else { //User has cancelled operation return; } //Convert to stream var audioStream = await file.OpenStreamForReadAsync(); Guid speakerId = new Guid(txtBoxGuid.Text.ToString()); var response = await voiceServiceClient.VerifyAsync(audioStream, speakerId); LogMessage($"Result: {response.Result}"); LogMessage($"Confidence: {response.Confidence}"); LogMessage($"Phrase: {response.Phrase}"); } catch (Exception error) { LogMessage($"{error.Message}"); } }
private async Task OpenFileAsync(StorageFile file) { loading.Visibility = Visibility.Visible; using (var s = await file.OpenStreamForReadAsync()) { try { var xml = await GetStringFromStreamAsync(s); _file = await new FB2Reader().ReadAsync(xml); //DisplayLines(); } catch (Exception ex) { bookInfo.Text = string.Format("Error loading file : {0}", ex.Message); } finally { loading.Visibility = Visibility.Collapsed; } } }
/// <summary> /// Uploads a file to OneDrive. This method is NOT thread safe. It assumes that the contents of the file will not change during the upload process. /// </summary> /// <param name="file"></param> The file to upload to OneDrive. The file will be read, and a copy uploaded. The original file object will not be modified. /// <param name="destinationPath"></param> The path to the destination on Onedrive. Passing in an empty string will place the file in the root of Onedrive. Other folder paths should be passed in with a leading '/' character, such as "/Documents" or "/Pictures/Random" /// <returns>The response message given by the server for the request</returns> public IAsyncOperation<HttpResponseMessage> UploadFileAsync(StorageFile file, string destinationPath) { string uploadUri = String.Format(UploadUrlFormat, destinationPath, file.Name); return Task.Run(async () => { using (Stream stream = await file.OpenStreamForReadAsync()) { using (HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream())) { using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Put, new Uri(uploadUri))) { requestMessage.Content = streamContent; using (HttpResponseMessage response = await httpClient.SendRequestAsync(requestMessage)) { return response; } } } } }).AsAsyncOperation<HttpResponseMessage>(); }
private async void KiesBestandAsync() { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads; picker.FileTypeFilter.Add(".xls"); picker.FileTypeFilter.Add(".xlsx"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { KiesBestandButton.Visibility = Visibility.Collapsed; // Application now has read/write access to the picked file // this.textBlock.Text = "Picked photo: " + file.Name; var stream = await file.OpenStreamForReadAsync(); List <string> links = new List <string>(); using (var reader = ExcelReaderFactory.CreateReader(stream)) { TextBlockItems.Text = "Zoeken naar links..."; do { while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { string link = reader.GetString(i); if (link != null && link.Contains("https://") && (link.Contains("youtube.com") || link.Contains("youtu.be"))) { links.Add(link); } } } } while (reader.NextResult()); TextBlockItems.Text = $"{links.Count} items gevonden."; var folderPicker = new Windows.Storage.Pickers.FolderPicker(); folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; folderPicker.FileTypeFilter.Add("*"); Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); if (folder != null) { // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) Windows.Storage.AccessCache.StorageApplicationPermissions. FutureAccessList.AddOrReplace("PickedFolderToken", folder); var youtube = new YoutubeClient(); TextBlockItems.Text = "Bezig met downloaden."; int aantalLinks = links.Count; int teller = 0; int fouten = 0; foreach (string link in links) { try { var video = await youtube.Videos.GetAsync(link); var manifest = await youtube.Videos.Streams.GetManifestAsync(video.Id); var streamInfo = manifest.GetAudioOnlyStreams().GetWithHighestBitrate(); if (streamInfo != null) { var soundStream = await youtube.Videos.Streams.GetAsync(streamInfo); var storageFolder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync("PickedFolderToken"); var storageFile = await storageFolder.CreateFileAsync($"{Regex.Replace(video.Title, "[^a-zA-Z0-9_.]+", " ", RegexOptions.Compiled)}.{streamInfo.Container}", CreationCollisionOption.ReplaceExisting); long length = soundStream.AsInputStream().AsStreamForRead().Length; var writeStream = await storageFile.OpenStreamForWriteAsync(); await soundStream.CopyToAsync(writeStream); teller++; DownloadProgress.Value = (teller + 0.0) / (aantalLinks + 0.0) * 100; TextBlockItems.Text = $"{teller - fouten}/{aantalLinks} liedjes gedownload." + (fouten > 0 ? $" Mislukt: {fouten}" : ""); } } catch (Exception e) { Debug.WriteLine(e); teller++; fouten++; } } } else { TextBlockItems.Text = "Downloaden geannuleerd."; } } } else { // this.textBlock.Text = "Operation cancelled."; } }
private async Task UploadFileToSkydrive(StorageFile file, string eventBuddyFolderId, LiveConnectClient client) { using (var stream = await file.OpenStreamForReadAsync()) { var progressHandler = InitializeProgressBar(); var hasErrors = false; do { try { hasErrors = false; this.retrySelected = false; LiveOperationResult result = await client.BackgroundUploadAsync(eventBuddyFolderId, file.Name, stream.AsInputStream(), OverwriteOption.Overwrite, cancellationToken.Token, progressHandler); this.FileNameTextBlock.Text = file.Name; await UpdateSession(client, result); } catch (LiveConnectException) { hasErrors = true; } if (hasErrors) { var errorTitle = "Upload file error"; await ShowMessage(errorTitle, "Exception occured while trying to upload the " + file.Name + " file to Skydrive."); } uploadProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed; } while(this.retrySelected); } }
private async Task opensubreddits_clickasync() { Regex url_rx = new Regex(@"(?:^(?:https?:\/\/)?(?:www.)?(?:(?:np|np-dk).)?(?:reddit\.com)\/r\/([a-zA-Z0-9_]+)\/?|^(?:\/?r\/)?([a-zA-Z0-9_]+))", RegexOptions.Compiled); var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".txt"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { try { Stream x = await file.OpenStreamForReadAsync(); StreamReader reader = new StreamReader(x, Encoding.UTF8); try { while (!reader.EndOfStream) { string line = await reader.ReadLineAsync(); StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(line); bool canAccess = StorageApplicationPermissions.FutureAccessList.CheckAccess(folder); if (canAccess) { Link link = new Link(); link.Url = line; LinkList.Add(link); } } } finally { reader.Dispose(); x.Dispose(); } } catch (PathTooLongException) { ShowMessageDialog("File Opening Error", "Unfortunately we couldn't open the file as the path was too long. Please try using a shorter path."); return; } catch (NotSupportedException) { ShowMessageDialog("File Opening Error", "Unfortunately we couldn't open the file as file access is not supported on this platform. Apologies for the inconvenience."); return; } catch (DirectoryNotFoundException) { ShowMessageDialog("File Opening Error", "Unfortunately we couldn't open the file as we couldn't find the directory. Please try using a different directory."); return; } catch (SecurityException) { ShowMessageDialog("File Opening Error", "Unfortunately we couldn't open the file due to security issues. Please send the error code SEC1 to the developer for support."); return; } catch (UnauthorizedAccessException) { ShowMessageDialog("File Opening Error", "Unfortunately we couldn't open the file as access to that file is not authorized on this account. Please try again with higher priveleges or open a different file."); return; } catch (IOException) { ShowMessageDialog("File Opening Error", "Unfortunately we couldn't open the file. Please send the error code IOE1 to the developer for support."); return; } } }
public async Task<bool> readPackageAsync(StorageFile file) { this.deckDescriptionFound = false; this.deck.filename = file.Name; bool result = false; //Locate Archive based on this.packagePath var folder = ApplicationData.Current.TemporaryFolder; //Open Archive Stream stream = await file.OpenStreamForReadAsync(); using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read)) { foreach (ZipArchiveEntry en in archive.Entries) { //Iterate through Entries if (en.FullName.Contains("deckdescription.xml")) { char[] output = new char[en.Length]; this.deckDescriptionFound = true; //Open deckdescription.xml and save it into deckXml using (StreamReader sr = new StreamReader(en.Open())) { await sr.ReadAsync(output, 0, (int)en.Length); //There was some weirdness here, which I'm documenting for the sake of my Memento-esque memory. //We were hitting all kinds of weird XMLExceptions at the end of certain files (XMLExceptions around the Null character 0x00). //The UTF-8 files effected always involved some characters that required two bytes. We'd hit this exception after the closing tag ("</deck>") //When I inspected these files in a Hex editor, there were never any null characters at the end of the file, which was weird. //My hypothesis was that when we built the output char array using en.Length, that length was returning the length in Bytes, which //was not the same as the number of characters (since some required 2 bytes). The result was that the output array was longer //than the string that it was representing, and those extra slots were NULL (excess length was a function of the number of characters //requiring 2 bytes). Thus, I am trimming the null chars off the end. //tl;dr: ZipArchiveEntry.Length doesn't actually return the number of characters in the file. This seems obvious in retrospect. this.deckXml = new String(output).TrimEnd('\0'); } } if (en.FullName.EndsWith(".jpg") || en.FullName.EndsWith(".jpeg") || en.FullName.EndsWith(".png")) { //Copy Images to LocalStorage - Tmp Folder using (Stream picdata = en.Open()) { StorageFile outfile = await folder.CreateFileAsync(en.Name, CreationCollisionOption.ReplaceExisting); using (Stream outputfilestream = await outfile.OpenStreamForWriteAsync()) { await picdata.CopyToAsync(outputfilestream); await outputfilestream.FlushAsync(); //flush makes sure all the bits are written } } } } } //kick off processXml, return result of that. if (this.deckDescriptionFound) { try { result = processXml(); } catch (XmlException e) { result = false; } } else { result = false; } return result; }
public static async Task<object> readPlistAsync(StorageFile file) { var s = await file.OpenStreamForReadAsync(); return readPlist(s, plistType.Auto); }
static public async Task <ObservableCollection <ClassSob> > OpenP() { ObservableCollection <ClassSob> classSobsC = new ObservableCollection <ClassSob>(); try { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".uranprog"); picker.FileTypeFilter.Add(".xml"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { // Application now has read/write access to the picked file // this.textBlock.Text = "Picked photo: " + file.Name; // } // else // { // this.textBlock.Text = "Operation cancelled."; // } // var folderPicker = new Windows.Storage.Pickers.FolderPicker(); // folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; // folderPicker.FileTypeFilter.Add("*"); // Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync(); // if (folder != null) // { // Application now has read/write access to all contents in the picked folder // (including other sub-folder contents) // Windows.Storage.AccessCache.StorageApplicationPermissions. // FutureAccessList.AddOrReplace("PickedFolderToken", folder); // StorageFolder storageFolder = ApplicationData.Current.LocalFolder; using (StreamReader writer = new StreamReader(await file.OpenStreamForReadAsync())) { DataSet ds = new DataSet(); ds.ReadXml(writer); // выбираем первую таблицу DataTable SobT = ds.Tables[0]; // перебор всех строк таблицы foreach (DataRow row in SobT.Rows) { Debug.WriteLine(row.ItemArray[0].ToString()); List <ClassSobNeutron> cll = new List <ClassSobNeutron>(); var cells = row.ItemArray; string[] strTime = row.ItemArray[3].ToString().Split('.'); // Debug.WriteLine(time1); DataTimeUR dataTimeUR = new DataTimeUR(0, 0, Convert.ToInt16(strTime[0]), Convert.ToInt16(strTime[1]), Convert.ToInt16(strTime[2]), Convert.ToInt16(strTime[3]), Convert.ToInt16(strTime[4]), Convert.ToInt16(strTime[5]), Convert.ToInt16(strTime[6])); if (row.ItemArray[1].ToString().Contains("Test")) { string[] vs = row.ItemArray[1].ToString().Split("_"); string gg = vs[0] + "_" + vs[2]; dataTimeUR.corectTime(gg); } else { dataTimeUR.corectTime(row.ItemArray[1].ToString()); } int[] mA = new int[12]; for (int i = 0; i < 12; i++) { mA[i] = Convert.ToInt32(row.ItemArray[i + 6]); } int[] mT = new int[12]; for (int i = 0; i < 12; i++) { mT[i] = Convert.ToInt32(row.ItemArray[i + 54]); } double[] sT = new double[12]; for (int i = 0; i < 12; i++) { // MessageDialog messageDialog4 = new MessageDialog(row.ItemArray[i+30].ToString()+"\t"+i.ToString()); // await messageDialog4.ShowAsync(); sT[i] = Convert.ToDouble((row.ItemArray[i + 30].ToString().Replace(".", ","))); } if (Convert.ToInt32(row.ItemArray[5]) > 0) { DataTable dNeutron = ds.Tables[1]; foreach (DataRow rowN in dNeutron.Rows) { var cellsN = rowN.ItemArray; if ((row.ItemArray[1].ToString() == rowN.ItemArray[1].ToString()) && (dataTimeUR.TimeString() == rowN.ItemArray[4].ToString())) { cll.Add(new ClassSobNeutron() { D = Convert.ToInt32(rowN.ItemArray[2]), Amp = Convert.ToInt32(rowN.ItemArray[3]), TimeAmp = Convert.ToInt32(rowN.ItemArray[7]), TimeEnd = Convert.ToInt32(rowN.ItemArray[8]), TimeEnd3 = Convert.ToInt32(rowN.ItemArray[9]), TimeFirst = Convert.ToInt32(rowN.ItemArray[5]), TimeFirst3 = Convert.ToInt32(rowN.ItemArray[6]) }); } } } try { classSobsC.Add(new ClassSob() { nameFile = row.ItemArray[1].ToString(), nameklaster = row.ItemArray[2].ToString(), nameBAAK = "У1", time = dataTimeUR.TimeString(), mAmp = mA, dateUR = dataTimeUR, TimeS0 = Convert.ToString(row.ItemArray[54]), TimeS1 = Convert.ToString(row.ItemArray[55]), TimeS2 = Convert.ToString(row.ItemArray[56]), TimeS3 = Convert.ToString(row.ItemArray[57]), TimeS4 = Convert.ToString(row.ItemArray[58]), TimeS5 = Convert.ToString(row.ItemArray[59]), TimeS6 = Convert.ToString(row.ItemArray[60]), TimeS7 = Convert.ToString(row.ItemArray[61]), TimeS8 = Convert.ToString(row.ItemArray[62]), TimeS9 = Convert.ToString(row.ItemArray[63]), TimeS10 = Convert.ToString(row.ItemArray[64]), TimeS11 = Convert.ToString(row.ItemArray[65]), mTimeD = mT, sig0 = Convert.ToDouble((row.ItemArray[30].ToString().Replace(".", ","))), sig1 = Convert.ToDouble((row.ItemArray[31].ToString().Replace(".", ","))), sig2 = Convert.ToDouble((row.ItemArray[32].ToString().Replace(".", ","))), sig3 = Convert.ToDouble((row.ItemArray[33].ToString().Replace(".", ","))), sig4 = Convert.ToDouble((row.ItemArray[34].ToString().Replace(".", ","))), sig5 = Convert.ToDouble((row.ItemArray[35].ToString().Replace(".", ","))), sig6 = Convert.ToDouble((row.ItemArray[36].ToString().Replace(".", ","))), sig7 = Convert.ToDouble((row.ItemArray[37].ToString().Replace(".", ","))), sig8 = Convert.ToDouble((row.ItemArray[38].ToString().Replace(".", ","))), sig9 = Convert.ToDouble((row.ItemArray[39].ToString().Replace(".", ","))), sig10 = Convert.ToDouble((row.ItemArray[40].ToString().Replace(".", ","))), sig11 = Convert.ToDouble((row.ItemArray[41].ToString().Replace(".", ","))), Nnull0 = Convert.ToInt16(row.ItemArray[42]), Nnull1 = Convert.ToInt16(row.ItemArray[43]), Nnull2 = Convert.ToInt16(row.ItemArray[44]), Nnull3 = Convert.ToInt16(row.ItemArray[45]), Nnull4 = Convert.ToInt16(row.ItemArray[46]), Nnull5 = Convert.ToInt16(row.ItemArray[47]), Nnull6 = Convert.ToInt16(row.ItemArray[48]), Nnull7 = Convert.ToInt16(row.ItemArray[49]), Nnull8 = Convert.ToInt16(row.ItemArray[50]), Nnull9 = Convert.ToInt16(row.ItemArray[51]), Nnull10 = Convert.ToInt16(row.ItemArray[52]), Nnull11 = Convert.ToInt16(row.ItemArray[53]), classSobNeutronsList = cll }); } catch (Exception ex) { MessageDialog messageDialogf1 = new MessageDialog("dfsfs" + ex.ToString()); await messageDialogf1.ShowAsync(); } //booksTable.Columns.Add(idColumn); // booksTable.Columns.Add(FileColumn); //booksTable.Columns.Add(klColumn); // booksTable.Columns.Add(TimeColumn); // booksTable.Columns.Add(SAColumn); // booksTable.Columns.Add(SNColumn); /* booksTable.Columns.Add(AD1Column); * booksTable.Columns.Add(AD2Column); * booksTable.Columns.Add(AD3Column); * booksTable.Columns.Add(AD4Column); * booksTable.Columns.Add(AD5Column); * booksTable.Columns.Add(AD6Column); * booksTable.Columns.Add(AD7Column); * booksTable.Columns.Add(AD8Column); * booksTable.Columns.Add(AD9Column); * booksTable.Columns.Add(AD10Column); * booksTable.Columns.Add(AD11Column); * booksTable.Columns.Add(AD12Column); * * booksTable.Columns.Add(ND1Column); * booksTable.Columns.Add(ND2Column); * booksTable.Columns.Add(ND3Column); * booksTable.Columns.Add(ND4Column); * booksTable.Columns.Add(ND5Column); * booksTable.Columns.Add(ND6Column); * booksTable.Columns.Add(ND7Column); * booksTable.Columns.Add(ND8Column); * booksTable.Columns.Add(ND9Column); * booksTable.Columns.Add(ND10Column); * booksTable.Columns.Add(ND11Column); * booksTable.Columns.Add(ND12Column); * * booksTable.Columns.Add(Sig1Column); * booksTable.Columns.Add(Sig2Column); * booksTable.Columns.Add(Sig3Column); * booksTable.Columns.Add(Sig4Column); * booksTable.Columns.Add(Sig5Column); * booksTable.Columns.Add(Sig6Column); * booksTable.Columns.Add(Sig7Column); * booksTable.Columns.Add(Sig8Column); * booksTable.Columns.Add(Sig9Column); * booksTable.Columns.Add(Sig10Column); * booksTable.Columns.Add(Sig11Column); * booksTable.Columns.Add(Sig12Column); * * booksTable.Columns.Add(NullD1Column); * booksTable.Columns.Add(NullD2Column); * booksTable.Columns.Add(NullD3Column); * booksTable.Columns.Add(NullD4Column); * booksTable.Columns.Add(NullD5Column); * booksTable.Columns.Add(NullD6Column); * booksTable.Columns.Add(NullD7Column); * booksTable.Columns.Add(NullD8Column); * booksTable.Columns.Add(NullD9Column); * booksTable.Columns.Add(NullD10Column); * booksTable.Columns.Add(NullD11Column); * booksTable.Columns.Add(NullD12Column); * * booksTable.Columns.Add(TD1Column); * booksTable.Columns.Add(TD2Column); * booksTable.Columns.Add(TD3Column); * booksTable.Columns.Add(TD4Column); * booksTable.Columns.Add(TD5Column); * booksTable.Columns.Add(TD6Column); * booksTable.Columns.Add(TD7Column); * booksTable.Columns.Add(TD8Column); * booksTable.Columns.Add(TD9Column); * booksTable.Columns.Add(TD10Column); * booksTable.Columns.Add(TD11Column); * booksTable.Columns.Add(TD12Column); */ } } } else { } } catch (Exception ex) { MessageDialog messageDialogf = new MessageDialog(ex.ToString()); await messageDialogf.ShowAsync(); } return(classSobsC); }
private async Task SendFileAsync(String url, StorageFile sFile, HttpMethod httpMethod) { //Log data for upload attempt Windows.Storage.FileProperties.BasicProperties fileProperties = await sFile.GetBasicPropertiesAsync(); Dictionary<string, string> properties = new Dictionary<string, string> { { "File Size", fileProperties.Size.ToString() } }; App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload attempt", properties); HttpStreamContent streamContent = null; try { //Open file to send as stream Stream stream = await sFile.OpenStreamForReadAsync(); streamContent = new HttpStreamContent(stream.AsInputStream()); Debug.WriteLine("SendFileAsync() - sending: " + sFile.Path); } catch (FileNotFoundException ex) { Debug.WriteLine(ex.Message); // Log telemetry event about this exception var events = new Dictionary<string, string> { { "OneDrive", ex.Message } }; App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events); } catch (Exception ex) { // Log telemetry event about this exception var events = new Dictionary<string, string> { { "OneDrive", ex.Message } }; App.Controller.TelemetryClient.TrackEvent("FailedToOpenFile", events); throw new Exception("SendFileAsync() - Cannot open file. Err= " + ex.Message); } if (streamContent == null) { //Throw exception if stream is not created Debug.WriteLine(" File Path = " + (sFile != null ? sFile.Path : "?")); throw new Exception("SendFileAsync() - Cannot open file."); } try { Uri resourceAddress = new Uri(url); //Create requst to upload file using (HttpRequestMessage request = new HttpRequestMessage(httpMethod, resourceAddress)) { request.Content = streamContent; // Do an asynchronous POST. using (HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token)) { await DebugTextResultAsync(response); if (response.StatusCode != HttpStatusCode.Created) { throw new Exception("SendFileAsync() - " + response.StatusCode); } } } } catch (TaskCanceledException ex) { // Log telemetry event about this exception var events = new Dictionary<string, string> { { "OneDrive", ex.Message } }; App.Controller.TelemetryClient.TrackEvent("CancelledFileUpload", events); throw new Exception("SendFileAsync() - " + ex.Message); } catch (Exception ex) { // This failure will already be logged in telemetry in the enclosing UploadPictures function. We don't want this to be recorded twice. throw new Exception("SendFileAsync() - Error: " + ex.Message); } finally { streamContent.Dispose(); Debug.WriteLine("SendFileAsync() - final."); } App.Controller.TelemetryClient.TrackEvent("OneDrive picture upload success", properties); }
private async void ReadBook_Click(object sender, RoutedEventArgs e) { //open file picker var picker = new Windows.Storage.Pickers.FileOpenPicker(); //show icons as thumbnails picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; //open on desktop if not opened before picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop; //only need txt or epub files picker.FileTypeFilter.Add(".txt"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { IRandomAccessStream sr = await file.OpenReadAsync(); byte[] result; using (Stream stream = await file.OpenStreamForReadAsync()) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); result = memoryStream.ToArray(); } } var folder = ApplicationData.Current.LocalFolder; StorageFolder subFolder; try { subFolder = await folder.GetFolderAsync("books"); } catch (FileNotFoundException) { subFolder = await folder.CreateFolderAsync("books"); } /*await subFolder.DeleteAsync(); * await folder.CreateFolderAsync("books"); * var k = await folder.GetFoldersAsync(); * foreach(StorageFolder sf in k) * { * await sf.DeleteAsync(); * }*/ if (!await isFilePresent(file.Name, subFolder)) { file = await subFolder.CreateFileAsync(file.Name); await FileIO.WriteBytesAsync(file, result); String str = await new TxtParser().readFile(file); Book b = new Book(str); String read = ""; int counter = 0; var fileFolder = await folder.CreateFolderAsync(file.DisplayName); MessageDialog dialog = new MessageDialog("Synthesizing speech, this can take a few minutes, we'll let you know when we're done" + " Please don't close the app"); await dialog.ShowAsync(); while ((read = b.popSegment()) != null) { await new Speaker().StoreText(read, file.DisplayName, counter.ToString(), fileFolder); counter++; } updateBookPhrases(); dialog = new MessageDialog("File Synthesized, thank you for waiting"); await dialog.ShowAsync(); //update bindings books.AddBook(file.Name); this.DataContextChanged += (s, DataContextChangedEventArgs) => this.Bindings.Update(); } else { MessageDialog dialog = new MessageDialog("Book with that name already in library"); await dialog.ShowAsync(); } } }
public async static Task <EncryptionResult> EncryptFile(Windows.Storage.StorageFile inputFile, string password) { EncryptionResult encryptionResult = null; try { byte[] encryptedBytes = null; using (Stream stream = await inputFile.OpenStreamForReadAsync()) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); encryptedBytes = memoryStream.ToArray(); } } byte[] passwordToByteArray = System.Text.Encoding.ASCII.GetBytes(password); passwordToByteArray = SHA256.Create().ComputeHash(passwordToByteArray); byte[] SaltedHashedPassword = SHA256.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(password + "CryptoApp")); int Blocks128000Size = encryptedBytes.Length / 128000; int LastBlockSize = encryptedBytes.Length % 128000; int ctr = 0; byte[] encryptedByteArray = new byte[encryptedBytes.Length]; for (long i = 0; i < Blocks128000Size; i++) { byte[] input = new byte[128000]; System.Buffer.BlockCopy(encryptedBytes, ctr, input, 0, 128000); byte[] result = EncryptionService.GetEncryptedByteArray(input, passwordToByteArray); System.Buffer.BlockCopy(result, 0, encryptedByteArray, ctr, 128000); ctr = ctr + 128000; } if (LastBlockSize > 0) { byte[] input = new byte[LastBlockSize]; System.Buffer.BlockCopy(encryptedBytes, ctr, input, 0, LastBlockSize); byte[] result = EncryptionService.GetEncryptedByteArray(input, passwordToByteArray); System.Buffer.BlockCopy(result, 0, encryptedByteArray, ctr, LastBlockSize); } string CurrentDirectoryPath = System.IO.Path.GetDirectoryName(inputFile.Path); string CurrentFileName = Path.GetFileNameWithoutExtension(inputFile.Path); string CurrentFileExtension = Path.GetExtension(inputFile.Path); byte[] FileNameBytes = System.Text.Encoding.ASCII.GetBytes(CurrentFileName); byte[] ExtensionBytes = System.Text.Encoding.ASCII.GetBytes(CurrentFileExtension); int FileNameBytesLength = FileNameBytes.Length; int ExtensionBytesLength = ExtensionBytes.Length; FileNameBytesLength = (FileNameBytesLength >= 1000) ? 999 : FileNameBytesLength; ExtensionBytesLength = (ExtensionBytesLength >= 1000) ? 999 : ExtensionBytesLength; byte[] FileContentBytes = new byte[1000 + 1000 + 32 + encryptedByteArray.Length]; System.Buffer.BlockCopy(FileNameBytes, 0, FileContentBytes, 0, FileNameBytesLength); System.Buffer.BlockCopy(ExtensionBytes, 0, FileContentBytes, 1000, ExtensionBytesLength); System.Buffer.BlockCopy(SaltedHashedPassword, 0, FileContentBytes, 2000, 32); System.Buffer.BlockCopy(encryptedByteArray, 0, FileContentBytes, 2032, encryptedByteArray.Length); string WritePath = System.IO.Path.Combine(CurrentDirectoryPath, CurrentFileName + ".senc"); encryptionResult = new EncryptionResult() { Result = true, Error = null, EncryptedString = null, EncryptedContents = FileContentBytes, WritePath = WritePath }; } catch (Exception ex) { encryptionResult = new EncryptionResult() { Result = false, Error = ex.Message, EncryptedString = null, }; } return(encryptionResult); }
//根据书籍来源(书架/书库)加载上一页 private async void preButton_Click(object sender, RoutedEventArgs e) { preButton.IsEnabled = false; nextButton.IsEnabled = false; media_element.Stop(); if (type == "0") { if (currentPage == 1) { preButton.IsEnabled = true; nextButton.IsEnabled = true; if (isPlaying) { await play(); } return; } currentPage--; using (Stream stream = await file.OpenStreamForReadAsync()) { using (StreamReader reader = new StreamReader(stream, x, false)) { string text = reader.ReadToEnd(); numOfPage = text.Length / wordsOnePage + 1; string result = text.Substring((currentPage - 1) * wordsOnePage, wordsOnePage); B1.Text = result; } } } if (type == "1") { string result = null; if (currentPage == 1) { if (nowChapter == "1") { MessageDialog message = new MessageDialog("已经是第一页", "提示"); await message.ShowAsync(); return; } int num = int.Parse(nowChapter); nowChapter = (--num).ToString(); content = await BookService.GetChapterContent(bookId, nowChapter); currentPage = content.Length / wordsOnePage + 1; numOfPage = currentPage; result = content.Substring((currentPage - 1) * wordsOnePage, content.Length % wordsOnePage); } else { currentPage--; result = content.Substring((currentPage - 1) * wordsOnePage, wordsOnePage); } B1.Text = result; } preButton.IsEnabled = true; nextButton.IsEnabled = true; if (isPlaying) { await play(); } }
static public async Task <ObservableCollection <ClassSob> > OpenP() { ObservableCollection <ClassSob> classSobsC = new ObservableCollection <ClassSob>(); try { var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".uranprog"); picker.FileTypeFilter.Add(".xml"); Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { using (StreamReader writer = new StreamReader(await file.OpenStreamForReadAsync())) { DataSet ds = new DataSet(); int x = 0; using (XmlTextReader reader = new XmlTextReader(await file.OpenStreamForReadAsync())) { Debug.WriteLine("Start"); while (reader.Read()) { if (reader.IsStartElement("Sob") && !reader.IsEmptyElement) { while (reader.Read()) { if (reader.IsStartElement("Time") && !reader.IsEmptyElement) { Debug.WriteLine(x.ToString() + "\t" + reader.ReadString()); x++; } } } if (reader.IsStartElement("Project")) { Debug.WriteLine("ff" + x.ToString()); x++; } } } Debug.WriteLine("End"); ds.ReadXml(writer); // выбираем первую таблицу DataTable SobT = ds.Tables[0]; SobT.ReadXml(writer); MessageDialog messageDialogf11 = new MessageDialog("Rows" + SobT.Rows.Count.ToString()); await messageDialogf11.ShowAsync(); // перебор всех строк таблицы foreach (DataRow row in SobT.Rows) { Debug.WriteLine(row.ItemArray[0].ToString()); List <ClassSobNeutron> cll = new List <ClassSobNeutron>(); var cells = row.ItemArray; string[] strTime = row.ItemArray[3].ToString().Split('.'); // Debug.WriteLine(time1); DataTimeUR dataTimeUR = new DataTimeUR(0, 0, Convert.ToInt16(strTime[0]), Convert.ToInt16(strTime[1]), Convert.ToInt16(strTime[2]), Convert.ToInt16(strTime[3]), Convert.ToInt16(strTime[4]), Convert.ToInt16(strTime[5]), Convert.ToInt16(strTime[6])); if (row.ItemArray[1].ToString().Contains("Test")) { string[] vs = row.ItemArray[1].ToString().Split("_"); string gg = vs[0] + "_" + vs[2]; dataTimeUR.corectTime(gg); } else { dataTimeUR.corectTime(row.ItemArray[1].ToString()); } int[] mA = new int[12]; for (int i = 0; i < 12; i++) { mA[i] = Convert.ToInt32(row.ItemArray[i + 6]); } int[] mT = new int[12]; for (int i = 0; i < 12; i++) { mT[i] = Convert.ToInt32(row.ItemArray[i + 54]); } double[] sT = new double[12]; for (int i = 0; i < 12; i++) { sT[i] = Convert.ToDouble((row.ItemArray[i + 30].ToString().Replace(".", ","))); } /* if (Convert.ToInt32(row.ItemArray[5]) > 0) * { * * DataTable dNeutron = ds.Tables[1]; * foreach (DataRow rowN in dNeutron.Rows) * { * var cellsN = rowN.ItemArray; * if ((row.ItemArray[1].ToString() == rowN.ItemArray[1].ToString()) && (dataTimeUR.TimeString() == rowN.ItemArray[4].ToString())) * { * cll.Add(new ClassSobNeutron() * { * D = Convert.ToInt32(rowN.ItemArray[2]), * Amp = Convert.ToInt32(rowN.ItemArray[3]), * TimeAmp = Convert.ToInt32(rowN.ItemArray[7]), * TimeEnd = Convert.ToInt32(rowN.ItemArray[8]), * TimeEnd3 = Convert.ToInt32(rowN.ItemArray[9]), * TimeFirst = Convert.ToInt32(rowN.ItemArray[5]), * TimeFirst3 = Convert.ToInt32(rowN.ItemArray[6]) * }); * } * } * * } * */ try { Debug.WriteLine(dataTimeUR.TimeString()); classSobsC.Add(new ClassSob() { nameFile = row.ItemArray[1].ToString(), nameklaster = row.ItemArray[2].ToString(), nameBAAK = "У1", time = dataTimeUR.TimeString(), mAmp = mA, dateUR = dataTimeUR, TimeS0 = Convert.ToString(row.ItemArray[54]), TimeS1 = Convert.ToString(row.ItemArray[55]), TimeS2 = Convert.ToString(row.ItemArray[56]), TimeS3 = Convert.ToString(row.ItemArray[57]), TimeS4 = Convert.ToString(row.ItemArray[58]), TimeS5 = Convert.ToString(row.ItemArray[59]), TimeS6 = Convert.ToString(row.ItemArray[60]), TimeS7 = Convert.ToString(row.ItemArray[61]), TimeS8 = Convert.ToString(row.ItemArray[62]), TimeS9 = Convert.ToString(row.ItemArray[63]), TimeS10 = Convert.ToString(row.ItemArray[64]), TimeS11 = Convert.ToString(row.ItemArray[65]), mTimeD = mT, sig0 = Convert.ToDouble((row.ItemArray[30].ToString().Replace(".", ","))), sig1 = Convert.ToDouble((row.ItemArray[31].ToString().Replace(".", ","))), sig2 = Convert.ToDouble((row.ItemArray[32].ToString().Replace(".", ","))), sig3 = Convert.ToDouble((row.ItemArray[33].ToString().Replace(".", ","))), sig4 = Convert.ToDouble((row.ItemArray[34].ToString().Replace(".", ","))), sig5 = Convert.ToDouble((row.ItemArray[35].ToString().Replace(".", ","))), sig6 = Convert.ToDouble((row.ItemArray[36].ToString().Replace(".", ","))), sig7 = Convert.ToDouble((row.ItemArray[37].ToString().Replace(".", ","))), sig8 = Convert.ToDouble((row.ItemArray[38].ToString().Replace(".", ","))), sig9 = Convert.ToDouble((row.ItemArray[39].ToString().Replace(".", ","))), sig10 = Convert.ToDouble((row.ItemArray[40].ToString().Replace(".", ","))), sig11 = Convert.ToDouble((row.ItemArray[41].ToString().Replace(".", ","))), Nnull0 = Convert.ToInt16(row.ItemArray[42]), Nnull1 = Convert.ToInt16(row.ItemArray[43]), Nnull2 = Convert.ToInt16(row.ItemArray[44]), Nnull3 = Convert.ToInt16(row.ItemArray[45]), Nnull4 = Convert.ToInt16(row.ItemArray[46]), Nnull5 = Convert.ToInt16(row.ItemArray[47]), Nnull6 = Convert.ToInt16(row.ItemArray[48]), Nnull7 = Convert.ToInt16(row.ItemArray[49]), Nnull8 = Convert.ToInt16(row.ItemArray[50]), Nnull9 = Convert.ToInt16(row.ItemArray[51]), Nnull10 = Convert.ToInt16(row.ItemArray[52]), Nnull11 = Convert.ToInt16(row.ItemArray[53]), classSobNeutronsList = cll }); } catch (Exception ex) { MessageDialog messageDialogf1 = new MessageDialog("dfsfs" + ex.ToString()); await messageDialogf1.ShowAsync(); } } } } else { } } catch (Exception ex) { MessageDialog messageDialogf = new MessageDialog(ex.ToString()); await messageDialogf.ShowAsync(); } return(classSobsC); }