Пример #1
0
 public static CueFile CreateFromStream(IRandomAccessStream stream, bool autodetectEncoding)
 {
     if (stream.Size > MaxCueFileSize)
     {
         // Return empty list when file size exceeds the limit.
         return(new CueFile("", new List <ManagedAudioIndexCue>()));
     }
     if (!autodetectEncoding)
     {
         using (var mstream = stream.AsStreamForRead())
             using (var sr = new StreamReader(mstream))
                 return(CreateFromString(sr.ReadToEnd()));
     }
     else
     {
         using (var mstream = stream.AsStreamForRead())
         {
             int    length = (int)mstream.Length;
             byte[] bytes  = new byte[length];
             mstream.Read(bytes, 0, length);
             var charset  = Text.Chardet.DetectCodepage(bytes);
             var encoding = Encoding.GetEncoding(charset);
             if (encoding == null)
             {
                 encoding = Encoding.UTF8;
             }
             return(CreateFromString(encoding.GetString(bytes)));
         }
     }
 }
Пример #2
0
    public static async Task <IBuffer> StreamToBuffer(IRandomAccessStream stream)
    {
        var s = stream.AsStreamForRead();

        if (stream != null)
        {
            s = stream.AsStreamForRead();
            int    len = (int)s.Length;
            byte[] b   = new byte[(uint)s.Length];
            await s.ReadAsync(b, 0, len);

            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(b, 0, len);
            return(buffer);
        }
        return(null);
    }
Пример #3
0
 public static async Task CreateAndWriteToFileAsync(IRandomAccessStream contentStream, string path)
 {
     CreateParentDirectories(path);
     await using var stream = File.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
     contentStream.Seek(0);
     await contentStream.AsStreamForRead().CopyToAsync(stream);
 }
Пример #4
0
        /// <summary>
        /// ZIPデータを読み込みファイル一覧を作成する
        /// </summary>
        /// <returns></returns>
        public async Task LoadDataAsync()
        {
            this.Dispose();
            this.m_dataList.Clear();

            StorageFile zipFile = await StorageFile.GetFileFromPathAsync(m_imageParam.Path);

            StorageHistoryManager.AddStorage(zipFile, StorageHistoryManager.DataType.Latest);
            this.ParentStorage = zipFile;

            IRandomAccessStream randomStream = await zipFile.OpenReadAsync();

            Stream stream = randomStream.AsStreamForRead();

            m_zipArchive = new ZipArchive(stream);
            foreach (ZipArchiveEntry entry in m_zipArchive.Entries)
            {
                if (FileKind.IsImageFile(entry.FullName))
                {
                    m_dataList.Add(entry);
                }
            }
            sortList(m_dataList);

            //名前の順に並び替え
            foreach (ZipArchiveEntry entry in m_dataList)
            {
                Debug.WriteLine(entry.Name);
            }
        }
Пример #5
0
        public async Task <Stream> Encode()
        {
            try
            {
                Stopwatch stopwatchEncode = new Stopwatch();
                stopwatchEncode.Start();
                IRandomAccessStream imageStream   = (IRandomAccessStream) new InMemoryRandomAccessStream();
                BitmapEncoder       bitmapEncoder = await GraffitiEncoder.BuildEncoder(imageStream);

                BitmapPixelFormat pixelFormat;
                byte[]            imageBinaryData1 = GraffitiEncoder.GetImageBinaryData1(this._bitmap, out pixelFormat);
                int    num1        = (int)pixelFormat;
                int    num2        = 0;
                int    pixelWidth  = this._bitmap.PixelWidth;
                int    pixelHeight = this._bitmap.PixelHeight;
                double dpiX        = 72.0;
                double dpiY        = 72.0;
                byte[] pixels      = imageBinaryData1;
                bitmapEncoder.SetPixelData((BitmapPixelFormat)num1, (BitmapAlphaMode)num2, (uint)pixelWidth, (uint)pixelHeight, dpiX, dpiY, pixels);
                await bitmapEncoder.FlushAsync().AsTask().ConfigureAwait(false);

                long num3 = (long)imageStream.Size;
                stopwatchEncode.Stop();
                Execute.ExecuteOnUIThread((Action)(() => {}));
                return(imageStream.AsStreamForRead());
            }
            catch
            {
                return((Stream)null);
            }
        }
