private async Task Download(string url,StorageFile file,bool cover)
        {
            var http = new HttpClient();
            byte[] response = { };
            string betterUrl = url;
            if(cover)
            {
                var pos = betterUrl.IndexOf(".jpg");
                if (pos != -1)
                    betterUrl = betterUrl.Insert(pos, "l");
            }

            //get bytes
            try
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(betterUrl));
            }
            catch (Exception)
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(url));
            }

            var fs = await file.OpenStreamForWriteAsync(); //get stream
            var writer = new DataWriter(fs.AsOutputStream());

            writer.WriteBytes(response); //write
            await writer.StoreAsync();
            await writer.FlushAsync();

            writer.Dispose();
        }
        public static async Task<bool> ConnectAsync()
        {
            if (imageComparisonServer != null)
                return true;
			
            try
            {
                imageComparisonServer = new StreamSocket();
                await imageComparisonServer.ConnectAsync(new HostName(ParadoxImageServerHost), ParadoxImageServerPort.ToString());
			
                // Send initial parameters
                using (var memoryStream = new MemoryStream())
                {
                    var binaryWriter = new BinaryWriter(memoryStream);
                    ImageTestResultConnection.Write(binaryWriter);

                    var dataWriter = new DataWriter(imageComparisonServer.OutputStream);
                    dataWriter.WriteBytes(memoryStream.ToArray());
                    await dataWriter.StoreAsync();
                    await dataWriter.FlushAsync();
                    dataWriter.DetachStream();
                }

                return true;
            }
            catch (Exception)
            {
                imageComparisonServer = null;
			
                return false;
            }
        }
        //</SnippetVertices>

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

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

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

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

            writer.WriteString(replacedText);

            await writer.StoreAsync();

            await writer.FlushAsync();

            writer.DetachStream();
            return(outputStream);
        }
        public async void PerformPeerDiscovery()
        {
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Start();

            if (socket == null)
            {
                socket = new DatagramSocket();
                socket.MessageReceived += socket_MessageReceived;

                try
                {
                    await socket.BindEndpointAsync(null, "22002");
                }
                catch
                {
                    // Swallow any already bound exceptions!
                }
            }

            using (var outputStream = await socket.GetOutputStreamAsync(new HostName("230.0.0.1"), "22003"))
            {
                using (DataWriter wr = new DataWriter(outputStream))
                {
                    wr.WriteString("**BECHARMING DISCOVERY**");
                    await wr.FlushAsync();
                    await wr.StoreAsync();
                }
            }
        }
Exemple #5
0
        //private uint sizeOfPixel = 4;
        private async void createTile(IRandomAccessStream tileStream, Color color)
        {
            // Create the data writer object backed by the in-memory stream.
            using (var dataWriter = new Windows.Storage.Streams.DataWriter(tileStream))
            {
                for (uint y = 0; y < sizeOfMapTile; y++)
                {
                    for (uint x = 0; x < sizeOfMapTile; x++)
                    {
                        // RGBA
                        dataWriter.WriteByte(color.R);
                        dataWriter.WriteByte(color.G);
                        dataWriter.WriteByte(color.B);
                        dataWriter.WriteByte(color.A);
                    }
                }

                // Send the contents of the writer to the backing stream.
                await dataWriter.StoreAsync();

                // For the in-memory stream implementation we are using, the flushAsync call
                // is superfluous,but other types of streams may require it.
                await dataWriter.FlushAsync();

                // In order to prolong the lifetime of the stream, detach it from the
                // DataWriter so that it will not be closed when Dispose() is called on
                // dataWriter. Were we to fail to detach the stream, the call to
                // dataWriter.Dispose() would close the underlying stream, preventing
                // its subsequent use by the DataReader below.
                dataWriter.DetachStream();
            }
        }
        public async void StoreData()
        {
            var stream = await _dataFile.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.AllowReadersAndWriters);

            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    const string delinieater = ";";
                    foreach (double[] data in _data)
                    {
                        foreach (double d in data)
                        {
                            dataWriter.WriteDouble(d);
                            dataWriter.WriteString(delinieater);
                        }
                    }
                    await dataWriter.FlushAsync();
                }
            }
            stream.Dispose();

            _dataLineCount += _data.Count();

            if (_dataLineCount >= LINE_LIMIT)
            {
                await CreateDataFile();
            }
            _data = new List <double[]>();
        }
