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  = ((BitmapSource)this._bitmap).PixelWidth;
                int    pixelHeight = ((BitmapSource)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 WindowsRuntimeSystemExtensions.AsTask(bitmapEncoder.FlushAsync()).ConfigureAwait(false);

                long size = (long)imageStream.Size;
                stopwatchEncode.Stop();
                Execute.ExecuteOnUIThread((Action)(() => {}));
                return(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)imageStream));
            }
            catch
            {
                return(null);
            }
        }
        /// <summary>
        /// 通过转成byte[]来实现图片储存,但不知道为什么就是不好用,得到得图片颜色配置不正确。
        /// 会不会因为方法将所有像素数据视为sRGB 颜色空间中的像素数据?
        /// </summary>
        /// <param name="thumbnail"></param>
        /// <returns></returns>
        private async Task SaveWizPixelAsync(StorageItemThumbnail thumbnail)
        {
            Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(thumbnail.GetInputStreamAt(0));

            byte[] buffer = new byte[thumbnail.Size];
            // byte[] pixelbytes;
            using (MemoryStream ms = new MemoryStream())
            {
                stream.Read(buffer, 0, buffer.Length);
            }
            #region 测试得到的buffer是否完整 结果是使用buffer生成的IrandomAccessTream来为BitmapImage.SetValue()提供参数,显示正常。
            //InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream();
            //DataWriter datawriter = new DataWriter(memoryStream.GetOutputStreamAt(0));
            //datawriter.WriteBytes(buffer);
            //await datawriter.StoreAsync();
            #endregion

            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("Testimage.jpg", CreationCollisionOption.GenerateUniqueName);

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

                encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                     BitmapAlphaMode.Premultiplied
                                     thumbnail.OriginalWidth,
                                     thumbnail.OriginalHeight,
                                     DisplayInformation.GetForCurrentView().LogicalDpi,
                                     DisplayInformation.GetForCurrentView().LogicalDpi,
                                     buffer);
                await encoder.FlushAsync();
            }
        }
Exemple #3
0
 public static IEnumerable <string> ReadLines(string path)
 {
     if (string.IsNullOrWhiteSpace(path))
     {
         throw new ArgumentException();
     }
     try
     {
         IAsyncOperation <IRandomAccessStream> source = FileHelper.GetFileForPathOrURI(path).OpenAsync(FileAccessMode.Read);
         WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStream>(source).Wait();
         using (FileRandomAccessStream randomAccessStream = (FileRandomAccessStream)source.GetResults())
         {
             StreamReader  streamReader = new StreamReader(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)randomAccessStream));
             List <string> list         = new List <string>();
             while (true)
             {
                 string str = streamReader.ReadLine();
                 if (str != null)
                 {
                     list.Add(str);
                 }
                 else
                 {
                     break;
                 }
             }
             return((IEnumerable <string>)list);
         }
     }
     catch (Exception ex)
     {
         throw File.GetRethrowException(ex);
     }
 }