Пример #6
0
        public static async Task <List <Kategoria> > Import(StorageFile _fajl)
        {
            XLWorkbook wb = null;

            using (IRandomAccessStream s = await _fajl.OpenReadAsync())
                wb = new XLWorkbook(s.AsStreamForRead());

            IXLWorksheet     ws         = wb.Worksheet("Categories");
            List <Kategoria> kategoriak = new List <Kategoria>();

            foreach (var sor in ws.RangeUsed().RowsUsed())
            {
                if (sor.RowNumber() == 1)
                {
                    continue;
                }

                Kategoria kategoria = new Kategoria()
                {
                    ID         = sor.Cell(1).GetValue <int>(),
                    ParentID   = sor.Cell(2).GetValue <int>(),
                    Megnevezes = sor.Cell(4).GetString()
                };

                kategoriak.Add(kategoria);
            }

            return(kategoriak);
        }
        public void UpdateImage(IRandomAccessStream rass)
        {

            storage["Picture"] = new ParseFile("Picture.jpg", rass.AsStreamForRead());

            this.RaisePropertyChanged("Picture");
        }
Пример #8
0
        /// <summary>
        /// Load a given filename asynchronously
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task <T> LoadAsync(string fileName)
        {
            try
            {
                fileName = AppendExt(fileName);
                StorageFile file = null;
                file = await storageFolder.GetFileAsync(fileName);

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

                Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
                return((T)xmlSerializer.Deserialize(inStream));
            }
            catch (FileNotFoundException)
            {
                //file not existing is perfectly valid so simply return the default
                return(default(T));
                //throw;
            }
            catch (Exception)
            {
                //Unable to load contents of file
                throw;
            }
        }
Пример #9
0
        public async Task ReadExcuseAsync()
        {
            try
            {
                using (IRandomAccessStream stream =
                           await excuseFile.OpenAsync(FileAccessMode.Read))
                    using (Stream inputStream = stream.AsStreamForRead())
                    {
                        DataContractSerializer serializer
                                      = new DataContractSerializer(typeof(Excuse));
                        CurrentExcuse = serializer.ReadObject(inputStream) as Excuse;
                    }

                await new MessageDialog("Excuse read from to "
                                        + excuseFile.Name).ShowAsync();
                await UpdateFileDateAsync();
            }
            catch (SerializationException)
            {
                new MessageDialog("Unable to read " + excuseFile.Name).ShowAsync();
                NewExcuseAsync();
            }
            finally
            {
                OnPropertyChanged("CurrentExcuse");
            }
        }
        /// <summary>
        /// Chargement du contenu du fichier XML contenant
        /// les scores des joueurs dans une collection de joueurs
        /// </summary>
        public async void charger()
        {
            var       localFolder = ApplicationData.Current.LocalFolder;
            XDocument doc         = new XDocument();

            try
            {
                StorageFile textFile = await localFolder.GetFileAsync("scores.xml");

                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    Stream s = textStream.AsStreamForRead();
                    doc = XDocument.Load(s);

                    int nbJoueurs = doc.Root.Elements().Count();
                    var joueurs   = doc.Descendants("Joueur");
                    foreach (var joueur in joueurs)
                    {
                        string pseudo = joueur.Element("pseudo").Value;
                        int    score  = int.Parse(joueur.Element("score").Value);

                        Joueur leJoueur = new Joueur();
                        leJoueur.pseudo = pseudo;
                        leJoueur.score  = score;

                        tabScores.Add(leJoueur);
                    }
                    tabScores.Sort();
                }
            }
            catch { }
        }
Пример #11
0
        public static async Task <T> readObjektAsync <T>(string datei)
        {
            StorageFile         file;
            IRandomAccessStream inStream = null;

            try
            {
                file = await ApplicationData.Current.LocalFolder.GetFileAsync(datei);

                inStream = await file.OpenAsync(FileAccessMode.Read);

                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                var data = (T)serializer.ReadObject(inStream.AsStreamForRead());
                inStream.Dispose();

                return(data);
            }
            catch (Exception)
            {
                if (inStream != null)
                {
                    inStream.Dispose();
                }
                return(default(T));
            }
        }
