Пример #1
0
        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;
            }
        }
Пример #2
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);
    }
Пример #3
0
		private async Task WriteToOutputStreamAsync(byte[] bytes)
		{

			if (_socket == null) return;
			_writer = new DataWriter(_socket.OutputStream);
			_writer.WriteBytes(bytes);

			var debugString = UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length);

			try
			{
				await _writer.StoreAsync();
				await _socket.OutputStream.FlushAsync();

				_writer.DetachStream();
				_writer.Dispose();
			}
			catch (Exception exception)
			{
				// If this is an unknown status it means that the error if fatal and retry will likely fail.
				if (global::Windows.Networking.Sockets.SocketError.GetStatus(exception.HResult) == global::Windows.Networking.Sockets.SocketErrorStatus.Unknown)
				{
					// TODO abort any retry attempts on Unity side
					throw;
				}
			}
		}
Пример #4
0
 public async void WriteToSerialPort(string message)
 {
     var writer = new DataWriter(_realDevice.OutputStream);
     writer.WriteString(AddNewLine(message));
     await writer.StoreAsync().AsTask();
     writer.DetachStream();
 }
Пример #5
0
		public static async void init(TiSettings settings) {
			if (!settings.ContainsKey("logToken") || settings["logToken"].Length == 0) {
				return;
			}

			logToken = settings["logToken"];

			multicastSocket = new DatagramSocket();
			multicastSocket.MessageReceived += multicastSocket_MessageReceived;

			HostName hostname = new HostName("239.6.6.6");

			try {
				await multicastSocket.BindServiceNameAsync("8666");
				multicastSocket.JoinMulticastGroup(hostname);

				IOutputStream stream = await multicastSocket.GetOutputStreamAsync(hostname, "8666");
				DataWriter writer = new DataWriter(stream);
				writer.WriteString("TI_WP8_LOGGER");
				await writer.StoreAsync();
				writer.DetachStream();
				stream.Dispose();
			} catch (Exception ex) {
				if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) {
					throw;
				}
				Debug.WriteLine(ex.ToString());
			}
		}
Пример #6
0
 private async Task<string> DoCommand(string command)
 {
     StringBuilder strBuilder = new StringBuilder();
     using (StreamSocket clientSocket = new StreamSocket())
     {
         await clientSocket.ConnectAsync(new HostName("192.168.9.108"),  "9001");
         using (DataWriter writer = new DataWriter(clientSocket.OutputStream))
         {
             writer.WriteString(command);
             await writer.StoreAsync();
             writer.DetachStream();
         }
         using (DataReader reader = new DataReader(clientSocket.InputStream))
         {
             reader.InputStreamOptions = InputStreamOptions.Partial;
             await reader.LoadAsync(8192);
             while (reader.UnconsumedBufferLength > 0)
             {
                 strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
                 await reader.LoadAsync(8192);
             }
             reader.DetachStream();
         }
     }
     return (strBuilder.ToString());
 }
        //</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);
        }
Пример #8
0
		public static async Task WriteFileAsync(string fileName, byte[] content)
		{
			try
			{
				var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

				using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
				{
					using (var outputStream = fileStream.GetOutputStreamAt(0))
					{
						using (var dataWriter = new DataWriter(outputStream))
						{
							dataWriter.WriteBytes(content);
							await dataWriter.StoreAsync();
							dataWriter.DetachStream();
						}
						await outputStream.FlushAsync();
					}
				}
			}
			catch (Exception exception)
			{
				SnazzyDebug.WriteLine(exception);
			}
		}
Пример #9
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();
            }
        }
Пример #10
0
        /// <summary>
        /// Writes a string to a text file.
        /// </summary>
        /// <param name="text">The text to write.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="folder">The folder.</param>
        /// <param name="options">
        /// The enum value that determines how responds if the fileName is the same
        /// as the name of an existing file in the current folder. Defaults to ReplaceExisting.
        /// </param>
        /// <returns></returns>
        public static async Task SaveAsync(
            this string text,
            string fileName,
            StorageFolder folder = null,
            CreationCollisionOption options = CreationCollisionOption.ReplaceExisting)
        {
            folder = folder ?? ApplicationData.Current.LocalFolder;
            var file = await folder.CreateFileAsync(
                fileName,
                options);
            using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var outStream = fs.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outStream))
                    {
                        if (text != null)
                            dataWriter.WriteString(text);

                        await dataWriter.StoreAsync();
                        dataWriter.DetachStream();
                    }

                    await outStream.FlushAsync();
                }
            }
        }
