Inheritance: Windows.Storage.Streams.IBuffer
Beispiel #1
0
        public async void OnConnected(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                if (socket != null)
                {
                    socket.Dispose(); //fecha o socket anterior
                }
                socket = args.Socket;
                Windows.Storage.Streams.Buffer bufferRx = new Windows.Storage.Streams.Buffer(600);
                string  respostaOk = "OK";
                IBuffer bufferTx   = Encoding.ASCII.GetBytes(respostaOk).AsBuffer();

                await socket.InputStream.ReadAsync(bufferRx, bufferRx.Capacity, InputStreamOptions.None);

                parametes = Encoding.ASCII.GetString(bufferRx.ToArray()).Replace("\0", "");
                //this.textoPLC = System.Text.Encoding.ASCII.GetString(bufferRx.ToArray());
                //Debug.WriteLine("Rx: " + ", from: " + socket.Information.RemoteAddress);
                await socket.OutputStream.WriteAsync(bufferTx);  //Envia Ok como resposta
            }
            catch (Exception ex)
            {
                Debug.WriteLine("OnConnected Socket Exception " + ex.ToString());
            }
        }
        private async Task ConnectAsyncInternal(HostName hostName)
        {
            _tokenSource = new CancellationTokenSource();

            _socket = new StreamSocket();

            // połącz z kontrolerem na porcie 5555 
            await _socket.ConnectAsync(hostName, "5555", SocketProtectionLevel.PlainSocket);

            // wyslij komendę odblokowującą
            await _socket.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(UnlockCommand).AsBuffer());

            // read the "Accept:EV340\r\n\r\n" response
            //stworzenie bufor na odpowiedź
            IBuffer bufferResponse = new Buffer(128);
            //pobranie do bufora odpowiedzi przychodzącej od kontrolera EV3
            await _socket.InputStream.ReadAsync(bufferResponse, bufferResponse.Capacity, InputStreamOptions.Partial);
            //przekształcenie danych z bufora na ciag znaków w formacie UTF8
            string response = Encoding.UTF8.GetString(bufferResponse.ToArray(), 0, (int)bufferResponse.Length);
            if (string.IsNullOrEmpty(response))
                //zgłoszenie błędu w razie braku odpowiedzi
                throw new Exception("LEGO EV3 brick did not respond to the unlock command.");
            //rozpoczęcie pobierania danych
            await ThreadPool.RunAsync(PollInput);
        }
Beispiel #3
0
        public static async Task <byte[]> ComputeMD5(IRandomAccessStream stream)
        {
            var  alg         = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            var  inputStream = stream.GetInputStreamAt(0);
            uint capacity    = 1024 * 1024;
            var  buffer      = new Buffer(capacity);
            var  hash        = alg.CreateHash();

            while (true)
            {
                await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None);

                if (buffer.Length > 0)
                {
                    hash.Append(buffer);
                }
                else
                {
                    break;
                }
            }

            return(hash.GetValueAndReset().ToArray());

            //string hashText = CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset()).ToUpper();
            //var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            ////IBuffer buff =
            //var hashed = alg.HashData(str.)
            //var res = CryptographicBuffer.EncodeToHexString(hashed);
            //return res;
        }
Beispiel #4
0
        /// <summary>
        /// 获取Emoji的JSON
        /// </summary>
        /// <returns>JSON</returns>
        public async static Task <string> GetEmojis()
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage response = await client.GetAsync(new Uri(EmojiLink));

                    if (null != response && response.StatusCode == HttpStatusCode.Ok)
                    {
                        using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
                        {
                            await response.Content.WriteToStreamAsync(stream);

                            stream.Seek(0);
                            Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);
                            await stream.ReadAsync(buffer, (uint)stream.Size, Windows.Storage.Streams.InputStreamOptions.Partial);

                            using (DataReader reader = DataReader.FromBuffer(buffer))
                            {
                                return(reader.ReadString((uint)stream.Size));
                            }
                        }
                    }
                }catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    return(string.Empty);
                }
                return(string.Empty);
            }
        }
 private IBuffer GetBuffer()
 {
     IBuffer buffer;
     var dequeued = _buffersQueue.TryDequeue(out buffer);
     if (!dequeued) buffer = new Buffer(SAMPLE_BUFFER_SIZE);
     return buffer;
 }
Beispiel #6
0
 public static async Task<IBuffer> ReadIntoBuffer(IRandomAccessStream stream)
 {
     stream.Seek(0);
     var buffer = new Buffer((uint) stream.Size);
     await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);
     return buffer;
 }
Beispiel #7
0
        internal static async Task <string> ReadStringFromFile(this string filename)
        {
            var text = string.Empty;

            try
            {
                var appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

                Debug.WriteLine($"AppFolder {appFolder.Path}");

                var storageFile = await appFolder.GetFileAsync(filename);

                var stream = await storageFile.OpenAsync(FileAccessMode.Read);

                var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);

                await stream.ReadAsync(buffer, (uint)stream.Size, InputStreamOptions.None);

                if (buffer.Length > 0)
                {
                    text = Encoding.UTF8.GetString(buffer.ToArray());
                }
            }
            catch (Exception)
            {
                //await Display.Write($"Read failed {filename}");
            }

            return(text);
        }
        public async Task <IMediaModel> GenerateThumbImageFromVideo(DirectoryInfo argCurrentDataFolder, MediaModel argExistingMediaModel, IMediaModel argNewMediaModel)
        {
            StorageFolder currentFolder = await StorageFolder.GetFolderFromPathAsync(argCurrentDataFolder.FullName);

            StorageFile outfile = await currentFolder.CreateFileAsync(argNewMediaModel.OriginalFilePath, CreationCollisionOption.ReplaceExisting);

            //if (outfile.Name == "_e9e27fbe8ed34e9b554a0ba93aa~imagevideo.jpg")
            //{
            //}

            StorageFile videoFile = await currentFolder.GetFileAsync(argExistingMediaModel.OriginalFilePath);

            StorageItemThumbnail thumbnail = await videoFile.GetThumbnailAsync(ThumbnailMode.SingleItem);

            Windows.Storage.Streams.Buffer MyBuffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(thumbnail.Size));
            IBuffer iBuf = await thumbnail.ReadAsync(MyBuffer, MyBuffer.Capacity, InputStreamOptions.None);

            IRandomAccessStream strm = await outfile.OpenAsync(FileAccessMode.ReadWrite);

            await strm.WriteAsync(iBuf);

            await strm.FlushAsync();

            strm.Dispose();

            // check size
            BasicProperties outProperties = await outfile.GetBasicPropertiesAsync();

            if (outProperties.Size == 0)
            {
                return(new MediaModel());
            }

            return(argNewMediaModel);
        }
Beispiel #9
0
        // incoming data receive loop
        private async Task _receiveData()
        {
            try
            {
                var     stream = _socket.InputStream;
                IBuffer buffer = new Windows.Storage.Streams.Buffer(10240);
                while (true)
                {
                    IBuffer data = await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);

                    if (data.Length == 0)
                    {
                        break;
                    }
                    _emitData(data);
                }
                // Client disconnected.
                _emitEnd();
                _socket = null;
                if (_server != null)
                {
                    _server._connectionDidClose(this);
                }
            }
            catch (System.IO.IOException ex)
            {
                NKLogging.log(ex.ToString());
            }
            catch (Exception ex)
            {
                NKLogging.log(ex.ToString());
            }
        }
        /// <summary>
        /// Used for applying our video effect to a single frame. 
        /// </summary>
        /// <param name="context"></param>
        public void ProcessFrame(ProcessVideoFrameContext context)
        {
            var inputFrameBitmap = context.InputFrame.SoftwareBitmap;

            // Create intermediate buffer for holding the frame pixel data.
            var frameSize = inputFrameBitmap.PixelWidth * inputFrameBitmap.PixelHeight * 4;
            var frameBuffer = new Buffer((uint)frameSize);

            // Copy bitmap data from the input frame.
            inputFrameBitmap.CopyToBuffer(frameBuffer);

            // Iterate through all pixels in the frame.
            var framePixels = frameBuffer.ToArray();
            for (int i = 0; i < frameSize; i += 4)
            {
                // Calculate the luminance based on the RGB values - this way we can convert it to grayscale.
                var bValue = framePixels[i];
                var gValue = framePixels[i + 1];
                var rValue = framePixels[i + 2];

                var luminance = ((rValue / 255.0f) * 0.2126f) +
                                ((gValue / 255.0f) * 0.7152f) +
                                ((bValue / 255.0f) * 0.0722f);

                // Set the pixel data to the calculated grayscale values.
                framePixels[i] = framePixels[i + 1] = framePixels[i + 2] = (byte)(luminance * 255.0f);
            }

            // Copy the modified frame data to the output frame.
            context.OutputFrame.SoftwareBitmap.CopyFromBuffer(framePixels.AsBuffer());
        }