Exemple #4
0
        /// <summary>
        /// 保存远程url地址图片,到本地
        /// </summary>
        /// <param name="uri">远程地址</param>
        /// <param name="filename">保存的名称</param>
        /// <param name="folder">保存位置枚举</param>
        /// <returns></returns>
        internal async static Task SaveImageFromUrl(string uri, string filename, StorageFolder folder)
        {
            var rass = RandomAccessStreamReference.CreateFromUri(new Uri(uri));
            IRandomAccessStream inputStream = await rass.OpenReadAsync();

            Stream input = WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream.GetInputStreamAt(0));

            try
            {
                //获取图片扩展名的Guid
                StorageFile outputFile = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                using (IRandomAccessStream outputStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    Stream output = WindowsRuntimeStreamExtensions.AsStreamForWrite(outputStream.GetOutputStreamAt(0));
                    await input.CopyToAsync(output);

                    output.Dispose();
                    input.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #5
0
        internal ImageSource GetActualImageSource()
        {
            if (_imageSource != null)
            {
                return(_imageSource);
            }

            if (_uriSource != null)
            {
                // hdt
                BitmapImage imageSource = new BitmapImage();
                StorageFile.GetFileFromApplicationUriAsync(_uriSource).AsTask().ContinueWith((fr) =>
                {
                    if ((fr.Result != null) && !fr.IsFaulted)
                    {
                        Action <Task <IRandomAccessStreamWithContentType> > func = delegate(Task <IRandomAccessStreamWithContentType> r)
                        {
                            using (Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(r.Result))
                            {
                                // Utility.InitImageSource(imageSource, stream);
                                //导出RptText ImageUri时图片不出问题 李雪修改
                                InitImageSource(stream);
                            }
                        };
                        WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStreamWithContentType>(fr.Result.OpenReadAsync()).ContinueWith(func);
                    }
                });
                return(imageSource);
            }
            return(null);
        }
Exemple #6
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.ConPPT.IsEnabled = false;
            Client = Connect.Client;
            changlanguage();
            Client.SendCommand("data?");
            if (e.NavigationMode == NavigationMode.Back && PickFiles.PickedFiles.Count > 0)
            {
                StorageFile         file       = PickFiles.PickedFiles[0];
                IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);

                Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(fileStream.GetInputStreamAt(0));
                byte[] bt     = ConvertStreamTobyte(stream);

                Client.SendCommand("FileName|" + file.Name);
                Thread.Sleep(1000);
                Client.SendCommand(bt);

                string[] type = file.Name.Split('.');
                if (type[type.Length - 1] == "ppt")
                {
                    this.ConPPT.IsEnabled = true;
                }
            }
        }
Exemple #7
0
        public async Task <IRandomAccessStream> StartDownload(Uri uri)
        {
            byte[] bytes = null;
            TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, 0, bytes));
            cts = new CancellationTokenSource();
            DownloadBytesCount = new DownLoadBytes();

            var stream = await GetAsyncStreamDownLoad(uri, cts.Token);

            if (!cts.IsCancellationRequested && stream != null)
            {
                using (stream)
                {
                    var randomAccessStream = new InMemoryRandomAccessStream();
                    var outputStream       = randomAccessStream.GetOutputStreamAt(0);
                    await RandomAccessStream.CopyAsync(stream.AsInputStream(), outputStream);

                    DownloadBytesCount.BytesReceived = Convert.ToInt64(randomAccessStream.Size);
                    var    randomAccessStreamTemp = randomAccessStream.CloneStream();
                    Stream streamTemp             = WindowsRuntimeStreamExtensions.AsStreamForRead(randomAccessStreamTemp.GetInputStreamAt(0));
                    var    bytesTemp = ConvertStreamTobyte(streamTemp);
                    TriggerDownLoadChanging(new DownLoadChangingEventArgs(DownloadBytesCount, 100, bytesTemp));
                    //TriggerDownLoadComplete(new DownLoadCompleteEventArgs(randomAccessStream));
                    TriggerDownLoadComplete(new DownLoadCompleteEventArgs(randomAccessStream.CloneStream()));
                    return(randomAccessStream as IRandomAccessStream);
                }
            }
            return(null);
        }
Exemple #8
0
        /// <summary>
        /// IRandomAccessStream转换为bytes
        /// </summary>
        /// <param name="randomAccessStream"></param>
        /// <returns></returns>
        public static async Task <byte[]> AccessStreamToBytesAsync(IRandomAccessStream randomAccessStream)
        {
            Stream       stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomAccessStream.GetInputStreamAt(0));
            MemoryStream ms     = new MemoryStream();
            await stream.CopyToAsync(ms);

            return(ms.ToArray());
        }
Exemple #9
0
        /// <summary>
        /// 网络图片Uri转换成流
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        internal async static Task <Stream> UriToStream(string uri)
        {
            var rass = RandomAccessStreamReference.CreateFromUri(new Uri(uri));
            IRandomAccessStream inputStream = await rass.OpenReadAsync();

            Stream input = WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream.GetInputStreamAt(0));

            return(input);
        }