Exemple #7
0
        public async Task SendAsync(string text)
        {
            try
            {
                // DataWriter to send message to client
                var writer = new DataWriter(_socket.OutputStream);
                //Encrypt message
                byte[] data = Cryptographic.Encrypt(text, "123");

                //Write Lenght message in buffer
                writer.WriteInt32(data.Length);
                //Write message in buffer
                writer.WriteBytes(data);

                //Send buffer
                await writer.StoreAsync();
                //Clear buffer
                await writer.FlushAsync();

            }
            catch (Exception e)
            {
                InvokeOnError(e.Message);
            }
        }
Exemple #8
0
    public static async Task <Windows.UI.Xaml.Media.Imaging.BitmapImage> GetBitmapAsync(byte[] data)
    {
        if (data is null)
        {
            return(null);
        }

        var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();

        using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
        {
            using (var writer = new Windows.Storage.Streams.DataWriter(stream))
            {
                writer.WriteBytes(data);
                await writer.StoreAsync();

                await writer.FlushAsync();

                writer.DetachStream();
            }

            stream.Seek(0);
            await bitmapImage.SetSourceAsync(stream);
        }
        return(bitmapImage);
    }
		private async Task ExecuteDiscoveryTask()
		{
			int repeatTime = EndpointController.REPEAT_DISCOVERY_TASK / 2;

			while (running)
			{
				Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Started Cloudlet Discovery using Multicast UDP");
				retry = 0;

				DatagramSocket socketSent = null;
				DatagramSocket socketReplay = null;
				try
				{
					socketSent = new DatagramSocket();
					await socketSent.BindEndpointAsync(null, string.Empty);
					socketSent.JoinMulticastGroup(ip);

					socketReplay = new DatagramSocket();
					socketReplay.MessageReceived += SocketOnMessageReceived;
					await socketReplay.BindServiceNameAsync(replyCloudletPort.ToString());

					using (DataWriter writer = new DataWriter(await socketSent.GetOutputStreamAsync(ip, multicastPort.ToString())))
					{
						while (retry < 60 && running)
						{
							writer.WriteString("mpos_cloudlet_req");
							await writer.StoreAsync();
							await writer.FlushAsync();

							await Task.Delay(500);
							retry++;
						}
					}
				}
				catch (IOException e)
				{
					Debug.WriteLine("## [DiscoveryCloudletMulticast]: Any problem with i/o in multicast system!\n" + e.ToString());
				}
				finally
				{
					socketSent.Dispose();
					socketReplay.Dispose();

					socketSent = null;
					socketReplay = null;
				}

				if (running)
				{
					Debug.WriteLine(">> [DiscoveryCloudletMulticast]: Retry Discovery Cloudlet, in " + repeatTime + " ms");
					await Task.Delay(repeatTime);
				}
				else
				{
					Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Finished Discovery Cloudlet");
				}
			}
		}
        /// <summary>
        /// Attempts to send a magic packet to the desination hostname, on the specified port with the specified MAC address.
        /// </summary>
        /// <param name="destination">Destination hostname or IP address.</param>
        /// <param name="destinationPort">Destination port number.</param>
        /// <param name="targetMac">Destination MAC address. Bytes can be separated by colons, dashes, or nothing.</param>
        /// <returns>True if magic packet is sent successfully, false otherwise.</returns>
        public async Task<bool> SendMagicPacket(Windows.Networking.HostName destination, uint destinationPort, string targetMac)
        {
            try
            {
                DatagramSocket _socket = new DatagramSocket();               

                using (var stream = await _socket.GetOutputStreamAsync(destination, destinationPort.ToString()))
                {
                    //Split on common MAC separators
                    char? splitChar = null;
                    if (targetMac.Contains('-'))
                        splitChar = '-';
                    else if (targetMac.Contains(':'))
                        splitChar = ':';
                    else if (targetMac.Contains(' '))
                        splitChar = ' ';

                    //Turn MAC into array of bytes
                    byte[] macAsArray;
                    if (splitChar != null)
                    {
                        macAsArray = targetMac.Split((char)splitChar)
                            .Select(b => Convert.ToByte(b, 16))
                            .ToArray<byte>();
                    }
                    else
                    {
                        //Jump through MAC-string, reading 2 chars at a time
                        macAsArray = Enumerable.Range(0, targetMac.Length)
                            .Where(x => x % 2 == 0)
                            .Select(x => Convert.ToByte(targetMac.Substring(x, 2), 16)) //16 = hexadecimal
                            .ToArray();
                    }

                    List<byte> magicPacket = new List<byte> { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

                    //A WoLAN magic packet is just FF FF FF FF FF FF, then the target MAC adress repeated 16 times.
                    for (int i = 0; i < 16; i++)
                    {
                        magicPacket = magicPacket.Concat(macAsArray).ToList();
                    }

                    using (DataWriter writer = new DataWriter(stream))
                    {
                        writer.WriteBytes(magicPacket.ToArray<byte>());
                        await writer.StoreAsync();
                        await writer.FlushAsync();
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                return false;
            }
        }       
Exemple #11
0
 private static async Task<IInputStream> GetStreamForByteArray(string content2)
 {
     var ras = new InMemoryRandomAccessStream();
     var datawriter = new DataWriter(ras);
     datawriter.WriteString(content2);
     //datawriter.WriteBytes(content2);
     await datawriter.StoreAsync();
     await datawriter.FlushAsync();
     return ras.GetInputStreamAt(0);
 }
 async Task Send(FayeObject o) {
     if (o is FayeRequest) 
         (o as FayeRequest).ClientID = ClientID;
     using (var writer = new DataWriter(_socket.OutputStream)) {
         writer.UnicodeEncoding = UnicodeEncoding.Utf8;
         var stringd = await Helpers.SerializeAsync(o);
         writer.WriteString(stringd);
         await writer.StoreAsync();
         await writer.FlushAsync();
         writer.DetachStream();
     }
 }
        /// <summary>
        /// Gets intent and entities from a text string
        /// </summary>
        /// <returns>Unprocessed result from a server</returns>
        public async Task<string> GetAsync()
        {
            return await Task.Run<string>(async () =>
            {
                try
                {
                    var socket = new StreamSocket();

                    var writer = new DataWriter(socket.OutputStream);
                    var reader = new DataReader(socket.InputStream);
                    reader.InputStreamOptions = InputStreamOptions.Partial;

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.AppendLine(String.Format("GET /message?q={0} HTTP/1.1", HttpUtility.UrlEncode(message)));
                    stringBuilder.AppendLine("Host: api.wit.ai");
                    stringBuilder.AppendLine(String.Format("Authorization: Bearer {0}", accessToken));
                    stringBuilder.AppendLine("");
                    string headers = stringBuilder.ToString();
                    byte[] headersPayload = Encoding.UTF8.GetBytes(headers);

                    await socket.ConnectAsync(new HostName("wit.ai"), "443", SocketProtectionLevel.SslAllowNullEncryption);

                    writer.WriteBytes(headersPayload);

                    WitLog.Log("Sending text...");

                    await writer.StoreAsync();
                    await writer.FlushAsync();

                    var count = await reader.LoadAsync(UInt16.MaxValue);
                    string response = reader.ReadString(count);

                    int bodyStartIndex = response.IndexOf("\r\n\r\n");

                    if (bodyStartIndex != -1)
                    {
                        string body = response.Substring(bodyStartIndex + 4);

                        WitLog.Log(body);

                        return body;
                    }
                    else
                    {
                        return null;
                    }
                }
                catch
                {
                    return null;
                }
            });
        }
Exemple #14
0
        private async void cutTile(IRandomAccessStream stream, int pixeloffsetX, int pixeloffsetY, int levelOfDetail)
        {
            // Create the data writer object backed by the in-memory stream.
            using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
            {
                //dataWriter.dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;

                for (int y = 0; y < sizeOfMapTile; y++)
                {
                    for (int x = 0; x < sizeOfMapTile; x++)
                    {
                        double lat, lon = 0.0;

                        Microsoft.MapPoint.TileSystem.PixelXYToLatLong(pixeloffsetX + x, pixeloffsetY + y, levelOfDetail, out lat, out lon);
                        BasicGeoposition point = new BasicGeoposition {
                            Latitude = lat, Longitude = lon
                        };

                        if (PathCache.pointInPolygon(point.Longitude, point.Latitude))
                        {
                            // RGBA
                            dataWriter.WriteByte(ColorIn.R);
                            dataWriter.WriteByte(ColorIn.G);
                            dataWriter.WriteByte(ColorIn.B);
                            dataWriter.WriteByte(ColorIn.A);
                        }
                        else
                        {
                            // RGBA
                            dataWriter.WriteByte(ColorOut.R);
                            dataWriter.WriteByte(ColorOut.G);
                            dataWriter.WriteByte(ColorOut.B);
                            dataWriter.WriteByte(ColorOut.A);
                        }
                    }
                }

                // Send the contents of the writer to the backing stream.
                await dataWriter.StoreAsync();

                // For the in-memory stream implementation we are using, the flushAsync call
                // is superfluous,but other types of streams may require it.
                await dataWriter.FlushAsync();

                // In order to prolong the lifetime of the stream, detach it from the
                // DataWriter so that it will not be closed when Dispose() is called on
                // dataWriter. Were we to fail to detach the stream, the call to
                // dataWriter.Dispose() would close the underlying stream, preventing
                // its subsequent use by the DataReader below.
                dataWriter.DetachStream();
            }
        }
    private async System.Threading.Tasks.Task SendMessage(byte[] data)
    {
        using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(externalIP), externalPort))
        {
            using (var writer = new Windows.Storage.Streams.DataWriter(stream))
            {
                writer.WriteBytes(data);
                await writer.StoreAsync();

                await writer.FlushAsync();
            }
        }
    }
        public void Send(string message)
        {
            var ostream = this.streamSocket.OutputStream;
            var dataWriter = new DataWriter(ostream);

            byte[] msgByteArray = Helpers.stringToByteArray(message);
            byte[] msgSizeByteArray = Helpers.intToByteArray(msgByteArray.Length);

            dataWriter.WriteBytes(msgSizeByteArray);
            dataWriter.WriteBytes(msgByteArray);
            dataWriter.StoreAsync().AsTask().Wait();
            dataWriter.FlushAsync().AsTask().Wait();
        }
Exemple #17
0
        /// <summary>
        /// Send a message to the server.
        /// This message is specified in the JsonObject message.
        /// The byteorder of the send message is LittleEndian and the encoding is Utf8.
        /// </summary>
        /// <param name="message">The message to be send.</param>
        /// <returns>A boolean that indicates that the message was succesfully send.</returns>
        public async Task <bool> SendMessage(JsonObject message)
        {
            //Check if the connector is connected. If not, call the Connect() function.
            if (!isConnected)
            {
                await Connect();
            }

            //Write the message to the server.
            //Code used from https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datawriter
            try
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(socket.OutputStream))
                {
                    dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    dataWriter.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

                    // Parse the input stream and write each element separately.
                    //Get the string version of the json object.
                    var stringToSend = message.ToString();

                    //Get the length of the stream, so the server knows how much data was send.
                    uint inputElementSize = dataWriter.MeasureString(stringToSend);
                    dataWriter.WriteUInt32(inputElementSize);
                    dataWriter.WriteString(stringToSend);

                    Debug.WriteLine("Wrote" + stringToSend);
                    Debug.WriteLine("Lenght:" + inputElementSize);

                    // Send the contents of the writer to the backing stream.
                    await dataWriter.StoreAsync();

                    // For the in-memory stream implementation we are using, the flushAsync call
                    // is superfluous,but other types of streams may require it.
                    await dataWriter.FlushAsync();

                    // In order to prolong the lifetime of the stream, detach it from the
                    // DataWriter so that it will not be closed when Dispose() is called on
                    // dataWriter. Were we to fail to detach the stream, the call to
                    // dataWriter.Dispose() would close the underlying stream, preventing
                    // its subsequent use by the DataReader below.
                    dataWriter.DetachStream();
                    return(true);
                }
            }
            catch
            {
                //TODO on error?
                throw;
            }
        }