Beispiel #11
0
 public static async Task<IBuffer> ToBuffer(this IRandomAccessStream stream)
 {
     stream.Seek(0);
     var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);
     await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);
     return buffer;
 }
        private async Task PollInputAsync()
        {
            while (!_tokenSource.IsCancellationRequested)
            {
                try
                {
                    IBuffer sizeBuffer = new Buffer(2);
                    await _socket.InputStream.ReadAsync(sizeBuffer, 2, InputStreamOptions.None);

                    uint size = (uint)(sizeBuffer.GetByte(0) | sizeBuffer.GetByte(1) << 8);

                    if (size != 0)
                    {
                        IBuffer data = new Buffer(size);
                        await _socket.InputStream.ReadAsync(data, size, InputStreamOptions.None);

                        RaiseDataReceived(data.ToArray());
                    }
                }
                catch (TaskCanceledException)
                {
                    return;
                }
                catch (Exception)
                {
                    // swallow exceptions...if we tank here, it's likely a disconnect and we can't do much anyway
                }
            }
        }
Beispiel #13
0
        private async void PollInput(IAsyncAction operation)
        {
            while (!_tokenSource.IsCancellationRequested)
            {
                try
                {
                    IBuffer sizeBuffer = new Buffer(2);
                    await _socket.InputStream.ReadAsync(sizeBuffer, 2, InputStreamOptions.None);

                    uint size = (uint)((sizeBuffer.GetByte(0) | sizeBuffer.GetByte(1) << 8));

                    if (size != 0)
                    {
                        IBuffer report = new Buffer(size);
                        await _socket.InputStream.ReadAsync(report, size, InputStreamOptions.None);

                        if (ReportReceived != null)
                        {
                            ReportReceived(this, new ReportReceivedEventArgs {
                                Report = report.ToArray()
                            });
                        }
                    }
                }
                catch (Exception)
                {
                    // swallow exceptions...if we tank here, it's likely a disconnect and we can't do much anyway
                }
            }
        }
        public override int Read(byte[] buffer, int offset, int count)
        {
            Windows.Storage.Streams.Buffer tmpBuffer = new Windows.Storage.Streams.Buffer((uint)count);

            try
            {
                var task = Client.Socket.InputStream.ReadAsync(tmpBuffer, tmpBuffer.Capacity, InputStreamOptions.Partial)
                           .AsTask();
                task.ConfigureAwait(false);
                task.Wait();
            }
            catch (AggregateException ex)
            {
                if (ex.InnerException != null)
                {
                    throw ex.InnerException;
                }
                else
                {
                    throw ex;
                }
            }

            DataReader reader = DataReader.FromBuffer(tmpBuffer);
            int        length = (int)reader.UnconsumedBufferLength;

            for (int i = 0; i < length; ++i)
            {
                buffer[offset + i] = reader.ReadByte();
            }
            return(length);
        }
        /// <summary>
        /// Asynchronously saves all the album arts in the library.
        /// </summary>
        /// <param name="Data">ID3 tag of the song to get album art data from.</param>
        public async void SaveImages(Windows.Storage.FileProperties.StorageItemThumbnail thumb, Mediafile file)
        {
            var albumartFolder = ApplicationData.Current.LocalFolder;
            var md5Path        = (file.Album + file.LeadArtist).ToLower().ToSha1();

            if (!File.Exists(albumartFolder.Path + @"\AlbumArts\" + md5Path + ".jpg"))
            {
                IBuffer buf;
                Windows.Storage.Streams.Buffer inputBuffer = new Windows.Storage.Streams.Buffer(1024);
                var albumart = await albumartFolder.CreateFileAsync(@"AlbumArts\" + md5Path + ".jpg", CreationCollisionOption.FailIfExists);

                using (IRandomAccessStream albumstream = await albumart.OpenAsync(FileAccessMode.ReadWrite))
                {
                    while ((buf = (await thumb.ReadAsync(inputBuffer, inputBuffer.Capacity, Windows.Storage.Streams.InputStreamOptions.None))).Length > 0)
                    {
                        await albumstream.WriteAsync(buf);
                    }

                    //try
                    //{
                    //    var data = Data.AttachedPictureFrames["APIC"] as AttachedPictureFrame;
                    //    var stream = data.Data.AsRandomAccessStream();
                    //    BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);

                    //    var x = await decoder.GetSoftwareBitmapAsync();
                    //    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, albumstream);
                    //    encoder.SetSoftwareBitmap(x);
                    //    await encoder.FlushAsync();
                    //    stream.Dispose();
                    //}
                    //catch(Exception ex) { Debug.Write(ex.Message + "||" + file.Path); }
                }
                thumb.Dispose();
            }
        }
Beispiel #16
0
        private async Task ConnectAsyncInternal(HostName hostName)
        {
            _tokenSource = new CancellationTokenSource();

            _socket = new StreamSocket();

            // connect to the brick on port 5555
            await _socket.ConnectAsync(hostName, "5555", SocketProtectionLevel.PlainSocket);

            // unlock the brick (doesn't actually need serial number?)
            await _socket.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(UnlockCommand).AsBuffer());

            // read the "Accept:EV340\r\n\r\n" response
            IBuffer bufferResponse = new Buffer(128);
            await _socket.InputStream.ReadAsync(bufferResponse, bufferResponse.Capacity, InputStreamOptions.Partial);

            string response = Encoding.UTF8.GetString(bufferResponse.ToArray(), 0, (int)bufferResponse.Length);

            if (string.IsNullOrEmpty(response))
            {
                throw new Exception("LEGO EV3 brick did not respond to the unlock command.");
            }

            await ThreadPool.RunAsync(PollInput);
        }
        public static async Task <MHzSongBase> ReadSongModelFromStorageFileAsync(StorageFile storage)
        {
            using (var stream = await storage.OpenReadAsync()) {
                IBuffer buff  = new Windows.Storage.Streams.Buffer((uint)stream.Size);
                var     bytes = new byte[stream.Size];
                await stream.AsStream().ReadAsync(bytes, 0, (int)stream.Size);

                var str    = Encoding.UTF8.GetString(bytes);
                var result = default(MHzSongBase);
                try {
                    result           = JsonHelper.FromJson <MHzSongBase>(RepairForOldVersion(str));
                    result.LocalPath = storage.Path;
                } catch (SerializationException) {
                    var music_file = await FetchStorageFileByPathAsync(storage.Path.Replace(JsonExtension, MusicExtension));

                    await storage.DeleteAsync();

                    await music_file.DeleteAsync();

                    return(null);
                } catch {
                    return(null);
                }
                return(result);
            }
        }
Beispiel #18
0
        public async Task <string> GetHashForFile(ListedItem fileItem, string nameOfAlg)
        {
            HashAlgorithmProvider algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(nameOfAlg);
            var itemFromPath = await StorageFile.GetFileFromPathAsync(fileItem.ItemPath);

            var stream = await itemFromPath.OpenStreamForReadAsync();

            var  inputStream = stream.AsInputStream();
            uint capacity    = 100000000;

            Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity);
            var hash = algorithmProvider.CreateHash();

            while (true)
            {
                await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None);

                if (buffer.Length > 0)
                {
                    hash.Append(buffer);
                }
                else
                {
                    break;
                }
            }
            inputStream.Dispose();
            stream.Dispose();
            return(CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset()).ToLower());
        }