Exemple #10
0
        private async void VoiceCaptureButton_Click(object sender, RoutedEventArgs e)
        {
            string output;

            //开始录音
            if (VoiceRecordSym == true)
            {
                _memoryBuffer = new InMemoryRandomAccessStream();
                VoiceCaptureButton.FontFamily = new FontFamily("Segoe UI");
                VoiceCaptureButton.Content    = "停止录音";
                VoiceRecordSym = false;
                if (IsRecording)
                {
                    throw new InvalidOperationException("Recording already in progress!");
                }
                MediaCaptureInitializationSettings settings =
                    new MediaCaptureInitializationSettings
                {
                    StreamingCaptureMode = StreamingCaptureMode.Audio
                };
                _mediaCapture = new MediaCapture();
                await _mediaCapture.InitializeAsync(settings);

                //将录音文件存入_memoryBuffer里面
                await _mediaCapture.StartRecordToStreamAsync(MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto), _memoryBuffer);

                IsRecording = true;
            }
            //停止录音
            else
            {
                await _mediaCapture.StopRecordAsync();

                IsRecording = false;
                VoiceCaptureButton.FontFamily = new FontFamily("Segoe MDL2 Assets");
                VoiceCaptureButton.Content    = "\xE1D6";
                VoiceRecordSym       = true;
                progessRing.IsActive = true;
                Input.IsReadOnly     = true;
                //转换InMemoryRandomAccessStream成Stream
                Stream tempStream = WindowsRuntimeStreamExtensions.AsStreamForRead(_memoryBuffer.GetInputStreamAt(0));
                using (var stream = new MemoryStream())
                {
                    tempStream.CopyTo(stream);
                    VoiceToText voiceToText = new VoiceToText();
                    //传入VoiceToText函数
                    output = await voiceToText.ReadVoice(stream, "yue");
                }
                //tempStream.Position = 0;
                progessRing.IsActive = false;
                Input.IsReadOnly     = false;
                Input.Text          += output;
            }
        }
Exemple #11
0
        public static async Task <string> GetTestData(string filePath)
        {
            var folder = Package.Current.InstalledLocation;
            var file   = await folder.GetFileAsync(filePath);

            var openFile = await file.OpenReadAsync();

            var reader = new StreamReader(WindowsRuntimeStreamExtensions.AsStreamForRead(openFile));

            return(await reader.ReadToEndAsync());
        }