Пример #12
0
        /// <summary>
        /// Load object from file
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task <T> LoadAsync(string fileName)
        {
            fileName = fileName + FileExtension;
            StorageFolder folder = await GetFolderAsync().ConfigureAwait(false);

            if (await folder.ContainsFileAsync(fileName).ConfigureAwait(false))
            {
                StorageFile file = await folder.GetFileAsync(fileName);

                string data;
                IRandomAccessStream accessStream = await file.OpenReadAsync();

                if (accessStream.Size == 0)
                {
                    return(default(T));
                }

                using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
                {
                    var content = new byte[stream.Length];
                    await stream.ReadAsync(content, 0, (int)stream.Length).ConfigureAwait(false);

                    data = Encoding.UTF8.GetString(content, 0, content.Length);
                }

                //Deserialize to object
                var result = JsonConvert.DeserializeObject <T>(data);

                return(result);
            }
            return(default(T));
        }
Пример #13
0
        public async Task LoadKHRSpecGlossGLTFFromStreamUWP()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            StorageFile   sampleFile  = await StorageFile.GetFileFromApplicationUriAsync(new Uri(GLTF_PBR_SPECGLOSS_PATH));


            IRandomAccessStream gltfStream = await sampleFile.OpenAsync(FileAccessMode.Read);

            var reader = new DataReader(gltfStream.GetInputStreamAt(0));
            await reader.LoadAsync((uint)gltfStream.Size);

            GLTFRoot gltfRoot = GLTFParser.ParseJson(gltfStream.AsStreamForRead());

            Assert.IsNotNull(gltfRoot.ExtensionsUsed);
            Assert.IsTrue(gltfRoot.ExtensionsUsed.Contains(KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME));

            Assert.IsNotNull(gltfRoot.Materials);
            Assert.AreEqual(1, gltfRoot.Materials.Count);
            Material materialDef = gltfRoot.Materials[0];
            KHR_materials_pbrSpecularGlossinessExtension specGloss = materialDef.Extensions[KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME] as KHR_materials_pbrSpecularGlossinessExtension;

            Assert.IsTrue(specGloss != null);

            Assert.AreEqual(Color.White, specGloss.DiffuseFactor);
            Assert.AreEqual(4, specGloss.DiffuseTexture.Index.Id);
            Assert.AreEqual(KHR_materials_pbrSpecularGlossinessExtension.SPEC_FACTOR_DEFAULT, specGloss.SpecularFactor);
            Assert.AreEqual(KHR_materials_pbrSpecularGlossinessExtension.GLOSS_FACTOR_DEFAULT, specGloss.GlossinessFactor);
            Assert.AreEqual(5, specGloss.SpecularGlossinessTexture.Index.Id);
        }
Пример #14
0
        private async Task <SavedData> retrieveSavedData()
        {
            SavedData     savedData     = new SavedData();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(SavedData));

            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(savedDataFileName);

                using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    if (writeStream.Size != 0)
                    {
                        using (XmlReader xmlReader = XmlReader.Create(writeStream.AsStreamForRead()))
                        {
                            savedData = xmlSerializer.Deserialize(xmlReader) as SavedData;

                            if (savedData == null)
                            {
                                savedData = new SavedData();
                            }
                        }
                    }
                }
            }
            catch (FileNotFoundException)
            {
                // EAT: The save game file doesn't exist, so a new one will be made later
            }

            return(savedData);
        }
Пример #15
0
        /// <summary>
        /// 读取本地文件夹根目录的文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>读取文件的内容</returns>
        public static async Task <string> ReadFileAsync(string fileName)
        {
            string text;

            try
            {
                // 获取存储数据的文件夹
                IStorageFolder applicationFolder = await GetDataFolder();

                // 根据文件名获取文件夹里面的文件
                IStorageFile storageFile = await applicationFolder.GetFileAsync(fileName);

                // 打开文件获取文件的数据流
                IRandomAccessStream accessStream = await storageFile.OpenReadAsync();

                // 使用StreamReader读取文件的内容,需要将IRandomAccessStream对象转化为Stream对象来初始化StreamReader对象
                using (StreamReader streamReader = new StreamReader(accessStream.AsStreamForRead((int)accessStream.Size)))
                {
                    text = streamReader.ReadToEnd();
                }
            }
            catch (Exception e)
            {
                text = "文件读取错误:" + e.Message;
            }
            return(text);
        }