Beispiel #19
0
        /// <summary>
        /// Asynchronously saves all the album arts in the library.
        /// </summary>
        /// <param name="Data">ID3 tag of the song to get album art data from.</param>
        public static async Task <bool> SaveImagesAsync(Windows.Storage.FileProperties.StorageItemThumbnail thumb, Mediafile file)
        {
            var albumartFolder = ApplicationData.Current.LocalFolder;
            var md5Path        = (file.Album + file.LeadArtist).ToLower().ToSha1();

            if (!File.Exists(albumartFolder.Path + @"\AlbumArts\" + md5Path + ".jpg"))
            {
                try
                {
                    Windows.Storage.Streams.IBuffer buf;
                    Windows.Storage.Streams.Buffer  inputBuffer = new Windows.Storage.Streams.Buffer(1024);
                    var albumart = await albumartFolder.CreateFileAsync(@"AlbumArts\" + md5Path + ".jpg", CreationCollisionOption.FailIfExists).AsTask().ConfigureAwait(false);

                    using (Windows.Storage.Streams.IRandomAccessStream albumstream = await albumart.OpenAsync(FileAccessMode.ReadWrite).AsTask().ConfigureAwait(false))
                    {
                        while ((buf = (await thumb.ReadAsync(inputBuffer, inputBuffer.Capacity, Windows.Storage.Streams.InputStreamOptions.None).AsTask().ConfigureAwait(false))).Length > 0)
                        {
                            await albumstream.WriteAsync(buf).AsTask().ConfigureAwait(false);
                        }
                    }

                    thumb.Dispose();
                    return(true);
                }
                catch (Exception ex)
                {
                    await NotificationManager.ShowAsync(ex.Message + "||" + file.Path);

                    return(false);
                }
            }
            return(false);
        }
Beispiel #20
0
        public void When_Create_Then_LengthIsZero()
        {
            var sut = new Buffer(42);

            Assert.AreEqual(0U, sut.Length);
            Assert.AreEqual(42U, sut.Capacity);
        }
        private async Task <byte[]> ReadAsync(int bufferLength)
        {
            var buffer = new Windows.Storage.Streams.Buffer((uint)bufferLength);
            await NetworkStream.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);

            return(buffer.ToArray());
        }
        public async void Save()
        {
            var fileSavePicker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                SuggestedFileName      = "Sketch",
            };

            fileSavePicker.FileTypeChoices.Add("PNG file", new List <string> {
                ".png"
            });
            var file = await fileSavePicker.PickSaveFileAsync();

            if (file != null)
            {
                var png = await GeneratePng();

                CachedFileManager.DeferUpdates(file);
                var buffer = new Buffer((uint)png.Size);
                await png.ReadAsync(buffer, (uint)png.Size, InputStreamOptions.None);

                await FileIO.WriteBufferAsync(file, buffer);

                var status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status != FileUpdateStatus.Complete)
                {
                    // failed
                }
            }
        }
Beispiel #23
0
        private async void AppBar_LoadDefault_Button_Click(object sender, RoutedEventArgs e)
        {
            string currentDirectory = Directory.GetCurrentDirectory(); //$"C:\\Users\\steve\\Documents"; //

            // Load the XML file from our project directory containing the purchase orders
            string      potentialdata_filename = "SeawaterPotentialData.xml";
            string      galvPotentialFilepath  = Path.Combine(currentDirectory, potentialdata_filename);
            StorageFile temp_file = await StorageFile.GetFileFromPathAsync(galvPotentialFilepath);

            string      alloytreatment_filename = "AlloyTreatmentRecommendations.xml";
            string      treatmentFilepath       = Path.Combine(currentDirectory, alloytreatment_filename);
            StorageFile temp_file_2             = await StorageFile.GetFileFromPathAsync(treatmentFilepath);

            if (temp_file != null)
            {
                sampleFile = temp_file;
            }
            if (sampleFile != null)
            {
                try
                {
                    using (IRandomAccessStream readstream = await sampleFile.OpenAsync(FileAccessMode.Read))
                    {
                        ulong size64 = readstream.Size;
                        if (size64 <= uint.MaxValue)
                        {
                            uint    size32 = (uint)size64;
                            IBuffer buffer = new Windows.Storage.Streams.Buffer(size32);
                            buffer = await readstream.ReadAsync(buffer, size32, InputStreamOptions.None);

                            string filecontent = GetStringFromBuffer(buffer);

                            XElement xmlroot = XElement.Parse(filecontent);
                            IEnumerable <XElement> MaterialNames = from el in xmlroot.Elements("Data") select el;

                            foreach (XElement el in MaterialNames)
                            {
                                ListOfAnodes.Items.Add(el.Element("Name").Value);
                                ListOfCathodes.Items.Add(el.Element("Name").Value);
                            }

                            ListOfAnodes.IsEnabled = true;
                        }
                        else
                        {
                            await displayMessageAsync("Alert message", "Your data file is too large.  It needs to be < 4 GB.", "notification");
                        }
                    }
                }
                catch
                {
                    await displayMessageAsync("Fail message", "The default data file did not load correctly.", "notification");
                }
            }

            if (temp_file_2 != null)
            {
                treatmentFile = temp_file_2;
            }
        }
            /// <summary>
            /// Non-blocking read implementation
            /// </summary>
            /// <param name="socket"></param>
            /// <param name="size"></param>
            /// <returns></returns>
            public byte[] ReadNonBlocking(Connection conn, uint size)
            {
                try
                {
                    StreamSocket socket = conn.sock;

                    IBuffer buffer = new Windows.Storage.Streams.Buffer(size);
                    var     t      = Task <byte[]> .Run(async() =>
                    {
                        buffer = await socket.InputStream.ReadAsync(buffer, size, InputStreamOptions.Partial);
                        if (buffer.Length == 0)
                        {
                            return(null);
                        }
                        else
                        {
                            return(buffer.ToArray());
                        }
                    });

                    t.Wait();
                    return(t.Result);
                }
                catch (Exception e)
                {
                    OneWireEventSource.Log.Debug("ReadNonBlocking(): " + e.ToString());
                }

                return(null);
            }
Beispiel #25
0
        public async void StartVideoRecordingOnThread(StreamSocket _socket)
        {
            //Make sure the MediaCapture object is initialized
            await CheckSetUp();

            Streamer streamer = new Streamer(_socket);

            // When the streamer is connected, create a new Output stream using the streamer
            isRecording = true;
            while (true)
            {
                InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                await _mediaCapture.StartRecordToStreamAsync(MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Vga), stream);

                await Task.Delay(TimeSpan.FromSeconds(1));

                await _mediaCapture.StopRecordAsync();

                stream.Seek(0);

                Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);
                await stream.ReadAsync(buffer, (uint)stream.Size, Windows.Storage.Streams.InputStreamOptions.None);

                streamer.WriteToSocketUsingReader(buffer);
            }
        }
        private void ListenForMessage()
        {
            IBuffer buffer = new Windows.Storage.Streams.Buffer((uint)currentReceivedMessage.Length);
            IAsyncOperationWithProgress <IBuffer, uint> newmessagereceived = networkConnection.InputStream.ReadAsync(buffer, (uint)currentReceivedMessage.Length, new InputStreamOptions());

            newmessagereceived.Completed = new AsyncOperationWithProgressCompletedHandler <IBuffer, uint>(MessageReceived);
        }
        private void ListenForMessageHeader()
        {
            IBuffer buffer = new Windows.Storage.Streams.Buffer(sizeof(ulong));
            IAsyncOperationWithProgress <IBuffer, uint> newmessagereceived = networkConnection.InputStream.ReadAsync(buffer, sizeof(ulong), new InputStreamOptions());

            newmessagereceived.Completed = new AsyncOperationWithProgressCompletedHandler <IBuffer, uint>(MessageHeaderReceived);
        }
Beispiel #28
0
        /// <summary>
        /// 用于上传拖拽的文件,每次可上传多个文件
        /// </summary>
        /// <param name="cts"></param>
        /// <param name="files"></param>
        /// <param name="beforeUpload"></param>
        /// <param name="afterUpload"></param>
        /// <returns></returns>
        public static async Task <List <string>[]> UploadFileAsync(CancellationTokenSource cts, IReadOnlyList <IStorageItem> files,
                                                                   Action <int, int, string> beforeUpload, Action <int> afterUpload)
        {
            var fileNameList = new List <string>(); // 用于与其他文本内容一起POST
            var fileCodeList = new List <string>(); // 用于插入内容文本框

            if (files != null && files.Count > 0)
            {
                int fileIndex = 1;
                foreach (var file in files)
                {
                    string fileName = file.Name;

                    beforeUpload?.Invoke(fileIndex, files.Count, fileName);

                    fileNameList.Add(fileName);

                    //byte[] imageBuffer;

                    //if (deviceFamily.Equals("Windows.Mobile"))
                    //{
                    //    imageBuffer = await ImageHelper.LoadAsync(file);
                    //}
                    //else
                    //{
                    IRandomAccessStream stream = await((StorageFile)file).OpenAsync(FileAccessMode.Read);
                    IBuffer             buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);
                    buffer = await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None);

                    //}

                    var data = new Dictionary <string, object>();
                    data.Add("uid", AccountService.UserId);
                    data.Add("hash", AccountService.Hash);

                    try
                    {
                        string url    = "http://www.hi-pda.com/forum/misc.php?action=swfupload&operation=upload&simple=1";
                        string result = await _httpClient.PostFileAsync(url, data, fileName, "Filedata", buffer, cts);

                        if (result.Contains("DISCUZUPLOAD|"))
                        {
                            string value = result.Split('|')[2];
                            value = $"[attachimg]{value}[/attachimg]";
                            fileCodeList.Add(value);

                            fileIndex++;
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                    }
                }

                afterUpload?.Invoke(files.Count);
            }

            return(new List <string>[] { fileNameList, fileCodeList });
        }