Exemple #18
0
        public async void WriteToSocketUsingReader(IBuffer buffer)
        {
            using (var dataWriter = new Windows.Storage.Streams.DataWriter(socket.OutputStream))
            {
                dataWriter.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian;
                dataWriter.WriteUInt32(buffer.Length);
                dataWriter.WriteBuffer(buffer);
                await dataWriter.StoreAsync();

                await dataWriter.FlushAsync();

                dataWriter.DetachStream();
            }
        }
        public async Task SaveAsync(string filePath, byte[] content)
        {
            StorageFile file = await GetFileAsync(filePath);

            using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (DataWriter dataWriter = new DataWriter(writeStream))
                {
                    dataWriter.WriteBytes(content);
                    await dataWriter.StoreAsync();
                    await dataWriter.FlushAsync();
                }
            }
        }
        /// <summary>
        /// Use for small assets
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        public static async Task<IRandomAccessStream> DownloadFileAsync(LibrelioUrl url, CancellationToken cancelToken = default(CancellationToken))
        {
            var stream = new InMemoryRandomAccessStream();

            using(var response = await new HttpClient().GetAsync(url.AbsoluteUrl))
            {
                var buffer = await response.Content.ReadAsStringAsync();
                var dataWriter = new DataWriter(stream.GetOutputStreamAt(0));
                dataWriter.WriteString(buffer);
                await dataWriter.StoreAsync();
                await dataWriter.FlushAsync();
            }

            return stream;
        }
		protected override async void OnResponse(object sender, XmlRpcResponseEventArgs e)
		{
			string fname = string.Format("{0}/{1}-{2:0000}-response-{3}.xml",
			  _directory, DateTime.Now.Ticks, e.RequestNum, e.ProxyID);
			var file = await Directory.CreateFileAsync(fname, CreationCollisionOption.ReplaceExisting);
			using (var str = await file.OpenAsync(FileAccessMode.ReadWrite))
			{
				using (var dw = new DataWriter(str))
				{
					await e.ResponseStream.CopyToAsync(str.AsStreamForWrite());
					await dw.FlushAsync();
					dw.DetachStream();
				}
			}
		}
        private async Task<IRandomAccessStream> ConvertToRandomAccessStream(byte[] bytes)
        {
            var randomAccessStream = new InMemoryRandomAccessStream();
            using (var writer = new DataWriter(randomAccessStream))
            {
                writer.WriteBytes(bytes);
                await writer.StoreAsync();
                await writer.FlushAsync();
                writer.DetachStream();
                writer.Dispose();
            }
            randomAccessStream.Seek(0);

            return randomAccessStream;
        }
        /// <summary>
        /// Sets source of the BitmapImage to specified byte array.
        /// </summary>
        public static async Task SetSourceAsync(this BitmapImage image, byte[] data)
        {
            using (var stream = new InMemoryRandomAccessStream())
            {
                using (var writer = new DataWriter(stream))
                {
                    writer.WriteBytes(data);
                    await writer.StoreAsync();
                    await writer.FlushAsync();
                    writer.DetachStream();
                }

                stream.Seek(0);
                await image.SetSourceAsync(stream);
            }
        }