Пример #16
0
        public async Task<IRandomAccessStream> GetThumbnailImage(IRandomAccessStream stream, int width, int height, bool smartCropping = true)
        {
            var response = await _client.GetThumbnailAsync(stream.AsStreamForRead(), width, height, smartCropping);

            var responseStream = new MemoryStream(response);
            return responseStream.AsRandomAccessStream();
        }
 public static async Task<ImgurEntity> UploadImgur(IRandomAccessStream fileStream)
 {
     try
     {
         var imageData = new byte[fileStream.Size];
         for (int i = 0; i < imageData.Length; i++)
         {
             imageData[i] = (byte)fileStream.AsStreamForRead().ReadByte();
         }
         var theAuthClient = new HttpClient();
         var request = new HttpRequestMessage(HttpMethod.Post, "https://api.imgur.com/3/image");
         request.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", "e5c018ac1f4c157");
         var form = new MultipartFormDataContent();
         var t = new StreamContent(fileStream.AsStream());
         // TODO: See if this is the correct way to use imgur's v3 api. I can't see why we would still need to convert images to base64.
         string base64Img = Convert.ToBase64String(imageData);
         t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
         form.Add(new StringContent(base64Img), @"image");
         form.Add(new StringContent("file"), "type");
         request.Content = form;
         HttpResponseMessage response = await theAuthClient.SendAsync(request);
         string responseString = await response.Content.ReadAsStringAsync();
         if (responseString == null) return null;
         var imgurEntity = JsonConvert.DeserializeObject<ImgurEntity>(responseString);
         return imgurEntity;
     }
     catch (WebException)
     {
     }
     catch (IOException)
     {
         return null;
     }
     return null;
 }
Пример #18
0
        public async Task <string> CreateMusicAlbumCoverFile(string name, IRandomAccessStream stream)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException($"“{nameof(name)}”不能为 null 或空。", nameof(name));
            }

            if (stream is null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            string        fileName = name.Replace(":", string.Empty).Replace("/", string.Empty).Replace("\\", string.Empty).Replace("?", string.Empty).Replace("*", string.Empty).Replace("|", string.Empty).Replace("\"", string.Empty).Replace("<", string.Empty).Replace(">", string.Empty);
            StorageFolder folder   = ApplicationData.Current.TemporaryFolder;

            if (await folder.FileExistsAsync($"{fileName}.png"))
            {
                return((await folder.GetFileAsync($"{fileName}.png")).Path);
            }
            StorageFile file = await folder.CreateFileAsync($"{fileName}.png", CreationCollisionOption.OpenIfExists);

            Stream fileStream = (await file.OpenAsync(FileAccessMode.ReadWrite)).AsStreamForWrite();
            Stream _stream    = stream.AsStreamForRead();

            _ = _stream.Seek(0, SeekOrigin.Begin);
            await _stream.CopyToAsync(fileStream);

            await fileStream.FlushAsync();

            fileStream.Dispose();
            return(file.Path);
        }
Пример #19
0
        public void TakePicture(int maxPixelDimension, int percentQuality, Action <Stream> pictureAvailable, Action assumeCancelled)
        {
            var dispatcher = this.GetService <IMvxViewDispatcherProvider>();

            dispatcher.Dispatcher.RequestMainThreadAction(
                async() =>
            {
                // Using Windows.Media.Capture.CameraCaptureUI API to capture a photo
                var dialog      = new CameraCaptureUI();
                var aspectRatio = new Size(16, 9);

                dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
                // HACK HACK!
                dialog.PhotoSettings.MaxResolution = CameraCaptureUIMaxPhotoResolution.SmallVga;
                dialog.PhotoSettings.Format        = CameraCaptureUIPhotoFormat.Jpeg;

                var file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
                if (file != null)
                {
                    BitmapImage bitmapImage = new BitmapImage();
                    var memoryStream        = new MemoryStream();
                    using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
                    {
                        var conventional = fileStream.AsStreamForRead();
                        conventional.CopyTo(memoryStream);
                    }
                    pictureAvailable(memoryStream);
                }
                else
                {
                    assumeCancelled();
                }
            });
        }