Пример #11
0
 private async void OnWrite(Object sender, RoutedEventArgs e)
 {
     // 获取本地目录的引用
     StorageFolder local = ApplicationData.Current.LocalFolder;
     // 创建新文件
     StorageFile newFIle = await local.CreateFileAsync("demo.dat", CreationCollisionOption.ReplaceExisting);
     // 打开文件流
     using(IRandomAccessStream stream = await newFIle.OpenAsync(FileAccessMode.ReadWrite))
     {
         // 实例化 DataWriter
         DataWriter dw = new DataWriter(stream);
         // 设置默认编码格式
         dw.UnicodeEncoding = UnicodeEncoding.Utf8;
         // 写入 bool 值
         dw.WriteBoolean(true);
         // 写入日期值
         DateTime dt = new DateTime(2010, 8, 21);
         dw.WriteDateTime(dt);
         // 写入字符串
         string str = "测试文本";
         // 计算字符串长度
         uint len = dw.MeasureString(str);
         // 先写入字符串的长的
         dw.WriteUInt32(len);
         // 再写入字符串
         dw.WriteString(str);
         // 以下方法必须调用
         await dw.StoreAsync();
         // 解除 DataWriter 与流的关联
         dw.DetachStream();
         dw.Dispose();
     }
     MessageDialog msgDlg = new MessageDialog("保存成功。");
     await msgDlg.ShowAsync();
 }
 public async Task SendAsync(string text)
 {
     var dataWriteObject = new DataWriter(_serialPort.OutputStream);
     dataWriteObject.WriteString(text);
     var task = dataWriteObject.StoreAsync().AsTask(_cancellation.Token);
     await task;
     dataWriteObject.DetachStream();
 }
Пример #13
0
		public static async Task WriteLine(this IOutputStream outputStream, string line)
		{
			using (var dataWriter = new DataWriter(outputStream))
			{
				dataWriter.WriteString(line);
				await dataWriter.StoreAsync();
				dataWriter.DetachStream();
			}
		}
Пример #14
0
        async void InitStreamInfo()
        {
            _stream = new InMemoryRandomAccessStream();

            DataWriter writer = new DataWriter(_stream);
            writer.WriteString(_jsonValue);

            var data = await writer.StoreAsync();
            writer.DetachStream();
        }
Пример #15
0
 private async Task SendMessageUsingMessageWebSocketAsync(string message)
 {
     using (var dataWriter = new Windows.Storage.Streams.DataWriter(m_Socket.OutputStream))
     {
         dataWriter.WriteString(message);
         await dataWriter.StoreAsync();
         dataWriter.DetachStream();
     }
     FlowNetworkManager.log("Sending message using MessageWebSocket: " + message);
 }
Пример #16
0
        private async Task <int> SendAsync(byte[] inbuffer)
        {
            using (var writer = new Windows.Storage.Streams.DataWriter(socket.OutputStream))
            {
                writer.WriteBytes(inbuffer);
                await writer.StoreAsync();

                writer.DetachStream();
            }
            // hopefully true...
            return(inbuffer.Length);
        }
Пример #17
0
 private async Task<bool> SendAsync(string data, string ok = "", string err = "")
 {
     if (serialPort == null)
     {
         if (!await Open())
             return false;
     }
     try
     {
         using (var writer = new DataWriter(serialPort.OutputStream))
         {
             writer.WriteString(data);
             await writer.StoreAsync();
             writer.DetachStream();
         }
     }
     catch (OperationCanceledException ex)
     {
         return false;
     }
     catch (Exception ex)
     {
         return false;
     }
     try
     {
         var buffer = string.Empty;
         using (var reader = new DataReader(serialPort.InputStream))
         {
             reader.InputStreamOptions = InputStreamOptions.ReadAhead;
             if (await reader.LoadAsync(1024) > 0)
                 buffer = reader.ReadString(reader.UnconsumedBufferLength);
             reader.DetachStream();
         }
         if (!string.IsNullOrEmpty(ok) && buffer.Contains(ok))
         {
             return true;
         }
         else if (!string.IsNullOrEmpty(err) && buffer.Contains(err))
         {
             return false;
         }
     }
     catch (OperationCanceledException ex)
     {
         return false;
     }
     catch (Exception ex)
     {
         return false;
     }
     return false;
 }
 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();
     }
 }