Exemple #24
0
    private async void send_data(string dataToSend)
    {
        Debug.Log("sending message: " + dataToSend);
        using (var dataWriter = new Windows.Storage.Streams.DataWriter(streamSocket.OutputStream)){
            dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            dataWriter.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

            dataWriter.WriteString(dataToSend);
            await dataWriter.StoreAsync();

            await dataWriter.FlushAsync();

            dataWriter.DetachStream();
        }
        Debug.Log("message sent");
    }
    //手柄按钮被按以后发送信息
    private async System.Threading.Tasks.Task SendControllerInfo(string message)
    {
        using (var stream = await socket.GetOutputStreamAsync(new Windows.Networking.HostName(local), externalPort))
        {
            using (var writer = new Windows.Storage.Streams.DataWriter(stream))
            {
                var data = Encoding.UTF8.GetBytes(message);
                writer.WriteBytes(data);
                await writer.StoreAsync();

                await writer.FlushAsync();

                Debug.Log("Sent: " + message);
            }
        }
    }
Exemple #26
0
 async public void SendRawMessage(string message)
 {
     if (!_connected) return;
     var writer = new DataWriter(_clientSocket.OutputStream);
     byte[] header = BitConverter.GetBytes(message.Length);
     if (BitConverter.IsLittleEndian)
         Array.Reverse(header);
     writer.WriteBytes(header);
     writer.WriteString(message);
     await writer.StoreAsync();
     await writer.FlushAsync();
     System.Diagnostics.Debug.WriteLine("Sent : header = " + BitConverter.ToString(header) + " | body = " + message);
     writer.DetachStream();
     //_clientSocket.Dispose();
     //_connected = false;
 }
        /// <summary>
        /// Use for small assets
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cancelToken"></param>
        /// <returns></returns>
        public static async Task<IRandomAccessStream> DownloadFileAsync(LibrelioUrl url, CancellationToken cancelToken = default(CancellationToken))
        {
            var stream = new InMemoryRandomAccessStream();
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("user-agent", "LibrelioWinRT");

            using (var response = await client.GetAsync(url))
            {
                var buffer = await response.Content.ReadAsStringAsync();
                var dataWriter = new DataWriter(stream.GetOutputStreamAt(0));
                dataWriter.WriteString(buffer);
                await dataWriter.StoreAsync();
                await dataWriter.FlushAsync();
            }

            return stream;
        }
 public static async Task CopyStreamAsync(this IInputStream src, IOutputStream outStream, uint bufferSize = 16384)
 {
     using (var rd = new DataReader(src))
     {
         using (var wr = new DataWriter(outStream))
         {
             do
             {
                 var r = await rd.LoadAsync(bufferSize);
                 if (r <= 0) break;
                 var buf = new byte[r];
                 rd.ReadBytes(buf);
                 wr.WriteBytes(buf);
                 await wr.FlushAsync();
             } while (true);
         }
     }
 }