Пример #20
0
        /// <summary>
        /// Retrieve a stored instance of T with a specified handle from Windows.Storage.ApplicationData.
        /// Specification of a handle supports storage and deletion of different instances of T.
        /// </summary>
        /// <param name="Handle">User-defined handle for the stored object</param>
        public async Task <T> LoadAsync(string Handle)
        {
            if (Handle == null)
            {
                throw new ArgumentNullException("Handle");
            }

            string fileName = FileName(Activator.CreateInstance <T>(), Handle);

            try
            {
                StorageFile   file   = null;
                StorageFolder folder = GetFolder(storageType);
                file = await folder.GetFileAsync(fileName);

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

                using (Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result)
                {
                    return((T)serializer.Deserialize(inStream));
                }
            }
            catch (FileNotFoundException)
            {
                //file not existing is perfectly valid so simply return the default
                return(default(T));
                //Interesting thread here: How to detect if a file exists (http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/1eb71a80-c59c-4146-aeb6-fefd69f4b4bb)
                //throw;
            }
            catch (Exception)
            {
                //Unable to load contents of file
                throw;
            }
        }
        //</SnippetVertices>

        /// <summary>
        /// Fixes issue in API where textures are not saved correctly
        /// </summary>
        /// <param name="modelStream">3dmodel.model data</param>
        /// <returns></returns>
        private async Task <IRandomAccessStream> FixTextureContentType(IRandomAccessStream modelStream)
        {
            XDocument xmldoc = XDocument.Load(modelStream.AsStreamForRead());

            var outputStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var writer       = new Windows.Storage.Streams.DataWriter(outputStream);

            writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            writer.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;
            writer.WriteString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

            var text = xmldoc.ToString();
            // ensure that content type is set correctly
            // texture content can be either png or jpg
            var replacedText = text.Replace("contenttype=\"\"", "contenttype=\"image/png\"");

            writer.WriteString(replacedText);

            await writer.StoreAsync();

            await writer.FlushAsync();

            writer.DetachStream();
            return(outputStream);
        }
        public WindowsUniversalFileStream(string fileName, StorageFolder directory, FileAccessMode mode, CreationCollisionOption collisionOptions, StorageOpenOptions openOptions, int length = 1024 * 80, int writeBufferSize = 1024 * 80, int readBufferSize = 1024 * 80)
        {
            if (fileName == null || fileName == string.Empty)
            {
                throw new ArgumentNullException("path");
            }

            Directory        = directory;
            FileName         = fileName;
            Mode             = mode;
            CollisionOptions = collisionOptions;
            OpenOptions      = openOptions;

            WriteBufferSize = writeBufferSize;
            ReadBufferSize  = readBufferSize;

            RandomAccessStream = Directory.CreateFileAsync(FileName, collisionOptions).AsTask().Result.OpenAsync(mode, openOptions).AsTask().Result;
            ReadStream         = RandomAccessStream.AsStreamForRead(ReadBufferSize);
            ReadStream.SetLength(length);

            if (mode == FileAccessMode.ReadWrite)
            {
                WriteStream = RandomAccessStream.AsStreamForWrite(WriteBufferSize);
            }
        }
Пример #23
0
        /// <summary>
        /// アーカイブファイルからサムネイル用画像データを取得する
        /// </summary>
        /// <param name="path"></param>
        /// <param name="thumWidth"></param>
        /// <returns></returns>
        public static async Task <BitmapImage> GetFirstImageFromArchive(string path, int thumWidth)
        {
            BitmapImage bitmap  = null;
            StorageFile zipFile = await StorageFile.GetFileFromPathAsync(path);

            using (IRandomAccessStream randomStream = await zipFile.OpenReadAsync())
            {
                using (Stream stream = randomStream.AsStreamForRead())
                {
                    using (ZipArchive zipArchive = new ZipArchive(stream))
                    {
                        foreach (ZipArchiveEntry entry in zipArchive.Entries)
                        {
                            if (FileKind.IsImageFile(entry.FullName))
                            {
                                bitmap = await BitmapUtils.CreateBitmap(entry, thumWidth);

                                break;
                            }
                        }
                    }
                }
            }

            return(bitmap);
        }