Beispiel #29
0
        public async Task <int> Receive(byte[] buffer, Action <int> callback, Action <Exception> error, int offset)
        {
            try
            {
                var        ibuffer = new Windows.Storage.Streams.Buffer((uint)buffer.Length);
                DataReader reader  = new DataReader(_socket.InputStream);
                reader.InputStreamOptions = InputStreamOptions.Partial;
                uint count = await reader.LoadAsync((uint)buffer.Length);

                byte[] bytes = new byte[count];
                reader.ReadBytes(bytes);
                reader.DetachStream();
                bytes.CopyTo(buffer, 0);
                //var result = await _socket.InputStream.AsStreamForRead(buffer.Length).ReadAsync(buffer, offset, buffer.Length,_tokenSource.Token);
                //var result = await _socket.InputStream.ReadAsync(ibuffer, (uint)buffer.Length, Windows.Storage.Streams.InputStreamOptions.None);

                callback((int)count);
                return((int)count);
            }
            catch (Exception e)
            {
                error(e);
                return(0);
            }
        }
Beispiel #30
0
        public WriteableBitmap(int pixelWidth, int pixelHeight) : base()
        {
            _buffer = new UwpBuffer((uint)(pixelWidth * pixelHeight * 4));

            PixelWidth  = pixelWidth;
            PixelHeight = pixelHeight;
        }
        public override int Read(byte[] buffer, int offset, int count)
        {
            Windows.Storage.Streams.Buffer tmpBuffer = new Windows.Storage.Streams.Buffer((uint)count);

            try
            {
                var task = Client.Socket.InputStream.ReadAsync(tmpBuffer, (uint)count, InputStreamOptions.None);
                task.AsTask().Wait();
            }
            catch(AggregateException ex)
            {
                if (ex.InnerException != null)
                    throw ex.InnerException;
                else
                    throw ex;
            }

            /*byte[] tmpBuff = tmpBuffer.ToArray();
            int length = Math.Min(tmpBuff.Length, count);

            Array.Copy(tmpBuff, 0, buffer, offset, length);

            return length;*/
            
            DataReader buf = DataReader.FromBuffer(tmpBuffer);
            int length = (int)buf.UnconsumedBufferLength;
            for (int i = 0; i < length; ++i)
                buffer[offset + i] = buf.ReadByte();
            return length;
        }
        private void ReadMore()
        {
            IBuffer buffer = new Windows.Storage.Streams.Buffer(1024);

            readOperation           = inputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);
            readOperation.Completed = OnReadCompleted;
        }
Beispiel #33
0
        public async Task DownloadFile(string path, StorageFile destFile)
        {
            Uri uri = GetUri($"/api/files/{Utils.EncodePath(path)}/download");

            if (uri == null)
            {
                return;
            }

            using (IRandomAccessStream fileStream = await destFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (HttpClient client = GetClient())
                {
                    using (IInputStream downloadStream = await client.GetInputStreamAsync(uri))
                    {
                        const uint capacity = 1_000_000;
                        Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity);
                        while (true)
                        {
                            await downloadStream.ReadAsync(buffer, capacity, InputStreamOptions.None);

                            if (buffer.Length == 0)
                            {
                                break;
                            }
                            await fileStream.WriteAsync(buffer);
                        }
                    }
                }
            }
        }
Beispiel #34
0
        async private void AppBarButton_Click_4(object sender, RoutedEventArgs e)
        {
            //Uri uri = new Uri("http://www.charlespetzold.com/pw6/PetzoldJersey.jpg");
            Uri uri = new Uri("ms-appx:///PetzoldJersey.jpg");
            RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri);

            // Create a buffer for reading the stream
            Windows.Storage.Streams.Buffer buffer = null;

            // Read the entire file
            using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
            {
                buffer = new Windows.Storage.Streams.Buffer((uint)fileStream.Size);
                await fileStream.ReadAsync(buffer, (uint)fileStream.Size, InputStreamOptions.None);
            }

            // Create WriteableBitmap with unknown size
            WriteableBitmap bitmap = new WriteableBitmap(1, 1);

            // Create a memory stream for transferring the data
            using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
            {
                await memoryStream.WriteAsync(buffer);

                memoryStream.Seek(0);

                // Use the memory stream as the Bitmap source
                bitmap.SetSource(memoryStream);
            }

            // Now get the pixels from the bitmap
            byte[] pixels = new byte[4 * bitmap.PixelWidth * bitmap.PixelHeight];
            int    index  = 0;

            using (Stream pixelStream = bitmap.PixelBuffer.AsStream())
            {
                await pixelStream.ReadAsync(pixels, 0, pixels.Length);

                // Apply opacity to the pixels
                for (int y = 0; y < bitmap.PixelHeight; y++)
                {
                    double opacity = (double)y / bitmap.PixelHeight;

                    for (int x = 0; x < bitmap.PixelWidth; x++)
                    {
                        for (int i = 0; i < 4; i++)
                        {
                            pixels[index] = (byte)(opacity * pixels[index]);
                            index++;
                        }
                    }
                }

                // Put the pixels back in the bitmap
                pixelStream.Seek(0, SeekOrigin.Begin);
                await pixelStream.WriteAsync(pixels, 0, pixels.Length);
            }
            bitmap.Invalidate();
            reflectedImage.Source = bitmap;
        }
        internal static async Task<string> ReadStringFromFile(this string filename)
        {
            var text = string.Empty;

            try
            {
                var appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;

                Debug.WriteLine($"AppFolder {appFolder.Path}");

                var storageFile = await appFolder.GetFileAsync(filename);
                var stream = await storageFile.OpenAsync(FileAccessMode.Read);
                var buffer = new Windows.Storage.Streams.Buffer((uint)stream.Size);

                await stream.ReadAsync(buffer, (uint)stream.Size, InputStreamOptions.None);

                if (buffer.Length > 0)
                    text = Encoding.UTF8.GetString(buffer.ToArray());
            }
            catch (Exception)
            {
                //await Display.Write($"Read failed {filename}");
            }

            return text;
        }
        public static Func <HttpRequest, HttpResponse, Task> Create(StorageFolder dataFolder)
        {
            return(async(request, response) =>
            {
                string filePath = request.ReqLine.Uri == "/" ? DefaultFile : request.ReqLine.Uri;
                filePath = filePath.Replace('/', '\\');
                var file = await dataFolder.GetFileAsync(filePath);

                await response.WriteHeadersAsync(
                    HttpStatus.OK,
                    Tuple.Create(HttpHeader.ContentType, file.ContentType),
                    Tuple.Create(HttpHeader.ContentLength, (await file.GetBasicPropertiesAsync()).Size.ToString())
                    );

                var stream = ((StreamWriterAsync)response.Stream).Stream;
                var buffer = new Windows.Storage.Streams.Buffer(DefaultBufferSize);
                using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    do
                    {
                        await fs.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.ReadAhead);

                        await stream.WriteAsync(buffer);
                    } while (buffer.Length == buffer.Capacity);
                }
            });
        }
Beispiel #37
0
        private async Task ReadAsync(StreamSocket socket)
        {
            IBuffer readBuffer = new Windows.Storage.Streams.Buffer(1024);

            while (true)
            {
                IBuffer buffer;
                try
                {
                    buffer = await socket.InputStream.ReadAsync(readBuffer, 1024, InputStreamOptions.Partial);
                }
                catch
                {
                    await Stop().ConfigureAwait(true);

                    return;
                }
                if (buffer.Length != 0)
                {
                    var data = new byte[buffer.Length];
                    using (DataReader dataReader = DataReader.FromBuffer(buffer))
                    {
                        dataReader.ReadBytes(data);
                        outputText.AppendBinary(data, data.Length);
                    }
                }
                else
                {
                    status.Text = "Disconnected.";
                    await Stop().ConfigureAwait(true);

                    return;
                }
            }
        }
        private async void buttonReceive_Click(object sender, RoutedEventArgs e)
        {
            var buffer = new Windows.Storage.Streams.Buffer(1024);
            var readBytes = await App.Socket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);

            GetString(GetByteArrayFromBuffer(buffer));
            //txtMsg.Text += GetString(GetByteArrayFromBuffer(buffer));
        }
