public static async Task <Color> GetDominantColorAsync(Uri uri) { if (uri == null) { throw new ArgumentNullException(nameof(uri)); } Color color = default(Color); IRandomAccessStreamWithContentType stationBgStream = null; try { var streamRef = RandomAccessStreamReference.CreateFromUri(uri); stationBgStream = await streamRef.OpenReadAsync(); color = await ColorUtilities.GetDominantColorAsync(stationBgStream); } catch (Exception) { //Dictionary<string, string> data = new Dictionary<string, string>(); //data.Add("BackgroundURI", uri.ToString()); // Microsoft.HockeyApp.HockeyClient.Current.TrackException(ex, data); } finally { stationBgStream?.Dispose(); } return(color); }
/// <summary> /// Sets the album art of the selected filename. This method is slow. /// </summary> /// <param name="filename">Path to file.</param> private async Task SetThumbnailAsync(string filename) { IntPtr image = GetAlbumArt(filename, "cover"); if (image != IntPtr.Zero) { using (Bitmap bmp = Image.FromHbitmap(image)) using (MemoryStream stream = new MemoryStream()) { bmp.Save(stream, ImageFormat.Png); InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream(); await randomAccessStream.WriteAsync(stream.ToArray().AsBuffer()); // Delete HBITMAP Win32.DeleteObject(image); // Dispose current thumbnail if (updater.Thumbnail != null) { IRandomAccessStreamWithContentType oldStream = await updater.Thumbnail.OpenReadAsync(); oldStream.Dispose(); } updater.Thumbnail = RandomAccessStreamReference.CreateFromStream(randomAccessStream); updater.Update(); } } else { updater.Thumbnail = null; } }
public static async Task <bool> HasSmartStore(Account account) { IRandomAccessStreamWithContentType stream = null; bool fileExists = false; try { var path = DBOpenHelper.GetOpenHelper(account).DatabaseFile; var folder = ApplicationData.Current.LocalFolder; var file = await folder.GetFileAsync(path); stream = await file.OpenReadAsync(); fileExists = true; } catch (UnauthorizedAccessException) { fileExists = true; } catch (Exception) { fileExists = false; } finally { if (stream != null) { stream.Dispose(); } } return(fileExists); }
private void ReleaseUnmanagedResources() { _inputStream?.Dispose(); _readingStream?.Dispose(); _inputStream = null; _readingStream = null; }
public static async Task <Color> GetStationBackgroundDominantColorAsync(StationItem station) { if (station == null) { throw new ArgumentNullException(nameof(station)); } if (station.Background == null) { return(Colors.Transparent); } string colorKey = "BgColor|" + station.Name; Color color = default(Color); if (await CookieJar.DeviceCache.ContainsObjectAsync(colorKey)) { var hexCode = await CookieJar.DeviceCache.PeekObjectAsync <string>(colorKey); return(ColorUtilities.ParseFromHexString(hexCode)); } IRandomAccessStreamWithContentType stationBgStream = null; try { var streamRef = RandomAccessStreamReference.CreateFromUri(new Uri(station.Background)); stationBgStream = await streamRef.OpenReadAsync(); color = await ColorUtilities.GetDominantColorAsync(stationBgStream); } catch (Exception ex) { Dictionary <string, string> data = new Dictionary <string, string>(); data.Add("StationName", station.Name); data.Add("StationBackgroundURL", station.Background?.ToString()); data.Add("StationURL", station.Site); Microsoft.HockeyApp.HockeyClient.Current.TrackException(ex, data); } finally { stationBgStream?.Dispose(); } await CookieJar.DeviceCache.PushObjectAsync <string>(colorKey, color.ToString()); return(color); }
private async Task <byte[]> GetAudioFileByte() { byte[] audio = null; DataReader reader = null; StorageFile audioFile = null; IRandomAccessStreamWithContentType stream = null; try { audioFile = await storageFolder.GetFileAsync("audioData.dat"); stream = await audioFile.OpenReadAsync(); audio = new byte[stream.Size]; reader = new DataReader(stream); await reader.LoadAsync((uint)stream.Size); reader.ReadBytes(audio); } catch (Exception e) { throw e; } finally { if (reader != null) { reader.Dispose(); } if (audioFile != null) { audioFile = null; } if (stream != null) { stream.Dispose(); stream = null; } } return(audio); }
private async void send_file_tcp(String ipadd, int port) { try { _tcpclient = new StreamSocket(); await _tcpclient.ConnectAsync(new HostName(ipadd), port.ToString()); _datawriter = new DataWriter(_tcpclient.OutputStream); StorageFolder folder = KnownFolders.PicturesLibrary; StorageFile file = await folder.GetFileAsync(this.filepath); IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync(); _datareader = new DataReader(filestream); while ((_length = await _datareader.LoadAsync(63 * 1024)) != 0) { _tosend = new byte[_length]; _datareader.ReadBytes(_tosend); _datawriter.WriteBytes(_tosend); await _datawriter.StoreAsync(); } filestream.Dispose(); _datareader.Dispose(); _datawriter.Dispose(); _tcpclient.Dispose(); _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath); this.callback.on_file_received(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); _stopwatch.Stop(); } catch (Exception e) { append_error_tolog(e, _stopwatch.Elapsed, ipadd); } }
public async Task Paste(DataPackageView dataView, CanvasControl control = null) { IRandomAccessStreamWithContentType stream = null; try { if (dataView.Contains(StandardDataFormats.Bitmap)) { var data = await dataView.GetBitmapAsync(); stream = await data.OpenReadAsync(); } else if (dataView.Contains(StandardDataFormats.StorageItems)) { var items = await dataView.GetStorageItemsAsync(); if (items.Count > 0) { var(IsImage, Stream) = await TryParseImage(items[0]); if (IsImage) { stream = Stream; } } } if (stream != null) { var bitmap = await CanvasBitmap.LoadAsync(control ?? this.canvas, stream); this.Update(bitmap); } } catch (Exception e) { Debug.WriteLine(e.GetType() + ":\n" + e);//ignore } finally { stream?.Dispose(); } }
private async void OnCapturePhotoButtonClick(object sender, RoutedEventArgs e) { var file = await TestedControl.CapturePhotoToStorageFileAsync(ApplicationData.Current.TemporaryFolder); var bi = new BitmapImage(); IRandomAccessStreamWithContentType stream = null; try { stream = await TryCatchRetry.RunWithDelayAsync <Exception, IRandomAccessStreamWithContentType>( file.OpenReadAsync(), TimeSpan.FromSeconds(0.5), 10, true); await bi.SetSourceAsync(stream); } catch (Exception ex) { // Seems like a bug with WinRT not closing the file sometimes that writes the photo to. #pragma warning disable 4014 new MessageDialog(ex.Message, "Error").ShowAsync(); #pragma warning restore 4014 return; } finally { if (stream != null) { stream.Dispose(); } } PhotoImage.Source = bi; CapturedVideoElement.Visibility = Visibility.Collapsed; PhotoImage.Visibility = Visibility.Visible; }
public static async Task <ObservableCollection <recognizedData> > readAsync() { ObservableCollection <recognizedData> readInCollection = new ObservableCollection <recognizedData>();; if (HistoryCollection == null) { try { IRandomAccessStreamWithContentType stream = await(await ApplicationData. Current.LocalFolder.GetFileAsync("history.json")).OpenReadAsync(); JsonSerializer serializer = JsonSerializer.Create(); StreamReader streamReader = new StreamReader(stream.AsStreamForRead()); readInCollection = serializer.Deserialize <ObservableCollection <recognizedData> >(new JsonTextReader(streamReader)); stream.Dispose(); foreach (var i in readInCollection) { try { i.imageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(i.imageName); i.bitmapImage = new BitmapImage(); await i.bitmapImage.SetSourceAsync(await i.imageFile.OpenReadAsync()); } catch (FileNotFoundException) { continue; } } } catch (Exception) { //HistoryCollection = new ObservableCollection<recognizedData>(); } finally { HistoryCollection = readInCollection; GC.Collect(); } } return(HistoryCollection); }
public async void SetAlbumArt(string niceTitle) { var picture = (StorageFile)await pictureFolder.TryGetItemAsync(niceTitle + ".jpg"); var bitmap = new BitmapImage(); if (picture != null) { using (IRandomAccessStreamWithContentType pictureStream = await picture.OpenReadAsync()) { updater.Thumbnail = RandomAccessStreamReference.CreateFromStream(pictureStream); bitmap.SetSource(pictureStream); pictureStream.Dispose(); } } else { string result = ""; try { string url = @"https://www.googleapis.com/customsearch/v1?key=AIzaSyDrSn8h3ZnHe_zg-FkVGuHUBNYAhJ31Nqw&cx=000001731481601506413:s6vjwyrugku&fileType=jpg&searchType=image&imgSize=large&num=1&q=" + niceTitle; var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)await request.GetResponseAsync(); using (var sr = new StreamReader(response.GetResponseStream())) { result = sr.ReadToEnd(); } string image = (string)JObject.Parse(result)["items"][0]["link"]; using (Stream originalStream = await new HttpClient().GetStreamAsync(image)) { using (var memStream = new MemoryStream()) { await originalStream.CopyToAsync(memStream); memStream.Position = 0; await bitmap.SetSourceAsync(memStream.AsRandomAccessStream()); updater.Thumbnail = RandomAccessStreamReference.CreateFromStream(memStream.AsRandomAccessStream()); StorageFile file = await pictureFolder.CreateFileAsync(niceTitle + ".jpg", CreationCollisionOption.ReplaceExisting); using (Stream fileStream = await file.OpenStreamForWriteAsync()) { byte[] buffer = memStream.ToArray(); await fileStream.WriteAsync(buffer, 0, buffer.Length); } } } } catch (Exception) { //internet is niet availai } } mainPage.albumImage.Source = bitmap; updater.Update(); }
public void Dispose() { _streamReader?.Dispose(); _classicStream?.Dispose(); _accessStream?.Dispose(); }
public override async void send_file(String devicename, String bluid, int not) { try { _stopwatch.Start(); PeerFinder.AllowBluetooth = true; PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{" + bluid + "}"; var peers = await PeerFinder.FindAllPeersAsync(); foreach (var p in peers) { if (p.DisplayName.Equals(devicename)) { _peer_info = p; break; } } _bluetooth_client = new StreamSocket(); if (_peer_info.ServiceName.Equals("")) { await _bluetooth_client.ConnectAsync(_peer_info.HostName, "{" + bluid + "}"); } else { await _bluetooth_client.ConnectAsync(_peer_info.HostName, _peer_info.ServiceName); } StorageFolder folder = KnownFolders.PicturesLibrary; StorageFile file = await folder.GetFileAsync(this.filepath); IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync(); _length = (uint)filestream.Size; _ibuffer = new Windows.Storage.Streams.Buffer(_length); _datareader = new DataReader(filestream); await _datareader.LoadAsync(_length); _ibuffer = _datareader.ReadBuffer(_length); _datawriter = new DataWriter(_bluetooth_client.OutputStream); _datawriter.WriteBuffer(_ibuffer); await _datawriter.StoreAsync(); filestream.Dispose(); _datareader.Dispose(); _datawriter.Dispose(); _datareader = new DataReader(_bluetooth_client.InputStream); _datareader.InputStreamOptions = InputStreamOptions.Partial; scan_received_acks(); while (true) { uint count = await _datareader.LoadAsync(4); byte[] ack = new byte[count]; _datareader.ReadBytes(ack); _counter_all_acks += BitConverter.ToInt32(ack, 0); if ((uint)_counter_all_acks == _length) { break; } } _datareader.Dispose(); _bluetooth_client.Dispose(); _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath); this.callback.on_file_received(_message, this.results); this.main_view.text_to_logs(_message.Replace("\t", " ")); _ack_timer.Cancel(); _stopwatch.Stop(); } catch (Exception e) { append_error_tolog(e, _stopwatch.Elapsed, devicename); } }
/// <summary> /// Retrieves a list of artists from BuiltinArtists.xml /// </summary> /// <returns>A list of artists.</returns> private async Task <BuiltinArtistEntry[]> LoadBuiltinArtistEntriesAsync() { XDocument xmlDoc = null; IRandomAccessStreamWithContentType reader = null; //local file only try { using (HttpClient http = new HttpClient()) { var xmlText = await http.GetStringAsync("https://raw.githubusercontent.com/Amrykid/Neptunium-ArtistsDB/master/BuiltinArtists.xml"); xmlDoc = XDocument.Parse(xmlText); } } catch (Exception) { //Opens up an XDocument for reading the xml file. var file = builtInArtistsFile; reader = await file.OpenReadAsync(); xmlDoc = XDocument.Load(reader.AsStream()); } //Creates a list to hold the artists. List <BuiltinArtistEntry> artists = new List <BuiltinArtistEntry>(); //Looks through the <Artist> elements in the file, creating a BuiltinArtistEntry for each one. foreach (var artistElement in xmlDoc.Element("Artists").Elements("Artist")) { var artistEntry = new BuiltinArtistEntry(); artistEntry.Name = artistElement.Attribute("Name").Value; if (artistElement.Attribute("JPopAsiaUrl") != null) { artistEntry.JPopAsiaUrl = new Uri(artistElement.Attribute("JPopAsiaUrl").Value); } if (artistElement.Elements("AltName") != null) { artistEntry.AltNames = artistElement.Elements("AltName").Select(altNameElement => { string name = altNameElement.Value; string lang = "en"; string sayAs = null; if (altNameElement.Attribute("Lang") != null) { lang = altNameElement.Attribute("Lang").Value; } if (altNameElement.Attribute("SayAs") != null) { sayAs = altNameElement.Attribute("SayAs").Value; } return(new BuiltinArtistEntryAltName(name, lang, sayAs)); }).ToArray(); } if (artistElement.Elements("Related") != null) { artistEntry.RelatedArtists = artistElement.Elements("Related").Select(relatedElement => { return(relatedElement.Value); }).ToArray(); } if (artistElement.Attribute("FanArtTVUrl") != null) { artistEntry.FanArtTVUrl = new Uri(artistElement.Attribute("FanArtTVUrl").Value); } if (artistElement.Attribute("MusicBrainzUrl") != null) { artistEntry.MusicBrainzUrl = new Uri(artistElement.Attribute("MusicBrainzUrl").Value); } if (artistElement.Attribute("OriginCountry") != null) { artistEntry.CountryOfOrigin = artistElement.Attribute("OriginCountry").Value; } if (artistElement.Attribute("NameLanguage") != null) { artistEntry.NameLanguage = artistElement.Attribute("NameLanguage").Value; } else { artistEntry.NameLanguage = "en"; } if (artistElement.Attribute("SayAs") != null) { artistEntry.NameSayAs = artistElement.Attribute("SayAs").Value; } artistEntry.IsBuiltIn = true; //Adds the artist entry to the list. artists.Add(artistEntry); } //Clean up. xmlDoc = null; reader?.Dispose(); return(artists.ToArray()); }