Пример #24
0
        private async void OnCapturePhotoCompleted(IRandomAccessStream stream, IAsyncAction result, AsyncStatus status)
        {
            try
            {
                Stream streamCopy = stream.AsStreamForRead();
                streamCopy.Position = 0;
                Face[] faces = await _faceClient.DetectAsync(streamCopy);

                stream.Dispose();
                stream = null;
                bool userDetected = false;
                foreach (var face in faces)
                {
                    VerifyResult verifyResult = await _faceClient.VerifyAsync(face.FaceId, _groupId, _personId);

                    if (userDetected = verifyResult.IsIdentical)
                    {
                        break;
                    }
                }
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    if (userDetected && !_loggedOn)
                    {
                        txtGreeting.Text = "Hello!";
                        animGreeting.Begin();
                        _loggedOn                     = true;
                        imgLogoff.Visibility          = Windows.UI.Xaml.Visibility.Collapsed;
                        imgLogon.Visibility           = Windows.UI.Xaml.Visibility.Visible;
                        itmsCalendarEvents.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    }
                    else if (!userDetected && _loggedOn)
                    {
                        txtGreeting.Text = "Goodbye!";
                        animGreeting.Begin();
                        _loggedOn                     = false;
                        imgLogoff.Visibility          = Windows.UI.Xaml.Visibility.Visible;
                        imgLogon.Visibility           = Windows.UI.Xaml.Visibility.Collapsed;
                        itmsCalendarEvents.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    }
                });
            }
            catch (FaceAPIException e)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    txtException.Text = e.ErrorMessage;
                    animException.Begin();
                });
            }
            catch (Exception)
            {
                if (stream != null)
                {
                    stream.Dispose();
                    stream = null;
                }
            }
        }
Пример #25
0
        public static async Task <string> Sha1Async(this IRandomAccessStream randomAccessStream)
        {
            using var sha1 = SHA1.Create();
            var result = await sha1.ComputeHashAsync(randomAccessStream.AsStreamForRead());

            randomAccessStream.Seek(0); // reset the stream
            return(result.Select(b => b.ToString("x2")).Aggregate((acc, str) => acc + str));
        }
Пример #26
0
        public async Task <IRandomAccessStream> GetThumbnailImage(IRandomAccessStream stream, int width, int height, bool smartCropping = true)
        {
            var response = await _client.GetThumbnailAsync(stream.AsStreamForRead(), width, height, smartCropping);

            var responseStream = new MemoryStream(response);

            return(responseStream.AsRandomAccessStream());
        }