Exemple #29
0
 private async void Test_Click(object sender, RoutedEventArgs e) {
     try {
         StreamSocket socket = new StreamSocket();
         await socket.ConnectAsync(new HostName("192.168.0.2"), "86", SocketProtectionLevel.PlainSocket);
         var writer = new DataWriter(socket.OutputStream);
         uint i = writer.WriteString("test\r\n");
         try {
             await writer.StoreAsync();
             Debug.WriteLine("StoreAsync was called");
             Debug.WriteLine("MainPage Wrote {0} bytes", i);
             await writer.FlushAsync();
         } catch (Exception ex1) {
             Debug.WriteLine(ex1.ToString());
         }
     } catch (Exception ex) {
         Debug.WriteLine(ex.ToString());
     }
 }
        // http://www.chrispeerman.info/loading-images-from-byte-arrays-in-windows-8-store-apps-winrt/
        /// <summary>
        /// Creates new BitmapImage from specified byte array.
        /// </summary>
        public static async Task<BitmapImage> FromByteArrayAsync(byte[] data)
        {
            using (var stream = new InMemoryRandomAccessStream())
            {
                using (var writer = new DataWriter(stream))
                {
                    writer.WriteBytes(data);
                    await writer.StoreAsync();
                    await writer.FlushAsync();
                    writer.DetachStream();
                }

                stream.Seek(0);
                var bitmap = new BitmapImage();
                await bitmap.SetSourceAsync(stream);

                return bitmap;
            }
        }
        private async void TransferImage(StreamSocket socket)
        {
            var writer = new DataWriter(socket.OutputStream);

            UpdateStatus("Übertrage Bild...");

            // Anzahl der zu übertragenden Bytes übertragen
            writer.WriteInt32(App.ImageBytesToTransfer.Length);
            await writer.StoreAsync();

            // Image-Bytes übertragen
            writer.WriteBytes(App.ImageBytesToTransfer);
            await writer.StoreAsync();
            await writer.FlushAsync();

            // Ressourcen freigeben
            writer.Dispose();
            UpdateStatus("Übertragung abgeschlossen");
        }
        /// <summary>
        /// Serializes the data object and sends it to the connected RemoteSocket.
        /// For more information on making an object serializable, see DataContractJsonSerializer.
        /// </summary>
        public async Task SendRemoteMessageAsync(object data)
        {
            // Connect to the remote host to ensure that the connection exists.
            await ConnectToRemoteAsync();

            using (var writer = new DataWriter(_remoteSocket.OutputStream))
            {
                byte[] serializedData = SerializeData(data);
                byte[] serializedDataLength = BitConverter.GetBytes(serializedData.Length);

                writer.WriteBytes(serializedDataLength);
                writer.WriteBytes(serializedData);

                await writer.StoreAsync();
                await writer.FlushAsync();
            }

            // Disconnect from the remote host.
            DisconnectFromRemote();
        }
 public object Convert(object value, System.Type type, object parameter, string language)
 {
     ImageSource src = null;
     byte[] bytearr = value as byte[];
     if (bytearr != null)
     {
         BitmapImage image = new BitmapImage();
         using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
         {
             using (DataWriter dataWriter = new DataWriter(ms.GetOutputStreamAt(0)))
             {
                 dataWriter.WriteBytes(bytearr);
                 dataWriter.StoreAsync().AsTask().Wait();
                 dataWriter.FlushAsync().AsTask().Wait();
             }
             image.SetSource(ms);
         }
         src = image;
     }
     return src;
 }
        private async void TransferPicture(StreamSocket socket)
        {
            // DataWriter erzeugen, um Byte-Umwandlung erledigen zu lassen...
            var writer = new DataWriter(socket.OutputStream);

            // Anzahl der zu übertragenden Bytes übertragen
            writer.WriteInt32(App.PhotoBytesToShare.Length);
            await writer.StoreAsync();

            // Image-Bytes übertragen
            writer.WriteBytes(App.PhotoBytesToShare);
            await writer.StoreAsync();
            await writer.FlushAsync();
            UpdateStatus("Übertragung abgeschlossen.");

            // Ressourcen freigeben
            writer.Dispose();
            socket.Dispose();

            // Beenden der Annahme von Client-Verbindungen
            _listener.Dispose();
        }