Пример #19
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();
            }
        }
Пример #20
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;
            }
        }
Пример #21
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 void Run(IBackgroundTaskInstance taskInstance)
 {
     var deferral = taskInstance.GetDeferral();
     try
     {
         var details = taskInstance.TriggerDetails as SocketActivityTriggerDetails;
         var socketInformation = details.SocketInformation;
         switch (details.Reason)
         {
             case SocketActivityTriggerReason.SocketActivity:
                 var socket = socketInformation.StreamSocket;
                 DataReader reader = new DataReader(socket.InputStream);
                 reader.InputStreamOptions = InputStreamOptions.Partial;
                 await reader.LoadAsync(250);
                 var dataString = reader.ReadString(reader.UnconsumedBufferLength);
                 ShowToast(dataString);
                 socket.TransferOwnership(socketInformation.Id);
                 break;
             case SocketActivityTriggerReason.KeepAliveTimerExpired:
                 socket = socketInformation.StreamSocket;
                 DataWriter writer = new DataWriter(socket.OutputStream);
                 writer.WriteBytes(Encoding.UTF8.GetBytes("Keep alive"));
                 await writer.StoreAsync();
                 writer.DetachStream();
                 writer.Dispose();
                 socket.TransferOwnership(socketInformation.Id);
                 break;
             case SocketActivityTriggerReason.SocketClosed:
                 socket = new StreamSocket();
                 socket.EnableTransferOwnership(taskInstance.Task.TaskId, SocketActivityConnectedStandbyAction.Wake);
                 if (ApplicationData.Current.LocalSettings.Values["hostname"] == null)
                 {
                     break;
                 }
                 var hostname = (String)ApplicationData.Current.LocalSettings.Values["hostname"];
                 var port = (String)ApplicationData.Current.LocalSettings.Values["port"];
                 await socket.ConnectAsync(new HostName(hostname), port);
                 socket.TransferOwnership(socketId);
                 break;
             default:
                 break;
         }
         deferral.Complete();
     }
     catch (Exception exception)
     {
         ShowToast(exception.Message);
         deferral.Complete();
     }
 }
Пример #23
0
        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;
        }
		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 void SendButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         DataWriter writer = new DataWriter(connectedSocket.OutputStream);
         writer.WriteBytes(Encoding.UTF8.GetBytes(SendMessageTextBox.Text));
         await writer.StoreAsync();
         writer.DetachStream();
         writer.Dispose();
     }
     catch(Exception exception)
     {
         rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);
     }
 }
Пример #26
0
 public async Task Send(byte[] command)
 {
     using (var socket = new DatagramSocket())
     {
         using (var stream = await socket.GetOutputStreamAsync(this.hostName, this.port))
         {
             using (var dataWriter = new DataWriter(stream))
             {
                 dataWriter.WriteBytes(command);
                 await dataWriter.StoreAsync();
                 dataWriter.DetachStream();
             }
         }
     }
 }
Пример #27
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");
    }
Пример #28
0
        /// <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);
            }
        }
        public static async Task Write(this IStorageFile file, byte[] content)
        {
            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var outputStream = fileStream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outputStream))
                    {
                        dataWriter.WriteBytes(content);
                        await dataWriter.StoreAsync();
                        dataWriter.DetachStream();
                    }

                    await outputStream.FlushAsync();
                }
            }
        }
Пример #30
0
        public static async Task SaveToFileAsync(this byte[] byteArray, StorageFile file)
        {
            ThrowIf.Null(byteArray, "byteArray");
            ThrowIf.Null(file, "file");

            using (var filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var writer = new DataWriter(filestream.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(byteArray);
                    await writer.StoreAsync();
                    writer.DetachStream();
                }

                await filestream.FlushAsync();
            }
        }