Exemple #12
0
        internal static Stream OpenFileForReading(StorageFile file)
        {
            Task <IRandomAccessStream> task = WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStream>(file.OpenAsync(FileAccessMode.Read));

            task.Wait();
            if (task.Status != TaskStatus.RanToCompletion)
            {
                throw new Exception("Failed to open file!");
            }
            else
            {
                return(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)task.Result));
            }
        }
        public static async Task <Point> GetPixelWidthAndHeight(this IRandomAccessStream iRandomAccessStream)
        {
            var    tempIRandomAccessStream = iRandomAccessStream.CloneStream();
            Stream inputStream             = WindowsRuntimeStreamExtensions.AsStreamForRead(tempIRandomAccessStream.GetInputStreamAt(0));
            var    copiedBytes             = ConvertStreamTobyte(inputStream);
            Stream tempStream = new MemoryStream(copiedBytes);

            Guid      decoderId = Guid.Empty;
            ImageType type      = ImageTypeCheck.CheckImageType(copiedBytes);

            switch (type)
            {
            case ImageType.GIF:
            {
                break;
            }

            case ImageType.JPG:
            {
                decoderId = BitmapDecoder.JpegDecoderId;
                break;
            }

            case ImageType.PNG:
            {
                decoderId = BitmapDecoder.PngDecoderId;
                break;
            }

            default:
            {
                break;
            }
            }

            var randomAccessStream = new InMemoryRandomAccessStream();
            var outputStream       = randomAccessStream.GetOutputStreamAt(0);
            await RandomAccessStream.CopyAsync(tempStream.AsInputStream(), outputStream);

            var bitDecoder = await BitmapDecoder.CreateAsync(decoderId, randomAccessStream);

            var frame = await bitDecoder.GetFrameAsync(0);

            Point point = new Point();

            point.X = frame.PixelWidth;
            point.Y = frame.PixelHeight;
            return(point);
        }
        /**
         * Extracts image pixels into byte array "pixels"
         */
        protected void GetImagePixels(IRandomAccessStream iRandomAccessStream)
        {
            /*Point pointWH = await WriteableBitmapExpansion.GetPixelWidthAndHeight(iRandomAccessStream);
             * int w = (int)pointWH.X;
             * int h = (int)pointWH.Y;*/
            int count = 0;

            byte[] tempByte = null;

            /*
             * //进行统一尺寸的格式压缩
             * if ((w != width)
             || (h != height)
             || )
             ||{
             || var bytes = await WriteableBitmapExpansion.ResizeBytes(iRandomAccessStream, width, height, BitmapInterpolationMode.Cubic);
             || pixels = new Byte[3 * width * height];
             || pointWH = new Point(width, height);
             || tempByte = bytes;
             ||}
             ||else
             ||{
             || pointWH = await WriteableBitmapExpansion.GetPixelWidthAndHeight(imageIAStream);
             || pixels = new Byte[3 * (int)pointWH.X * (int)pointWH.Y];
             || tempByte = await WriteableBitmapExpansion.WriteableBitmapToBytes(imageIAStream);
             ||}
             */

            pixels = new Byte[3 * (int)width * (int)height];
            /*tempByte = await WriteableBitmapExpansion.WriteableBitmapToBytes(imageIAStream);*/
            Stream inputStream = WindowsRuntimeStreamExtensions.AsStreamForRead(imageIAStream.GetInputStreamAt(0));

            tempByte = inputStream.ConvertStreamTobyte();

            for (int th = 0; th < height; th++)
            {
                for (int tw = 0; tw < width; tw++)
                {
                    Color color = WriteableBitmapExpansion.GetPixel(tempByte, Convert.ToInt32(width), tw, th);
                    pixels[count] = color.R;
                    count++;
                    pixels[count] = color.G;
                    count++;
                    pixels[count] = color.B;
                    count++;
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Gets the image.
        /// </summary>
        /// <param name="source">The source</param>
        /// <returns></returns>
        internal Image GetImage(ImageSource source)
        {
            if (source == null)
            {
                return(null);
            }
            if (this.imageCaches.ContainsKey(source))
            {
                return(this.imageCaches[source]);
            }
            Windows.UI.Xaml.Media.Imaging.BitmapImage image = source as Windows.UI.Xaml.Media.Imaging.BitmapImage;
            Stream stream = null;

            try
            {
                if ((image != null) && (image.UriSource != null))
                {
                    try
                    {
                        Uri uri1 = ((Windows.UI.Xaml.Media.Imaging.BitmapImage)source).UriSource;
                        Uri uri  = new Uri("ms-appx:///" + uri1.LocalPath.TrimStart(new char[] { '/' }));
                        stream = WindowsRuntimeStreamExtensions.AsStreamForRead(StorageFile.GetFileFromApplicationUriAsync(uri).GetResultSynchronously <StorageFile>().OpenSequentialReadAsync().GetResultSynchronously <IInputStream>());
                    }
                    catch (Exception)
                    {
                        stream = Utility.GetImageStream(source, ImageFormat.Png, PictureSerializationMode.Normal);
                    }
                }
                else if (image != null)
                {
                    stream = Utility.GetImageStream(source, ImageFormat.Png, PictureSerializationMode.Normal);
                }
                if (stream != null)
                {
                    byte[] buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, buffer.Length);
                    Image instance = Image.GetInstance(buffer);
                    this.imageCaches.Add(source, instance);
                    stream.Dispose();
                    return(instance);
                }
                return(null);
            }
            catch
            {
                return(null);
            }
        }
Exemple #16
0
        public static IBuffer ToBuffer(this IRandomAccessStream randomStream)
        {
            Stream stream       = WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0));
            var    memoryStream = new MemoryStream();

            if (stream != null)
            {
                byte[] bytes = stream.ToByteArray();
                if (bytes != null)
                {
                    var binaryWriter = new BinaryWriter(memoryStream);
                    binaryWriter.Write(bytes);
                }
            }
            return(WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, (int)memoryStream.Length));
        }