Exemple #35
0
		public static async void SaveTo ( ObservableCollection<RecentData> datas )
		{
			StorageFile sf = await ApplicationData.Current.LocalFolder.CreateFileAsync ( "data.dat",
				Windows.Storage.CreationCollisionOption.ReplaceExisting );
			FileRandomAccessStream stream = await sf.OpenAsync ( FileAccessMode.ReadWrite ) as FileRandomAccessStream;
			DataWriter dw = new DataWriter ( stream );

			dw.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
			dw.ByteOrder = ByteOrder.LittleEndian;

			dw.WriteInt32 ( datas.Count );
			foreach ( RecentData data in datas )
			{
				dw.WriteUInt32 ( ( uint ) dw.MeasureString ( data.Source ) );
				dw.WriteString ( data.Source );
				dw.WriteInt32 ( data.SourceIndex );
				dw.WriteInt32 ( data.TargetIndex );
			}

			await dw.StoreAsync ();
			await dw.FlushAsync ();
			stream.Dispose ();
		}
Exemple #36
0
    private async Task <IRandomAccessStream> FixTextureContentType(IRandomAccessStream modelStream)
    {
        XDocument xmldoc = XDocument.Load(modelStream.AsStreamForRead());

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

        writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
        writer.ByteOrder       = Windows.Storage.Streams.ByteOrder.LittleEndian;

        var text = xmldoc.ToString();

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

        writer.WriteString(replacedText);

        await writer.StoreAsync();

        await writer.FlushAsync();

        writer.DetachStream();
        return(outputStream);
    }