Beispiel #39
0
        protected override async void Loop()
        {
            Streams.DataReader reader = null;

            try
            {
                while (true)
                {
                    if (socket == null)
                    {
                        socket = new StreamSocket();
                        await socket.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
                    }

                    var readBuf = new Streams.Buffer((uint)NetworkBufferSize);
                    var readOp = socket.InputStream.ReadAsync(readBuf, (uint)NetworkBufferSize, Streams.InputStreamOptions.Partial);

                    readOp.Completed = (IAsyncOperationWithProgress<Streams.IBuffer, uint> asyncAction, AsyncStatus asyncStatus) =>
                    {
                        switch (asyncStatus)
                        {
                            case AsyncStatus.Completed:
                                Debug.WriteLine("Config:Completed ");
                                try
                                {
                                    Streams.IBuffer localBuf = asyncAction.GetResults();
                                    uint bytesRead = localBuf.Length;
                                    Debug.WriteLine("Config:Buffer (" + bytesRead + ")");
                                    reader = Streams.DataReader.FromBuffer(localBuf);
                                    OnDataReadCompletion(bytesRead, reader);
                                }
                                catch (Exception e)
                                {
                                    Debug.WriteLine(e.ToString());
                                }
                                break;
                            case AsyncStatus.Canceled:
                                Debug.WriteLine("Config:Canceled ");
                                break;
                            case AsyncStatus.Error:
                                Debug.WriteLine("Config:Error ");
                                break;
                        }
                    };
                    //socket.Dispose();
                    await Task.Delay(500);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
                Stop();
            }
        }
        public async Task WaitForFrameAsync()
        {
            var buffer = new Buffer(RequestBufferSize);
            await _clientSocket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);

            var data = new List<byte>(_overhead);
            _overhead = new byte[0];
            data.AddRange(buffer.ToArray());

            var parseWebSocketFrameResult = WebSocketFrame.Parse(data.ToArray());
            if (parseWebSocketFrameResult.WebSocketFrame == null)
            {
                _overhead = parseWebSocketFrameResult.Overhead;
                return;
            }

            var webSocketFrame = parseWebSocketFrameResult.WebSocketFrame;
            switch (webSocketFrame.Opcode)
            {
                case WebSocketOpcode.Ping:
                    {
                        webSocketFrame.Opcode = WebSocketOpcode.Pong;
                        await SendAsync(webSocketFrame);

                        return;
                    }

                case WebSocketOpcode.ConnectionClose:
                    {
                        CloseAsync().Wait();
                        return;
                    }

                case WebSocketOpcode.Pong:
                    {
                        return;
                    }
            }

            _frameQueue.Add(webSocketFrame);

            if (webSocketFrame.Fin)
            {
                var message = GenerateMessage();
                _frameQueue.Clear();

                MessageReceived?.Invoke(this, new WebSocketMessageReceivedEventArgs(message, this));
            }
        }
Beispiel #41
0
 private async Task<int> ReceiveAsync(byte[] outbuffer)
 {
     IBuffer buffer = new Windows.Storage.Streams.Buffer((uint)outbuffer.Length);
     buffer = await socket.InputStream.ReadAsync(buffer, buffer.Capacity, Windows.Storage.Streams.InputStreamOptions.None);
     if (buffer.Length < outbuffer.Length)
     {
         var outbuffer2 = new byte[buffer.Length];
         DataReader.FromBuffer(buffer).ReadBytes(outbuffer2);
         Array.Copy(outbuffer2, outbuffer, Math.Min(outbuffer.Length, outbuffer2.Length));
     }
     else
     {
         DataReader.FromBuffer(buffer).ReadBytes(outbuffer);
     }
     return (int)buffer.Length;
 }