Exemple #17
0
        //合成数据
        private byte[] Combine(IRandomAccessStream iRandomAccessStream)
        {
            Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(iRandomAccessStream.GetInputStreamAt(0));

            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                Bytes.AddRange(ms.ToArray());
                return(Bytes.ToArray());
            }
        }
Exemple #18
0
        /// <summary>
        /// 检测上一次同步的时间,并于本机同步时间比对
        /// </summary>
        /// <returns>相同返回<c>True</c>,不同返回<c>False</c></returns>
        public async Task <bool> CheckLastAsync()
        {
            if (_appFolder == null)
            {
                throw new UnauthorizedAccessException("You need to complete OneDrive authorization before you can upload the image");
            }
            try
            {
                var historyFile = await _appFolder.GetFileAsync("LastAsyncTime");

                using (var stream = (await historyFile.StorageFilePlatformService.OpenAsync()) as IRandomAccessStream)
                {
                    Stream st = WindowsRuntimeStreamExtensions.AsStreamForRead(stream);
                    st.Position = 0;
                    StreamReader sr     = new StreamReader(st, Encoding.UTF8);
                    string       result = sr.ReadToEnd();
                    result = result.Replace("\0", "");
                    if (string.IsNullOrEmpty(result))
                    {
                        return(true);
                    }
                    else
                    {
                        try
                        {
                            int cloudTime = Convert.ToInt32(result);
                            int localTime = Convert.ToInt32(AppTools.GetLocalSetting(AppSettings.SyncTime, "0"));
                            if (cloudTime != localTime)
                            {
                                return(false);
                            }
                            return(true);
                        }
                        catch (Exception)
                        {
                            return(true);
                        }
                    }
                }
            }
            catch (Exception)
            {
                await _appFolder.StorageFolderPlatformService.CreateFileAsync("LastAsyncTime", CreationCollisionOption.OpenIfExists);

                return(true);
            }
        }
Exemple #19
0
 public static string ReadAllText(string path)
 {
     if (string.IsNullOrWhiteSpace(path))
     {
         throw new ArgumentException();
     }
     try
     {
         IAsyncOperation <IRandomAccessStream> source = FileHelper.GetFileForPathOrURI(path).OpenAsync(FileAccessMode.Read);
         WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStream>(source).Wait();
         using (FileRandomAccessStream randomAccessStream = (FileRandomAccessStream)source.GetResults())
             return(new StreamReader(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)randomAccessStream)).ReadToEnd());
     }
     catch (Exception ex)
     {
         throw File.GetRethrowException(ex);
     }
 }
Exemple #20
0
        public static IBuffer RandomAccessStream2Buffer(IRandomAccessStream randomStream)
        {
            Stream       stream       = WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0));
            MemoryStream memoryStream = new MemoryStream();

            if (stream != null)
            {
                byte[] bytes = Stream2Bytes(stream);
                if (bytes != null)
                {
                    var binaryWriter = new BinaryWriter(memoryStream);
                    binaryWriter.Write(bytes);
                }
            }
            IBuffer buffer = WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(memoryStream, 0, (int)memoryStream.Length);

            return(buffer);
        }
Exemple #21
0
    public static async Task <Int32> ReadMusicData()
    {
        Int32 num;

        try
        {
            StorageFile fileAsync = await ApplicationData.Current.LocalFolder.GetFileAsync(readwrite.filename);

            IInputStream inputStream = await fileAsync.OpenSequentialReadAsync();

            try
            {
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(MusicData));
                App.musicdata = dataContractSerializer.ReadObject(WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream)) as MusicData;
            }
            finally
            {
                if (inputStream != null)
                {
                    inputStream.Dispose();
                }
            }
        }
        catch (FileNotFoundException fileNotFoundException)
        {
            App.musicdata = new MusicData();
            num           = 1;
            return(num);
        }
        catch (Exception exception1)
        {
            Exception exception = exception1;

            App.ShowError(String.Concat("Error while reading music data: ", exception.Message.ToString()));
            App.musicdata = new MusicData();
            num           = 1;
            return(num);
        }
        Boolean flag = await App.musicdata.CheckForNewMusic();

        num = (!flag ? 0 : 2);
        return(num);
    }