Пример #27
0
        /// <summary>
        /// Analyzes a bitmap image into a color palette.
        /// </summary>
        /// <param name="image">Bitmap Image.</param>
        /// <param name="width">Width of the image.</param>
        /// <param name="height">Hight of the image.</param>
        public async void Analyse(BitmapImage image, int width = 96, int height = 66)
        {
            RandomAccessStreamReference random = RandomAccessStreamReference.CreateFromUri(image.UriSource);
            IRandomAccessStream         str    = await random.OpenReadAsync();

            Analyse(str.AsStreamForRead(), width, height);
            str.Dispose();
        }
        /// <inheritdoc/>
        public async Task <IOneDriveStorageFile> UploadFileAsync(string desiredName, IRandomAccessStream content, CreationCollisionOption options = CreationCollisionOption.FailIfExists, int maxChunkSize = -1)
        {
            int currentChunkSize = maxChunkSize < 0 ? OneDriveUploadConstants.DefaultMaxChunkSizeForUploadSession : maxChunkSize;

            if (currentChunkSize % OneDriveUploadConstants.RequiredChunkSizeIncrementForUploadSession != 0)
            {
                throw new ArgumentException("Max chunk size must be a multiple of 320 KiB", nameof(maxChunkSize));
            }

            if (string.IsNullOrEmpty(desiredName))
            {
                throw new ArgumentNullException(nameof(desiredName));
            }

            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            var uploadSessionUri = $"{Provider.BaseUrl}/drive/items/{OneDriveItem.Id}:/{desiredName}:/oneDrive.createSession";

            var conflictBehavior = new OneDriveItemConflictBehavior {
                Item = new OneDriveConflictItem {
                    ConflictBehavior = OneDriveHelper.TransformCollisionOptionToConflictBehavior(options.ToString())
                }
            };

            var jsonConflictBehavior   = JsonConvert.SerializeObject(conflictBehavior);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uploadSessionUri)
            {
                Content = new StringContent(jsonConflictBehavior, Encoding.UTF8, "application/json")
            };
            await Provider.AuthenticationProvider.AuthenticateRequestAsync(request).ConfigureAwait(false);

            var response = await Provider.HttpProvider.SendAsync(request).ConfigureAwait(false);

            if (!response.IsSuccessStatusCode)
            {
                throw new ServiceException(new Error {
                    Message = "Could not create an UploadSession", Code = "NoUploadSession", ThrowSite = "UWP Community Toolkit"
                });
            }

            IsUploadCompleted = false;
            var jsonData = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            _uploadSession = JsonConvert.DeserializeObject <Microsoft.OneDrive.Sdk.UploadSession>(jsonData);

            var streamToUpload = content.AsStreamForRead();

            _uploadProvider = new Microsoft.OneDrive.Sdk.Helpers.ChunkedUploadProvider(_uploadSession, Provider, streamToUpload, maxChunkSize);

            var uploadedItem = await _uploadProvider.UploadAsync().ConfigureAwait(false);

            IsUploadCompleted = true;

            return(InitializeOneDriveStorageFile(uploadedItem.CopyToDriveItem()));
        }
 /// <summary>
 /// Constructs a Logo from a WinRT Stream.
 /// </summary>
 /// <param name="imageStream">A stream containing a valid image</param>
 public LogoSource(IRandomAccessStream imageStream)
 {
     if (imageStream == null)
     {
         throw new ArgumentNullException("imageStream");
     }
     _stream     = imageStream.AsStreamForRead();
     _ownsStream = true;
 }
        public virtual async void Consume(IRandomAccessStream stream)
        {
            using (stream)
            {
                using var gifStream = await IOHelper.GetGifStreamFromZipStreamAsync(stream.AsStreamForRead(), _metadata);

                await IOHelper.CreateAndWriteToFileAsync(gifStream, Destination);
            }
        }
Пример #31
0
        public async Task <bool> UploadFileAsync(StorageFile localFile, CancellationToken cancellationToken)
        {
            if (!await IsAuthenticatedAsync().ConfigureAwait(false))
            {
                return(false);
            }

            try
            {
                bool uploadSucceeded = await CoreHelper.RetryAsync(async() =>
                {
                    using (await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false))
                        using (IRandomAccessStream localFileContent = await localFile.OpenReadAsync())
                            using (Stream localFileContentStream = localFileContent.AsStreamForRead())
                            {
                                FileMetadata uploadResult = null;
                                long localFileSize        = localFileContentStream.Length;

                                int chunksCount = (int)Math.Ceiling((double)localFileSize / TransferBufferSize);

                                if (chunksCount <= 1)
                                {
                                    // File is too small for uploading by chunks. Let's upload in 1 shot.
                                    uploadResult = await _dropboxClient.Files.UploadAsync(
                                        new CommitInfo(
                                            path: "/" + localFile.Name,
                                            mode: WriteMode.Overwrite.Instance),
                                        localFileContentStream)
                                                   .ConfigureAwait(false);
                                }
                                else
                                {
                                    // For files > 150 MB, UploadAsync won't work, so we use an upload session in case.
                                    // It is unlikely that a user data file will be 150 MB but we never know.
                                    // In fact, here we use upload session for any file bigger than the TransferBufferSize.
                                    uploadResult = await UploadFileInChunksAsync(
                                        chunksCount,
                                        localFileContentStream,
                                        localFile.Name)
                                                   .ConfigureAwait(false);
                                }

                                return(uploadResult != null && uploadResult.Size == (ulong)localFileSize);
                            }
                }).ConfigureAwait(false);

                _logger.LogEvent(UploadFileEvent, $"Upload succeeded == {uploadSucceeded}");

                return(uploadSucceeded);
            }
            catch (Exception ex)
            {
                _logger.LogFault(UploadFileFaultEvent, "Unable to upload a file.", ex);
                return(false);
            }
        }