Пример #31
0
 public static async void SaveToStorage()
 {
     StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder;
     StorageFile roamingFile = await roamingFolder.CreateFileAsync("apis.json", CreationCollisionOption.ReplaceExisting);
     using (IRandomAccessStream textStream = await roamingFile.OpenAsync(FileAccessMode.ReadWrite))
     {
         using (DataWriter textWriter = new DataWriter(textStream))
         {
             foreach (ApiEntry api in APIs)
             {
                 textWriter.WriteString(api.ToJSON().ToString());
                 textWriter.WriteString("\n");
                 await textWriter.StoreAsync();
             }
             textWriter.DetachStream();
         }
     }
 }
Пример #32
0
        // 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;
            }
        }
Пример #33
0
        public static async Task WriteFile(string filename, string contents)
        {
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var folder      = await localFolder.CreateFolderAsync("DataCache", Windows.Storage.CreationCollisionOption.OpenIfExists);

            var file = await folder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);

            var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            fs.Seek(fs.Size);
            var outStream  = fs.GetOutputStreamAt(0);
            var dataWriter = new Windows.Storage.Streams.DataWriter(outStream);

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

            dataWriter.DetachStream();
            await outStream.FlushAsync();
        }
Пример #34
0
        public async void SaveASync(T Obj, string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                if (Obj != null)
                {
                    StorageFile   file   = null;
                    StorageFolder folder = GetFolder(storageType);
                    file = await folder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);

                    DataContractJsonSerializer ser = new DataContractJsonSerializer(Obj.GetType());
                    MemoryStream ms = new MemoryStream();
                    ser.WriteObject(ms, Obj);
                    var bytes    = ms.ToArray();
                    var contents = UTF8Encoding.UTF8.GetString(bytes, 0, bytes.Length);

                    using (var writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        //Stream outStream = Task.Run(() => writeStream.AsStreamForWrite()).Result;
                        //serializer.Serialize(outStream, Obj);

                        using (var outStream = writeStream.GetOutputStreamAt(0))
                        {
                            using (var dataWriter = new Windows.Storage.Streams.DataWriter(outStream))
                            {
                                dataWriter.WriteString(contents);
                                await dataWriter.StoreAsync();

                                dataWriter.DetachStream();
                                await outStream.FlushAsync();
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #35
0
        public static async Task<BitmapImage> ConvertToBitmapImageAsync(this byte[] byteArray)
        {
            ThrowIf.Null(byteArray, "byteArray");

            using (var stream = new InMemoryRandomAccessStream())
            {
                using (var writer = new DataWriter(stream.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes(byteArray);
                    await writer.StoreAsync();
                    writer.DetachStream();
                }

                BitmapImage image = null;
                // NOTE: ~HUGE HACK~  BitmapImage can only be created/manipulated on UI thread :(
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    () =>
                        {
                            image = new BitmapImage();
                            image.SetSource(stream);
                        });

                return image;

                /*Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (s, a) => {
    if (_image == null)
        {
            IRandomAccessStream imageStream = await _imageFile.OpenAsync(FileAccessMode.Read);
            _image = new BitmapImage();
            _image.DecodePixelHeight = _decodeHeight;
            _image.SetSource(imageStream);
        }
}, null, null);

return _image;*/
                /* var image = new BitmapImage();
                await image.SetSourceAsync(stream);
                return image;*/
            }
        }
Пример #36
0
        /// <summary>
        /// Writes text to the specified file.
        /// </summary>
        /// <param name="file">The file that the text is written to.</param>
        /// <param name="contents">The text to write.</param>
        public static async Task WriteTextAsync(IStorageFile file, string contents)
        {
            using (var fs = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var outStream = fs.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outStream))
                    {
                        if (contents != null)
                        {
                            dataWriter.WriteString(contents);
                        }

                        await dataWriter.StoreAsync();
                        dataWriter.DetachStream();
                    }

                    await outStream.FlushAsync();
                }
            }
        }
Пример #37
0
        public async void WriteString(string HostName, string Message)
        {
            HostName remoteHostName = new HostName(HostName);

            using (StreamSocket socket = new StreamSocket())
            {
                socket.Control.KeepAlive = false;
                await socket.ConnectAsync(remoteHostName, "6");

                using (DataWriter writer = new DataWriter(socket.OutputStream))
                {
                    // set payload length
                    writer.ByteOrder = ByteOrder.LittleEndian;
                    writer.WriteUInt32(writer.MeasureString(Message));
                    // set payload type
                    writer.WriteByte((byte)PayloadType.String);
                    // set payload
                    writer.WriteString(Message);
                    // transmit
                    await writer.StoreAsync();
                    writer.DetachStream();
                }

                using (DataReader reader = new DataReader(socket.InputStream))
                {
                    int length;
                    string response;
                    // receive payload length
                    reader.ByteOrder = ByteOrder.LittleEndian;
                    await reader.LoadAsync(4);
                    length = reader.ReadInt32();
                    // receive payload
                    await reader.LoadAsync((uint)length);
                    response = reader.ReadString((uint)length);

                    Debug.WriteLine(string.Format("response: {0}", response));
                    reader.DetachStream();
                }
            }
        }
        public async Task SaveFlickrPhotoToPictureLibraryAsync(FlickrPhoto photo)
        {
            using (var client = new HttpClient())
            {
                var image = await client.GetByteArrayAsync(photo.LargeImageUrl);
                var localFile = await KnownFolders.PicturesLibrary.CreateFileAsync(GetFilenameFromUrl(photo.LargeImageUrl), CreationCollisionOption.GenerateUniqueName);

                using (var fileStream = await localFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (var writeStream = fileStream.GetOutputStreamAt(0))
                    {
                        using (var writer = new DataWriter(writeStream))
                        {
                            writer.WriteBytes(image);
                            await writer.StoreAsync();
                            writer.DetachStream();
                        }
                        await writeStream.FlushAsync();
                    }
                }
            }
        }
Пример #39
0
 public async void sendMail(string strSendTo,string strContent , Boolean hasPicture)
 {
     HostName hostName = new HostName(hostIP);
     StreamSocket socket = new StreamSocket();
     List<string[]> storeList = new List<string[]>();
     try
     {
         await socket.ConnectAsync(hostName, port);
     }
     catch (Exception exception)
     {
         if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
         {
             throw;
         }
     }
     StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Temp");
     StorageFile pic = await folder.GetFileAsync("MyPainter.png");
     IBuffer buffer = await FileIO.ReadBufferAsync(pic);
     DataWriter writer = new DataWriter(socket.OutputStream);
     writer.WriteUInt32(writer.MeasureString(strSendTo));
     writer.WriteString(strSendTo);
     writer.WriteUInt32(writer.MeasureString(strContent));
     writer.WriteString(strContent);
     if (hasPicture)
     {
         writer.WriteUInt32((uint)buffer.Length);
         writer.WriteBuffer(buffer);
     }
     else
     {
         writer.WriteUInt32(0);
         writer.WriteString("");
     }
     await writer.StoreAsync();
     writer.DetachStream();
     writer.Dispose();
     socket.Dispose();
 }
Пример #40
0
        public async Task SendAsync(string msg)
        {
            if (IsConnected && !string.IsNullOrEmpty(msg))
            {
                try
                {
                    using (DataWriter writer = new DataWriter(socket.OutputStream))
                    {
                        writer.WriteString(msg);
                        await writer.StoreAsync();
                        writer.DetachStream();
                    }
                }
                catch (Exception ex)
                {
                    //if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
                    //    throw;

                    Disconnect();
                }
            }
        }
Пример #41
0
        public async Task Write(string key, Stream value)
        {
            var cacheFolder = await GetWorkingFolder();
            var file = await cacheFolder.CreateFileAsync(key, CreationCollisionOption.ReplaceExisting);
            using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var outputStream = fileStream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new DataWriter(outputStream))
                    {
                        var bytes = new byte[value.Length];
                        await value.ReadAsync(bytes, 0, (int)value.Length);

                        dataWriter.WriteBytes(bytes);
                        await dataWriter.StoreAsync();
                        dataWriter.DetachStream();
                    }

                    await outputStream.FlushAsync();
                }
            }
        }
Пример #42
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);
    }