Exemple #37
0
        public async static Task<BitmapImage> getFullImage(int pictureID)
        {
            var imageString = await SharedFunctions.RunHttpRequestWithStringReturn(new Uri("http://" + MainPage.mainPage.serverIP +
                "/server/requestHandler.php?operation=getImage&id=" + pictureID));
            using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
            {
                byte[] bytes = Convert.FromBase64String(imageString);
                using (DataWriter writer = new DataWriter(stream))
                {
                    writer.WriteBytes(bytes);

                    await writer.StoreAsync();

                    await writer.FlushAsync();

                    writer.DetachStream();
                }
                stream.Seek(0);
                var bitmapImage = new BitmapImage();
                bitmapImage.SetSource(stream);
                return bitmapImage;
            }
        }
        private async Task SendToServer(object arg = null, [CallerMemberName] string method = null)
        {
            var message = ClientChannelWriteHelper.FormatOutput(arg, method);

            using (var socketOperation = _signalingSocketService.SocketOperation)
            {
                var socket = socketOperation.Socket;
                if (socket != null)
                {
                    using (var writer = new DataWriter(socket.OutputStream))
                    {
                        writer.WriteString($"{message}{Environment.NewLine}");
                        await writer.StoreAsync();
                        await writer.FlushAsync();
                        writer.DetachStream();
                    }
                }
            }
        }