Пример #32
0
        public static byte[] ReadStreamToByteArray(this IRandomAccessStream oriStream)
        {
            var stream = oriStream.AsStreamForRead();

            stream.Seek(0, SeekOrigin.Begin);
            var data = new byte[stream.Length];

            stream.Read(data, 0, (int)stream.Length);
            return(data);
        }
Пример #33
0
        public static async Task <byte[]> ToByteArray(this IRandomAccessStream accessStream)
        {
            var stream = accessStream.AsStreamForRead();

            byte[] array = new byte[stream.Length];

            await stream.ReadAsync(array, 0, array.Length);

            return(array);
        }
Пример #34
0
        public async Task<string> GetPrevalentEmotion(IRandomAccessStream imageStream)
        {
            var result = await _client.RecognizeAsync(imageStream.AsStreamForRead());

            var emotionScores = typeof(Microsoft.ProjectOxford.Emotion.Contract.Scores).GetProperties()
                .Where(p => p.PropertyType == typeof(float))
                .Select(p => new { Name = p.Name, Score = (float)p.GetValue(result[0].Scores) });
                

            return emotionScores.OrderByDescending(s => s.Score).Select(s => s.Name).FirstOrDefault();
        }
 /// <summary>
 /// Pictures Libraryへファイルを保存する
 /// 既存の同名ファイルが存在している場合はファイルを上書きする
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="stream">エンコード済みの画像ストリーム</param>
 /// <returns></returns>
 public static async Task<StorageFile> SaveToPicturesLibraryAsync(string fileName, IRandomAccessStream stream)
 {
     var library = KnownFolders.PicturesLibrary;
     var file = await library.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
     using (var writeStrm = await file.OpenStreamForWriteAsync())
     {
         var readStrm = stream.AsStreamForRead();
         readStrm.CopyTo(writeStrm);
     }
     return file;
 }
        public async override Task<bool> SaveAsync(string cacheKey, IRandomAccessStream cacheStream)
        {
            var fullFileName = Path.Combine(CacheDirectory, CacheFileNameGenerator.GenerateCacheName(cacheKey));
            var cacheSizeInBytes = cacheStream.AsStreamForRead().Length;

            while (CurrentCacheSizeInBytes + cacheSizeInBytes > _cacheLimitInBytes)
            {
                if (!await RemoveOldestCacheFile())
                {
                    break; // All cache deleted
                }
            }

            var wasFileSaved = await base.InternalSaveAsync(fullFileName, cacheStream);

            if (wasFileSaved)
            {
                _lastAccessTimeDictionary[Path.Combine(CacheDirectory, fullFileName)] = DateTimeHelper.CurrentTimeMillis();
                CurrentCacheSizeInBytes += cacheSizeInBytes; // Updating current cache size
            }

            return wasFileSaved;
        }
Пример #37
0
        public async Task<string> RecognizeTextAsync(IRandomAccessStream stream, string language = "unk", bool detectOrientation = true)
        {
            var response = await _client.RecognizeTextAsync(stream.AsStreamForRead(), language, detectOrientation);

            return response.Regions.SelectMany(r => r.Lines).SelectMany(l => l.Words).Select(w => w.Text).StringJoin(" ");
        }
Пример #38
0
    private async Task<IRandomAccessStream> FixTextureContentType(IRandomAccessStream modelStream)
    {
        XDocument xmldoc = XDocument.Load(modelStream.AsStreamForRead());

        var outputStream = new Windows.Storage.Streams.InMemoryRandomAccessStream();
        var writer = new Windows.Storage.Streams.DataWriter(outputStream);
        writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
        writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

        var text = xmldoc.ToString();

        var replacedText = text.Replace("contenttype=\"\"", "contenttype=\"image/png\"");
        writer.WriteString(replacedText);

        await writer.StoreAsync();
        await writer.FlushAsync();
        writer.DetachStream();
        return outputStream;
    }
Пример #39
0
        public LoadResult Load(IRandomAccessStream lineStream)
        {
            StartLoad(lineStream.AsStreamForRead());

            return CreateResult();
        }