Beispiel #42
0
        public async Task<ReturnElements> GetScreen()
        {
            ReturnElements retelement = new ReturnElements();

            // Get the bitmap and display it.
            var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
            if (dataPackageView.Contains(StandardDataFormats.Bitmap))
            {
                IRandomAccessStreamReference imageReceived = null;
                try
                {
                    imageReceived = await dataPackageView.GetBitmapAsync();

                    if (imageReceived != null)
                    {
                        using (IRandomAccessStream imageStream = await imageReceived.OpenReadAsync())
                        {
                            StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Temp");
                            if (folder == null)
                                folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Temp", CreationCollisionOption.ReplaceExisting);

                            StorageFile file = await folder.CreateFileAsync("MyPainter.png", CreationCollisionOption.ReplaceExisting);
                            Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer((uint)imageStream.Size);
                            await imageStream.ReadAsync(buffer, (uint)imageStream.Size, InputStreamOptions.None);
                            await FileIO.WriteBufferAsync(file, buffer);
                            control.factory.IsGetScreenSucccess = true;
                            retelement.success = true;
                            return retelement;
                        }
                    }
                }
                catch (Exception ex)
                {
                    control.factory.IsGetScreenSucccess = false;
                    retelement.success = false;
                    return retelement;
                }

            }
            control.factory.IsGetScreenSucccess = false;
            retelement.success = false;
            return retelement;
        }
        public static async Task<string> ComputeMd5(IInputStream stream, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8)
        {
            var hashAlgorithmProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            var hash = hashAlgorithmProvider.CreateHash();
            uint size = 1024*64;
            var buffer = new Buffer(size);
            while (true)
            {
                var x = await stream.ReadAsync(buffer, size, InputStreamOptions.Partial);
                if (x.Length < 1)
                {
                    break;
                }
                hash.Append(x);
            }

            var result = hash.GetValueAndReset();
            var hex = CryptographicBuffer.EncodeToHexString(result);
            return hex;
        }
        private async Task ConnectAsyncInternal(HostName hostName)
        {
            _tokenSource = new CancellationTokenSource();

            _socket = new StreamSocket();

            // connect to the brick on port 5555
            await _socket.ConnectAsync(hostName, "5555", SocketProtectionLevel.PlainSocket);

            // unlock the brick (doesn't actually need serial number?)
            await _socket.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(UnlockCommand).AsBuffer());

            // read the "Accept:EV340\r\n\r\n" response
            IBuffer bufferResponse = new Buffer(128);
            await _socket.InputStream.ReadAsync(bufferResponse, bufferResponse.Capacity, InputStreamOptions.Partial);
            string response = Encoding.UTF8.GetString(bufferResponse.ToArray(), 0, (int)bufferResponse.Length);
            if (string.IsNullOrEmpty(response))
                throw new Exception("LEGO EV3 brick did not respond to the unlock command.");

            await ThreadPool.RunAsync(PollInput);
        }
        private async Task SendHearbeat()
        {
            using (var socket = new StreamSocket())
            {
                await socket.ConnectAsync(new HostName(_server.ToString()), _port.ToString());
                var formatter = new HeartBeatListener.Formatter();
                var writer = new DataWriter(socket.OutputStream);

                IBuffer buffer = null;
                if (State == CameraClientState.Idle)
                {
                    buffer = await StorageIO.ReadIntoBuffer(await _camera.Snapshot());
                }
                else
                {
                    buffer = new StreamBuffer(0);
                }
                Debug.WriteLine($"Hearbeat state {State}");
                await formatter.Write(writer, new CameraHeartBeat(_listener.LocalHost.ToString(), buffer, State));
                await writer.StoreAsync();
            }
        }
        /// <summary>
        /// There are no custom descriptors for the SuperMutt and OSRFX2 devices, however, this method will show you how to
        /// navigate through raw descriptors. The raw descriptors can be found in UsbConfiguration and
        /// UsbInterface, and UsbInterfaceSetting. All possible descriptors that you would find in the full Configuration Descriptor
        /// are found under UsbConfiguration.
        /// All raw descriptors under UsbInterface are constrained only to those that are found under the InterfaceDescriptor
        /// that is defined in the Usb spec.
        ///
        /// Usb descriptor header (first 2 bytes):
        /// bLength             Size of descriptor in bytes
        /// bDescriptorType     The type of descriptor (configuration, interface, endpoint)
        /// </summary>
        private String GetCustomDescriptorsAsString()
        {
            String content = null;

            if (EventHandlerForDevice.Current.IsDeviceConnected)
            {
                // Descriptor information will be appended to this string and then printed to UI
                content = "Raw Descriptors";

                var configuration = EventHandlerForDevice.Current.Device.Configuration;
                var allRawDescriptors = configuration.Descriptors;

                // Print first 2 bytes of all descriptors within the configuration descriptor    
                // because the first 2 bytes are always length and descriptor type
                // the UsbDescriptor's DescriptorType and Length properties, but we will not use these properties
                // in order to demonstrate ReadDescriptorBuffer() and how to parse it.
                foreach (UsbDescriptor descriptor in allRawDescriptors)
                {
                    var descriptorBuffer = new Windows.Storage.Streams.Buffer(descriptor.Length);
                    descriptor.ReadDescriptorBuffer(descriptorBuffer);

                    DataReader reader = DataReader.FromBuffer(descriptorBuffer);

                    // USB data is Little Endian according to the USB spec.
                    reader.ByteOrder = ByteOrder.LittleEndian;

                    // ReadByte has a side effect where it consumes the current byte, so the next ReadByte will read the next character.
                    // Putting multiple ReadByte() on the same line (same variable assignment) may cause the bytes to be read out of order.
                    var length = reader.ReadByte().ToString("D", NumberFormatInfo.InvariantInfo);
                    var type = "0x" + reader.ReadByte().ToString("X2", NumberFormatInfo.InvariantInfo);

                    content += "\n\nDescriptor"
                        + "\nLength : " + length
                        + "\nDescriptorType : " + type;
                }
            }

            return content;
        }
        /// <summary>
        /// this is used when the user selects save to file
        /// </summary>
        /// <remarks>
        /// to implement this, we will need to create and instance of the save file picker
        /// then write the output stream into a file
        /// </remarks>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnSaveToFile_Click(object sender, RoutedEventArgs e)
        {
            string text = this.tbData.Text;


            // select the file to save this data to
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.DefaultFileExtension = ".wav";
            // this is the only type available
            savePicker.FileTypeChoices.Add("Audio file", new List<string>() { ".wav" });

            StorageFile file = await savePicker.PickSaveFileAsync();
            if (file != null)
            {
                this.btnSaveToFile.IsEnabled = false;

                // create the data stream
                SpeechSynthesisStream synthesisStream;
                try
                {
                    synthesisStream = await this.synthesizer.SynthesizeSsmlToStreamAsync(text);
                }
                catch (Exception)
                {
                    synthesisStream = null;
                    this.btnSaveToFile.IsEnabled = true;
                }

                if (synthesisStream == null)
                {
                    MessageDialog dialog = new MessageDialog("unable to synthesize text");
                    await dialog.ShowAsync();
                    return;
                }

                // open the output stream                    
                Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(4096);
                IRandomAccessStream writeStream = (IRandomAccessStream)await file.OpenAsync(FileAccessMode.ReadWrite);
                IOutputStream outputStream = writeStream.GetOutputStreamAt(0);
                DataWriter dataWriter = new DataWriter(outputStream);

                // copy the stream data into the file                    
                while (synthesisStream.Position < synthesisStream.Size)
                {
                    await synthesisStream.ReadAsync(buffer, 4096, InputStreamOptions.None);
                    dataWriter.WriteBuffer(buffer);
                }

                // close the data file streams
                dataWriter.StoreAsync().AsTask().Wait();
                outputStream.FlushAsync().AsTask().Wait();

                this.btnSaveToFile.IsEnabled = true;
            }
        }
 public async void StartListening()
 {
     while (true)
     {
         try
         {
             hostName = new HostName("localhost");
         }
         catch (ArgumentException)
         {
             continue;
         }
         //CoreApplication.Properties.Add("clientSocket", socket);
         try
         {
             socket = new StreamSocket();
             await socket.ConnectAsync(hostName, port1);
             //CoreApplication.Properties.Add("connected", null);
         }
         catch
         {
             continue;
         }
         try
         {
             Windows.Storage.Streams.Buffer b = new Windows.Storage.Streams.Buffer(6000);
             var xxx = await socket.InputStream.ReadAsync(b, b.Capacity, InputStreamOptions.None);
             DataReader dr = DataReader.FromBuffer(b);
             string str = dr.ReadString(dr.UnconsumedBufferLength);
             if (this.TorrentInfoReceived != null)
             {
                 TorrentInfo ti = Commons.Serializer.Deserialize<TorrentInfo>(str);
                 TorrentInfoReceived(ti);
             }
         }
         catch
         {
             //break;
         }
     }
    
 }
		private async Task<VideoDataStructure> saveNonLocalFileToLocalAndAddVideoToList(StorageFile storageFile)
		{
			VideoDataStructure pds = null;
			try
			{
				IRandomAccessStream iras = await storageFile.OpenReadAsync();
                Windows.Storage.Streams.Buffer MyBuffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(iras.Size));
                IBuffer iBuf = await iras.ReadAsync(MyBuffer, MyBuffer.Capacity, InputStreamOptions.None);
                string filename = DateTime.Now.ToString().Replace(":", "").Replace("/", "_").Replace("\\", "_").Replace(".", "").Replace("\"", "") + "lifemapcover" + storageFile.Name;
                string filePath = await Helper.SaveImages(iBuf, filename);
      
                StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(filePath);
                StorageItemThumbnail fileThumbnail = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, 600);
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(fileThumbnail);

				pds = new VideoDataStructure()
				{
					VideoData = new DataModel.VideoDataStructure()
					{
						AlbumId = albumInfo.Id,
						Latitude = albumInfo.Latitude,
						Longitude = albumInfo.Longitude,
						VideoPath = filePath,
						ItemId = DateTime.Now.ToString() + file.Path
					},
					Image = bitmapImage,
					VideoWidthHeight = Constants.HalfScreenHeight - 35,
					VideoWidth = (Constants.HalfScreenHeight - 35) * (Convert.ToDouble(bitmapImage.PixelWidth) / Convert.ToDouble(bitmapImage.PixelHeight))
				};
			}
			catch (Exception exp)
			{
				//Constants.ShowWarningDialog(Constants.ResourceLoader.GetString("2FileLocalizationFailed") + "\n\r" + exp.Message);
			}
			return pds;
		}
        //Tache async qui ecoute en permanance le serveur
        private async void ReadSocketAsync(StreamSocket _socket)
        {
            while (true)
            {
                const uint size = 2048;
                IBuffer buffer = new Windows.Storage.Streams.Buffer(size);
                buffer = await _socket.InputStream.ReadAsync(buffer, size,
                 InputStreamOptions.Partial);
                var handler = DataReceived;
                if (handler != null && buffer.Length > 0)
                {
                    byte[] Array = buffer.ToArray();
                    string reponse = Encoding.UTF8.GetString(Array, 0, Array.Length);
                    if (reponse != "<EOF>")
                    {
                        string[] separator = new string[] { "<EOF>" };
                        string[] phrases = reponse.Split(separator, StringSplitOptions.None);

                        foreach (string phrase in phrases)
                        {
                            if (phrase != "")
                            {
                                Newtonsoft.Json.Linq.JObject jsonNoData = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(phrase);

                                if (jsonNoData["action"].ToString() == "talk")
                                {
                                    reponse = jsonNoData["message"].ToString();
                                }
                                else if (jsonNoData["action"].ToString() == "execute")
                                {
                                    reponse = "Je ne peux pas faire cela...";
                                }
                                else if (jsonNoData["action"].ToString() == "sound")
                                {
                                    reponse = "Je ne peux pas faire cela...";
                                }   
                                handler(this, new DataReceivedEventArgs(reponse));
                                if (tts) parle(reponse);
                            }
                            
                        }
                        
                    }
                        

                         
                    if (allmessages.Count() != 0)
                    {
                        myChat.UpdateLayout();
                        myChat.ScrollIntoView(allmessages.Last());

                    }
                }

            }
        }
        private static async Task fillBackgroundImageNonLocal(LifeMapStructure lifeMap, StorageFile storageFile)
        {
            try
            {
                IRandomAccessStream iras = await storageFile.OpenReadAsync();
                Windows.Storage.Streams.Buffer MyBuffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(iras.Size));
                IBuffer iBuf = await iras.ReadAsync(MyBuffer, MyBuffer.Capacity, InputStreamOptions.None);
                string filename = DateTime.Now.ToString().Replace(":", "").Replace("/", "_").Replace("\\", "_").Replace(".", "").Replace("\"", "") + "lifemapcover" + storageFile.Name;
                string filePath = await Helper.SaveImages(iBuf, filename);
                lifeMap.ImagePath = filePath;
                await Utils.FilesSaver<LifeMapStructure>.SaveData(Data.LifeMapMgr.LifeMaps, Constants.NamingListLifeMaps);
                StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(lifeMap.ImagePath);
                StorageItemThumbnail fileThumbnail = await file.GetThumbnailAsync(ThumbnailMode.SingleItem, 800);
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(fileThumbnail);
                lifeMap.Image = bitmapImage;
                Helper.CreateToastNotifications(Constants.ResourceLoader.GetString("UpdatedLiftMapBackground"));
            }
            catch(Exception exp)
            {
				lifeMap.ImagePath = "";
				Utils.Constants.ShowWarningDialog(Constants.ResourceLoader.GetString("2cannotreadfile") + " : " + exp.Message + "\n\r" +
                                                  Constants.ResourceLoader.GetString("2possiblereasoncannotaccessnonlocalfile"));
            }
        }
        /// <summary>
        /// Caches the given object to the Application's ImageCache
        /// and returns the uri of the cached file.
        /// </summary>
        /// <param name="objectToCache">Object to cache</param>
        /// <param name="cacheFileName">Name of the cache file</param>
        /// <param name="progressHandler">Delegate for handling progress</param>
        /// <returns>Uri</returns>
        public async Task<Uri> GetCachedUriAsync(object objectToCache, string cacheFileName,
            CacheProgressHandler progressHandler = null)
        {
            // Check if the objectToCache is a valid Uri
            var uri = objectToCache as Uri;
            if (uri == null)
            {
                // Is the objectToCache a string representing a Uri?
                var uriString = objectToCache as string;
                if (uriString != null)
                {
                    // Try creating the Uri from the uriString
                    if (!(Uri.TryCreate(uriString, UriKind.RelativeOrAbsolute, out uri)))
                    {
                        return null;
                    }
                }
            }

            // Calculate the expiry date
            var expirationDate = DateTime.Now.Subtract(ImageCache.CacheDuration);
            // Get the cache folder location
            var cacheFolder = await ImageCache.GetCacheFolderAsync();
            if (cacheFolder == null)
                return null;

            // Report Progress
            progressHandler?.Invoke(0);

            // Get the cache file corresponding to the cacheFileName
            var cacheFile = await cacheFolder.TryGetItemAsync(cacheFileName) as StorageFile;

            // Has the cache file expired or does it not exist?
            if (await cacheFile.IsNullOrExpired(expirationDate))
            {
                try
                {
                    // Create/Recreate the cache file
                    cacheFile = await cacheFolder.CreateFileAsync(cacheFileName, CreationCollisionOption.ReplaceExisting);

                    using (var httpClient = new HttpClient())
                    {
                        // Use HttpCompletionOption.ResponseHeadersRead for the GetAsync call so that it returns as 
                        // soon as response headers are received and not when the whole response is received
                        using (var response = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
                        {
                            // If respose status is not success then raise exception
                            response.EnsureSuccessStatusCode();
                            // Open the cache file for writing
                            using (var cacheStream = await cacheFile.OpenAsync(FileAccessMode.ReadWrite))
                            {
                                // Start reading the content as a stream
                                using (var inputStream = await response.Content.ReadAsInputStreamAsync())
                                {
                                    ulong totalBytesRead = 0;
                                    var prevProgress = -1;
                                    var totalContentLength = response.Content.Headers.ContentLength ?? 0UL;
                                    while (true)
                                    {
                                        // Read from the stream
                                        IBuffer buffer = new Windows.Storage.Streams.Buffer(2048);
                                        buffer = await inputStream.ReadAsync(buffer, buffer.Capacity,
                                                                             InputStreamOptions.None);

                                        if (buffer.Length == 0)
                                        {
                                            // There is nothing else to read
                                            break;
                                        }

                                        // The following code can be used to report progress
                                        totalBytesRead += buffer.Length;
                                        if (totalContentLength > 0UL)
                                        {
                                            // We will report a progress percent between 0%-80% because caching represents 80%
                                            // of the task of displaying the image. The other 20% requires successful loading 
                                            // of the cached image.
                                            var progress =
                                                (int)Math.Round((totalBytesRead * 80) / (double)totalContentLength);
                                            if (progress != prevProgress)
                                            {
                                                // Report Progress
                                                progressHandler?.Invoke(progress);
                                                prevProgress = progress;
                                            }
                                        }
                                        else
                                        {
                                            prevProgress = Math.Min(prevProgress + 1, 80);
                                            // Report Progress
                                            progressHandler?.Invoke(prevProgress);
                                        }

                                        // Write to cache file
                                        await cacheStream.WriteAsync(buffer);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    // In case any exception occurs during the downloading or caching
                    // delete the cacheFile and return a 'null' Uri
                    cacheFile = await cacheFolder.TryGetItemAsync(cacheFileName) as StorageFile;
                    if (cacheFile != null)
                    {
                        await cacheFile.DeleteAsync();
                    }

                    // Report Progress
                    progressHandler?.Invoke(-1);

                    return null;
                }
            }

            // Report Progress
            // Caching indicates only half of the task completed i.e. 50% progress,
            // Progress will be 100% only when the image is loaded successfully on the ImageFrame
            progressHandler?.Invoke(80);

            // Now that we have a valid cached file for the Uri, return the Uri of the cached inputFile
            return new Uri($"ms-appdata:///temp/{ImageCache.CacheFolderName}/{cacheFileName}");
        }
        private async void PollInput(IAsyncAction operation)
        {
            while (!_tokenSource.IsCancellationRequested)
            {
                try
                {
                    IBuffer sizeBuffer = new Buffer(2);
                    await _socket.InputStream.ReadAsync(sizeBuffer, 2, InputStreamOptions.None);
                    uint size = (uint)((sizeBuffer.GetByte(0) | sizeBuffer.GetByte(1) << 8));

                    if (size != 0)
                    {
                        IBuffer report = new Buffer(size);
                        await _socket.InputStream.ReadAsync(report, size, InputStreamOptions.None);
                        if (ReportReceived != null)
                            ReportReceived(this, new ReportReceivedEventArgs { Report = report.ToArray() });
                    }
                }
                catch (Exception)
                {
                    // swallow exceptions...if we tank here, it's likely a disconnect and we can't do much anyway
                }
            }
        }
Beispiel #54
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            using (new BackgroundTaskDeferralWrapper(taskInstance.GetDeferral()))
            {
                try
                {
                    var details = (SocketActivityTriggerDetails)taskInstance.TriggerDetails;
                    switch (details.Reason)
                    {
                        case SocketActivityTriggerReason.SocketActivity:

                            string request = null;
                            using (var socketOperation = Hub.Instance.SignalingSocketService.SocketOperation)
                            {
                                if (socketOperation.Socket != null)
                                {
                                    var socket = socketOperation.Socket;

                                    const uint length = 65536;
                                    var readBuf = new Buffer(length);

                                    var readOp = socket.InputStream.ReadAsync(readBuf, length, InputStreamOptions.Partial);
                                    // This delay is to limit how long we wait for reading.
                                    // StreamSocket has no ability to peek to see if there's any
                                    // data waiting to be read.  So we have to limit it this way.
                                    for (int i = 0; i < 100 && readOp.Status == Windows.Foundation.AsyncStatus.Started; ++i)
                                    {
                                        await Task.Delay(10);
                                    }
                                    await socket.CancelIOAsync();

                                    try
                                    {
                                        var localBuffer = await readOp;
                                        var dataReader = DataReader.FromBuffer(localBuffer);
                                        request = dataReader.ReadString(dataReader.UnconsumedBufferLength);
                                    }
                                    catch (Exception ex)
                                    {
                                        Debug.WriteLine($"ReadAsync exception probably due to timeout: {ex.Message}");
                                    }
                                }
                            }
                            if (request != null)
                            {
                                Hub.Instance.SignalingClient.HandleRequest(request);
                            }
                            break;
                        case SocketActivityTriggerReason.KeepAliveTimerExpired:
                            Hub.Instance.SignalingClient.ClientHeartBeat();
                            break;
                        case SocketActivityTriggerReason.SocketClosed:
                            Hub.Instance.SignalingClient.ServerConnectionError();
                            //ToastNotificationService.ShowToastNotification("Disconnected.");
                            break;
                    }
                }
                catch (Exception exception)
                {
                    Hub.Instance.SignalingClient.ServerConnectionError();
                    ToastNotificationService.ShowToastNotification(string.Format("Error in SignalingTask: {0}",
                        exception.Message));
                }
            }
        }
        /// <summary>
        /// Await loading an image from an external web site
        /// </summary>
        /// <param name="uri"></param>
        public async Task<WriteableBitmap> LoadImageWriteableBitmapFromWeb(Uri uri)
        {
            // From Petzold, Programming Windows, 6th edition pg. 692-3
            /* This simple method will return before the file read is complete.  As expected, this is a problem:  
                RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri);
                IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync();
                WriteableBitmap wb = new WriteableBitmap(1, 1); // dummy values
                wb.SetSource(fileStream);
                return wb; */
            try
            {
                RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(uri);

                // Create a buffer for reading the stream:
                Windows.Storage.Streams.Buffer buffer = null;
                // Read the entire file:
                using (IRandomAccessStreamWithContentType fileStream = await streamRef.OpenReadAsync())
                {
                    buffer = new Windows.Storage.Streams.Buffer((uint)fileStream.Size);
                    await fileStream.ReadAsync(buffer, (uint)fileStream.Size, InputStreamOptions.None);
                }
                WriteableBitmap wb = new WriteableBitmap(1, 1); // dummy values
                // Create a memory stream for transferring the data
                using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
                {
                    await memoryStream.WriteAsync(buffer);
                    memoryStream.Seek(0);
                    // Use the memory stream as the Bitmap Source
                    wb.SetSource(memoryStream);
                }
                return wb;
            }
            catch(Exception)
            {
                return null; // new Dec 2014.  Probably bad, dangling uri.  Let caller report & handle error.
            }
        }
        private async Task<HttpRequest> ReadRequest(StreamSocket client)
        {
            try
            {
                IBuffer buffer = new Buffer(2048);
                await client.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);

                var binaryRequest = buffer.ToArray();
                var requestText = Encoding.ASCII.GetString(binaryRequest, 0, binaryRequest.Length);

                HttpRequest request;
                new HttpRequestParser(requestText).TryParse(out request);

                return request;
            }
            catch (Exception exception)
            {
                Debug.WriteLine("Failed to read HTTP request. " + exception.Message);
                return null;
            }
        }
        private async Task<string> CreateSpeechSynthesisFile(TTSMessage item)
        {
                string filename = String.Format("{0}.wav", Guid.NewGuid());

                try
                {
                    // get system voice that matches the gender
                    var voice = (from v in voices
                                 where v.Gender == (Windows.Media.SpeechSynthesis.VoiceGender)item.VoiceGender.VoiceGenderId
                                 select v).FirstOrDefault<VoiceInformation>();

                    synthesizer.Voice = voice;

                    // create the data stream
                    SpeechSynthesisStream synthesisStream;
                    try
                    {
                        synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(item.Message);
                    }
                    catch (Exception ex)
                    {
                        ri.SendException("Unable to synthesize text", ex);
                        synthesisStream = null;
                        return string.Empty;
                    }

                    ri.SendMessage("Creating file '{0}'", filename);

                StorageFolder folder = await StorageFolder.GetFolderFromPathAsync("C:\\temp\\TTS"); //Windows.Storage.KnownFolders.DocumentsLibrary;// Windows.Storage.ApplicationData.Current.LocalFolder;
                    var option = CreationCollisionOption.ReplaceExisting;
                    StorageFile file = await folder.CreateFileAsync(filename, option);

                    ri.SendMessage("File '{0}' created. Text to speech synthesis has started...", file.Path); 

                    // open the output stream                    
                    Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(4096);
                    IRandomAccessStream writeStream = (IRandomAccessStream)await file.OpenAsync(FileAccessMode.ReadWrite);
                    IOutputStream outputStream = writeStream.GetOutputStreamAt(0);
                    DataWriter dataWriter = new DataWriter(outputStream);

                    // copy the stream data into the file                    
                    while (synthesisStream.Position < synthesisStream.Size)
                    {
                        await synthesisStream.ReadAsync(buffer, 4096, InputStreamOptions.None);
                        dataWriter.WriteBuffer(buffer);
                    }

                    // close the data file streams
                    dataWriter.StoreAsync().AsTask().Wait();
                    outputStream.FlushAsync().AsTask().Wait();

                    ri.SendMessage("Text to speech synthesis completed for file '{0}'", file.Name);
                }
                catch (Exception e)
                {
                    ri.SendException(e);
                    return String.Empty;

                }
                return filename;
        }
 private async void _socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
 {
     var stream = args.GetDataStream();
 
     IBuffer buffer = new Windows.Storage.Streams.Buffer(10240);
     var bytesRead = buffer.Capacity;
     while (bytesRead == buffer.Capacity)
     {
         IBuffer data = await stream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);
         bytesRead = data.Length;
         if (data.Length == 0) break;
         _emitRecv(data, args.RemoteAddress.DisplayName, Int32.Parse(args.RemotePort));
     }
 }
        /// <summary>
        /// Caches the given object to the Application's ImageCache
        /// and returns the uri of the cached file.
        /// </summary>
        /// <param name="objectToCache">Object to cache</param>
        /// <param name="cacheFileName">Name of the cache file</param>
        /// <param name="progressHandler">Delegate for handling progress</param>
        /// <returns>Uri</returns>
        public async Task<Uri> GetCachedUriAsync(object objectToCache, string cacheFileName,
            CacheProgressHandler progressHandler = null)
        {
            // Check if the objectToCache is a valid IRandomAccessStream
            var stream = objectToCache as IRandomAccessStream;
            if ((stream == null) || !stream.CanRead)
                return null;

            // Calculate the expiry date
            var expirationDate = DateTime.Now.Subtract(ImageCache.CacheDuration);
            // Get the cache folder location
            var cacheFolder = await ImageCache.GetCacheFolderAsync();
            if (cacheFolder == null)
                return null;

            // Report Progress
            progressHandler?.Invoke(0);

            // Get the cache file corresponding to the cacheFileName
            var cacheFile = await cacheFolder.TryGetItemAsync(cacheFileName) as StorageFile;

            // Has the cache file expired or does it not exist?
            if (await cacheFile.IsNullOrExpired(expirationDate))
            {
                try
                {
                    // Create/Recreate the cache file
                    cacheFile = await cacheFolder.CreateFileAsync(cacheFileName, CreationCollisionOption.ReplaceExisting);
                    // Open the cache file for writing
                    using (var cacheStream = await cacheFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        // Start reading the content as a stream
                        using (var inputStream = stream.GetInputStreamAt(0))
                        {
                            ulong totalBytesRead = 0;
                            var prevProgress = -1;
                            var totalContentLength = stream.Size;
                            if (totalContentLength <= 0UL)
                            {
                                prevProgress = 0;
                            }
                            while (true)
                            {
                                // Read from the stream
                                IBuffer buffer = new Windows.Storage.Streams.Buffer(2048);
                                buffer = await inputStream.ReadAsync(buffer, buffer.Capacity,
                                                                     InputStreamOptions.None);

                                if (buffer.Length == 0)
                                {
                                    // There is nothing else to read
                                    break;
                                }

                                // The following code can be used to report progress
                                totalBytesRead += buffer.Length;
                                if (totalContentLength > 0UL)
                                {
                                    // We will report a progress percent between 0%-80% because caching represents 80%
                                    // of the task of displaying the image. The other 20% requires successful loading 
                                    // of the cached image.
                                    var progress =
                                        (int)Math.Round((totalBytesRead * 80) / (double)totalContentLength);
                                    if (progress != prevProgress)
                                    {
                                        // Report Progress
                                        progressHandler?.Invoke(progress);
                                        prevProgress = progress;
                                    }
                                }
                                else
                                {
                                    prevProgress = Math.Min(prevProgress + 1, 80);
                                    // Report Progress
                                    progressHandler?.Invoke(prevProgress);
                                }

                                // Write to cache file
                                await cacheStream.WriteAsync(buffer);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    // In case any exception occurs during the copying of the StorageFile
                    // delete the cacheFile and return a 'null' Uri
                    cacheFile = await cacheFolder.TryGetItemAsync(cacheFileName) as StorageFile;
                    if (cacheFile != null)
                    {
                        await cacheFile.DeleteAsync();
                    }

                    // Report Progress
                    progressHandler?.Invoke(-1);

                    return null;
                }
            }

            // Report Progress
            // Caching indicates only half of the task completed i.e. 50% progress,
            // Progress will be 100% only when the image is loaded successfully on the ImageFrame
            progressHandler?.Invoke(80);

            // Now that we have a valid cached file for the Uri, return the Uri of the cached inputFile
            return new Uri($"ms-appdata:///temp/{ImageCache.CacheFolderName}/{cacheFileName}");
        }
 //private StreamSocket _socket;
 private async void button_Click(object sender, RoutedEventArgs e)
 {
     OutBuff = new Windows.Storage.Streams.Buffer(100);
     Button button = (Button)sender;
     if (button != null)
     {
         switch ((string)button.Content)
         {
             case "Disconnect":
                 await this._socket.CancelIOAsync();
                 _socket.Dispose();
                 _socket = null;
                 this.textBlockBTName.Text = "";
                 this.TxtBlock_SelectedID.Text = "";
                 this.buttonDisconnect.IsEnabled = false;
                 this.buttonSend.IsEnabled = false;
                 this.buttonStartRecv.IsEnabled = false;
                 this.buttonStopRecv.IsEnabled = false;
                 break;
             case "Send":
                 //await _socket.OutputStream.WriteAsync(OutBuff);
                 Send(this.textBoxSendText.Text);
                 this.textBoxSendText.Text = "";
                 break;
             case "Clear Send":
                 this.recvdText.Text = "";
                 break;
             case "Start Recv":
                 this.buttonStartRecv.IsEnabled = false;
                 this.buttonStopRecv.IsEnabled = true;
                 Listen();
                 break;
             case "Stop Recv":
                 this.buttonStartRecv.IsEnabled = false;
                 this.buttonStopRecv.IsEnabled = false;
                 CancelReadTask();
                 break;
             case "Refresh":
                 InitializeRfcommDeviceService();
                 break;
             case "Back":
                 //this.Frame.GoBack();
                 backButton_Click(null, null);
                 break;
         }
     }
 }