Exemple #39
0
 private async Task Save()
 {
     await _operationQueue.Queue((async () =>
     {
         string content = JsonConvert.SerializeObject(_playlist);
         using (var writer = await (await OpenFile()).OpenTransactedWriteAsync())
         {
             var stream = writer.Stream;
             stream.Size = 0;
             stream.Seek(0);
             var dw = new DataWriter(stream);
             dw.WriteString(content);
             await dw.StoreAsync();
             await dw.FlushAsync();
             dw.DetachStream();
             await writer.CommitAsync();
         }
     }));
 }
        private async Task Send(string stringToSend)
        {
            using (DataWriter chatWriter = new DataWriter(socket.OutputStream))
            {
               // string ToSend = "Send Photo";
                

                // chatWriter.WriteUInt32((uint)ToSend.Length);

                chatWriter.WriteString(stringToSend);

                try
                {
                    await chatWriter.StoreAsync();
                }

                catch (Exception ex)
                {
                    //   MainPage.Current.NotifyUser("Error: " + ex.HResult.ToString() + " - " + ex.Message,
                    //        NotifyType.StatusMessage);

                }
                await chatWriter.FlushAsync();
                chatWriter.DetachStream();

            }
            receivedMessage = null;
            await Task.Delay(2000);
            receivedMessage = await Receive();

            if (receivedMessage != null)
            {

                //   await  Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                //     async () => 
                //       {
                //RequestAggregateBatteryReport();
                MyImageSource = await ImgHelper.ReadImageFromPi(receivedMessage);
                RaisePropertyChanged("MyImageSource");
       //           });
                
               await CalculateShotPoint();
            }
        }
Exemple #41
0
 public async Task Send(string data)
 {
     byte[] dataBytes = Cryptography.TextManipulation.EncodeUTF(data);
     string dataLength = dataBytes.Length.ToString();
     DataWriter socketDataWriter=new DataWriter(internalSocket.OutputStream);
     byte[] dataToSend = Cryptography.TextManipulation.EncodeUTF(dataLength + "MLEN" + data);
     int dataSent = 0;
     while(dataSent<dataToSend.Length)
     {
         int currentChunkSize = CHUNK_SIZE;
         if (dataToSend.Length - dataSent < CHUNK_SIZE) currentChunkSize = dataToSend.Length - dataSent;
         byte[] chunk = new byte[currentChunkSize];
         Array.Copy(dataToSend, dataSent, chunk, 0, currentChunkSize);
         socketDataWriter.WriteBytes(chunk);
         await socketDataWriter.StoreAsync().AsTask(getTimeoutToken());
         await socketDataWriter.FlushAsync().AsTask(getTimeoutToken());
         dataSent += currentChunkSize;
         repportProgress(dataSent, dataToSend.Length);
     }
     await socketDataWriter.StoreAsync().AsTask(getTimeoutToken());
     await socketDataWriter.FlushAsync().AsTask(getTimeoutToken());
     socketDataWriter.DetachStream();
 }