Exemple #22
0
        private async void takePhoto()
        {
            try
            {
                ImageEncodingProperties imageProp = ImageEncodingProperties.CreateJpeg();
                IRandomAccessStream     uwpStream = new InMemoryRandomAccessStream();
                await camera.CapturePhotoToStreamAsync(imageProp, uwpStream);

                Emotion[] emotionResult = await UploadAndDetectEmotions(
                    WindowsRuntimeStreamExtensions.AsStreamForRead(
                        uwpStream.GetInputStreamAt(0)));

                ledDriver(emotionResult[0]);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemple #23
0
        public async static Task <string> GetBase64(StorageFile imagefile)
        {
            string strbaser64 = "";

            try
            {
                IRandomAccessStream iras = await imagefile.OpenReadAsync();

                Stream       stream = WindowsRuntimeStreamExtensions.AsStreamForRead(iras.GetInputStreamAt(0));
                MemoryStream ms     = new MemoryStream();
                await stream.CopyToAsync(ms);

                byte[] arr = ms.ToArray();
                ms.Dispose();
                strbaser64 = Convert.ToBase64String(arr);
            }
            catch { }

            return(strbaser64);
        }
Exemple #24
0
        /// <summary>
        /// 强制执行云端数据同步,并将同步时间写入记录
        /// </summary>
        /// <returns></returns>
        public async Task SyncCloud()
        {
            if (_appFolder == null)
            {
                throw new UnauthorizedAccessException("You need to complete OneDrive authorization before you can upload the image");
            }
            await ReplaceDatabase();

            var historyFile = await _appFolder.GetFileAsync("LastAsyncTime");

            using (var stream = (await historyFile.StorageFilePlatformService.OpenAsync()) as IRandomAccessStream)
            {
                Stream st = WindowsRuntimeStreamExtensions.AsStreamForRead(stream);
                st.Position = 0;
                StreamReader sr     = new StreamReader(st, Encoding.UTF8);
                string       result = sr.ReadToEnd();
                result = string.IsNullOrEmpty(result) ? "0" : result;
                AppTools.WriteLocalSetting(AppSettings.SyncTime, result);
            }
        }
Exemple #25
0
        private async Task <string> ProcessStreamWithMLEdgeAsync(InMemoryRandomAccessStream stream)
        {
            string sret = null;

            try
            {
                HttpContent httpContent = new StreamContent(WindowsRuntimeStreamExtensions.AsStreamForRead(stream.GetInputStreamAt(0)));
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                HttpRequestMessage RequestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri("http://" + AIEndPointIP + ":" + AIEndPointPort + "/image"));
                RequestMessage.Content = httpContent;
                var httpClient = new HttpClient();
                HttpResponseMessage response = await httpClient.SendAsync(RequestMessage);

                if (response.IsSuccessStatusCode)
                {
                    sret = await response.Content.ReadAsStringAsync();

                    //WriteLog(sret);
                    //WriteLog("Connected!");
                    return(sret);
                }
                else
                {
                    WriteLog(string.Format("The request failed with status code: {0}", response.StatusCode));

                    WriteLog(response.Headers.ToString());

                    string responseContent = await response.Content.ReadAsStringAsync();

                    WriteLog(responseContent);
                    WriteLog("Disconnect!");
                }
            }
            catch (Exception ex)
            {
                //WriteLog(ex.Message);
                //WriteLog( "Disconnect!");
            }
            return(sret);
        }
Exemple #26
0
        /// <summary>
        /// 获取OneDrive中存储的Rss列表数据
        /// </summary>
        /// <returns></returns>
        public async Task <List <Category> > GetCategoryList()
        {
            if (_appFolder == null)
            {
                throw new UnauthorizedAccessException("You need to complete OneDrive authorization before you can get this file");
            }
            try
            {
                var file = await _appFolder.GetFileAsync("RssList.json");

                using (var stream = (await file.StorageFilePlatformService.OpenAsync()) as IRandomAccessStream)
                {
                    Stream st = WindowsRuntimeStreamExtensions.AsStreamForRead(stream);
                    st.Position = 0;
                    StreamReader sr     = new StreamReader(st, Encoding.UTF8);
                    string       result = sr.ReadToEnd();
                    result = result.Replace("\0", "");
                    if (string.IsNullOrEmpty(result))
                    {
                        result = "[]";
                    }
                    var list = JsonConvert.DeserializeObject <List <Category> >(result);
                    return(list);
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToLower().Contains("itemnotfound"))
                {
                    await _appFolder.StorageFolderPlatformService.CreateFileAsync("RssList.json", CreationCollisionOption.ReplaceExisting);

                    return(new List <Category>());
                }
                throw;
            }
        }
Exemple #27
0
        static async void OnDocumentUriChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var excel = (Excel)d;
            Uri uri   = (Uri)e.NewValue;

            if (uri == null)
            {
                return;
            }

            var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

            using (Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(await file.OpenReadAsync()))
            {
                if (file.FileType == ".ssxml" || file.FileType == ".xml")
                {
                    await excel.OpenXml(stream);
                }
                else if (file.FileType == ".xlsx" || file.FileType == ".xls")
                {
                    await excel.OpenExcel(stream);
                }
            }
        }
Exemple #28
0
        public static Stream RandomAccessStream2Stream(IRandomAccessStream randomStream)
        {
            Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomStream.GetInputStreamAt(0));

            return(stream);
        }
Exemple #29
0
        private async void uploadAsync(string providerName, string token, string cloudFolder, string chunkName, string chunkId, IBuffer data)
        {
            try
            {
                HttpClient          client = new HttpClient();
                String              uri    = "toBeFilled";
                HttpRequestMessage  message;
                HttpResponseMessage response;
                switch (providerName)
                {
                case "dropbox":
                    uri     = "https://content.dropboxapi.com/1/files_put/auto/trustydrive/" + chunkName;
                    message = new HttpRequestMessage(HttpMethod.Put, new Uri(uri));
                    message.Headers.Append("Authorization", "Bearer " + token);
                    message.Content = new HttpBufferContent(data);
                    break;

                case "onedrive":
                    uri     = "https://api.onedrive.com/v1.0/drive/items/" + cloudFolder + ":/" + chunkName + ":/content?select=id";
                    message = new HttpRequestMessage(HttpMethod.Put, new Uri(uri));
                    message.Headers.Append("Authorization", "Bearer " + token);
                    message.Content = new HttpBufferContent(data);
                    message.Content.Headers.Append("Content-Type", "application/octet-stream");
                    break;

                case "gdrive":
                    if (chunkId == "none")
                    {
                        uri     = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart";
                        message = new HttpRequestMessage(HttpMethod.Post, new Uri(uri));
                    }
                    else
                    {
                        uri     = "https://www.googleapis.com/upload/drive/v3/files/" + chunkId + "?uploadType=media";
                        message = new HttpRequestMessage(HttpMethod.Patch, new Uri(uri));
                    }
                    message.Headers.Append("Authorization", "Bearer " + token);
                    message.Content = new HttpBufferContent(data);
                    message.Content.Headers.Append("Content-Type", "multipart/related; boundary=trustydrive_separator");
                    break;

                default:
                    // Never used, just for the compilation
                    message = new HttpRequestMessage();
                    break;
                }
                response = await client.SendRequestAsync(message);

                response.EnsureSuccessStatusCode();
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Chunk));
                Chunk ch = (Chunk)jsonSerializer.ReadObject(WindowsRuntimeStreamExtensions.AsStreamForRead(await response.Content.ReadAsInputStreamAsync()));
                if (providerName == "dropbox")
                {
                    _result.Add(chunkName);
                }
                else
                {
                    _result.Add(ch.name + ":$$:" + ch.id);
                }
            }
            catch
            {
                _result.Add(chunkName + ":$$:error");
            }
        }
Exemple #30
0
        /// <summary>
        /// IRandomAccessStream转byte[]
        /// </summary>
        /// <param name="randomAccessStream"></param>
        /// <returns></returns>
        public static byte[] ConvertIRandomAccessStreamTobyte(IRandomAccessStream randomAccessStream)
        {
            Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(randomAccessStream.GetInputStreamAt(0));

            return(ConvertStreamTobyte(stream));
        }