Inheritance: IDataWriter, IClosable
Ejemplo n.º 1
0
		public WinRtTransferHandler(StreamSocket socket)
		{
			if (socket == null) throw new ArgumentNullException("socket");

			_reader = new DataReader(socket.InputStream);
			_writer = new DataWriter(socket.OutputStream);
		}
Ejemplo n.º 2
0
        private async void WriteFile(string s)
        {
            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile sampleFile =
                await storageFolder.GetFileAsync("dsp_data.txt");

            try
            {
                var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(stream.Size))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        dataWriter.WriteString(s);
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose();
            }
            catch (Exception E) { }
        }
Ejemplo n.º 3
0
        private async Task <WriteableBitmap> LoadWritableBitmap(string path)
        {
            var file = await StorageFile.GetFileFromPathAsync(path);

            var data = await FileIO.ReadBufferAsync(file);

            var ms = new InMemoryRandomAccessStream();
            var dw = new Windows.Storage.Streams.DataWriter(ms);

            dw.WriteBuffer(data);
            await dw.StoreAsync();

            ms.Seek(0);

            var bm = new BitmapImage();
            await bm.SetSourceAsync(ms);

            var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);

            ms.Seek(0);

            await wb.SetSourceAsync(ms);

            return(wb);
        }
Ejemplo n.º 4
0
        public override async void Start()
        {
            if (_Started)
                return;
            _SequenceNumber = 1;

            try
            {
                // Connect to the Drone
                udpClient = new DatagramSocket();
                await udpClient.BindServiceNameAsync(_ServiceName);
                await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName);
                udpWriter = new DataWriter(udpClient.OutputStream);

                udpWriter.WriteByte(1);
                await udpWriter.StoreAsync();

                _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25));
                _Started = true;
            }
            catch (Exception)
            {
                Stop();
            }
        }
Ejemplo n.º 5
0
 public async void WriteToSerialPort(string message)
 {
     var writer = new DataWriter(_realDevice.OutputStream);
     writer.WriteString(AddNewLine(message));
     await writer.StoreAsync().AsTask();
     writer.DetachStream();
 }
Ejemplo n.º 6
0
        IBuffer getBuffer(short i)
        {
            var writer = new Windows.Storage.Streams.DataWriter();

            writer.WriteInt16(i);
            return(writer.DetachBuffer());
        }
Ejemplo n.º 7
0
            public static async void SetSensorPeriod(SensorChars sensorCharacteristics, int period)
            {
                SensorServicesCls.SensorIndexes SensorIndex = sensorCharacteristics.Sensor_Index;
                Debug.WriteLine("Begin SetSensorPeriod(): " + SensorIndex.ToString());


                try
                {
                    if (sensorCharacteristics.Charcteristics.Keys.Contains(SensorServicesCls.CharacteristicTypes.Period))
                    {
                        GattCharacteristic characteristic = sensorCharacteristics.Charcteristics[SensorServicesCls.CharacteristicTypes.Period];
                        {
                            if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                            {
                                var writer = new Windows.Storage.Streams.DataWriter();
                                // Accelerometer period = [Input * 10]ms
                                writer.WriteByte((Byte)(period / 10));
                                await characteristic.WriteValueAsync(writer.DetachBuffer());
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error: SetSensorPeriod(): " + SensorIndex.ToString() + " " + ex.Message);
                }
                Debug.WriteLine("End SetSensorPeriod(): " + SensorIndex.ToString());
            }
Ejemplo n.º 8
0
        // ---------------------------------------------------
        //     Hardware Configuration Helper Functions
        // ---------------------------------------------------

        // Retrieve Barometer Calibration data
        private async void calibrateBarometer()
        {
            GattDeviceService service;

            if (_serviceList.TryGetValue(BAROMETRIC_PRESSURE, out service))
            {
                // Set Barometer configuration to 2, so that calibration data is saved
                var characteristicList = service.GetCharacteristics(BAROMETER_CONFIGURATION_GUID);
                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        writer.WriteByte((Byte)0x02);
                        await characteristic.WriteValueAsync(writer.DetachBuffer());
                    }
                }

                // Save Barometer calibration data
                characteristicList = service.GetCharacteristics(BAROMETER_CALIBRATION_GUID);
                if (characteristicList != null)
                {
                    GattReadResult result = await characteristicList[0].ReadValueAsync(BluetoothCacheMode.Uncached);
                    baroCalibrationData = new byte[result.Value.Length];
                    DataReader.FromBuffer(result.Value).ReadBytes(baroCalibrationData);
                }
            }
        }
Ejemplo n.º 9
0
        public override async void receive_file(String devicename, String add, int not)
        {
            try
            {
                _httpurl = new Uri(add);
                _httpprogress = new Progress<HttpProgress>(ProgressHandler);

                HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), _httpurl);
                                
                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
                filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;

                _httpclient = new HttpClient(filter);

                _cancel_token_source = new CancellationTokenSource();
                _cancel_token = _cancel_token_source.Token;

                scan_network_speed();
                _stopwatch.Start();

                _httpresponse = await _httpclient.SendRequestAsync(request).AsTask(_cancel_token, _httpprogress);

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting);
                IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite);
                IOutputStream filewriter = filestream.GetOutputStreamAt(0);
                _datawriter = new DataWriter(filewriter);

                _timer.Cancel();

                _transferspeed /= 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _stopwatch.Stop();

                _buffer = await _httpresponse.Content.ReadAsBufferAsync();

                _datawriter.WriteBuffer(_buffer);
                await _datawriter.StoreAsync();

                _datawriter.Dispose();
                filewriter.Dispose();
                filestream.Dispose();

                _httpresponse.Content.Dispose();
                _httpresponse.Dispose();
                _httpclient.Dispose();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, "");
            }            
        }
Ejemplo n.º 10
0
		public async Task Connect()
		{
			if (!_isLoggedIn)
				throw new DiscordException(ExceptionList.NotLoggedIn);

			_socket = new MessageWebSocket();
			_writer = new DataWriter(_socket.OutputStream) { UnicodeEncoding = UnicodeEncoding.Utf8 };

			_socket.Control.MessageType = SocketMessageType.Utf8;
			_socket.MessageReceived += socket_MessageReceived;

			string gatewayUrl = await GetGateway();

			await _socket.ConnectAsync(new Uri(gatewayUrl));

			JsonObject request = new JsonObject
			{
				{ "op", JsonValue.CreateNumberValue(2) },
				{ "d", new JsonObject
					{
						{ "token", JsonValue.CreateStringValue(_token) },
						{ "v", JsonValue.CreateNumberValue(3) },
						{ "properties", new JsonObject
						{
							{ "$os", JsonValue.CreateStringValue("Windows") }
						}},
						{ "large_threshold", JsonValue.CreateNumberValue(0) }
					}
				}
			};

			await WriteToSocket(request.Stringify());
		}
Ejemplo n.º 11
0
 public async void SendMessage(string msg)
 {
     HostName hostName;
     try
     {
         hostName = new HostName("localhost");
     }
     catch (ArgumentException)
     {
         return;
     }
     StreamSocket socket;
     try
     {
         using (socket = new StreamSocket())
         {
             await socket.ConnectAsync(hostName, port2);
             //CoreApplication.Properties.Add("connected", null);
             DataWriter dw = new DataWriter(socket.OutputStream);
             dw.WriteString(msg);
             await dw.StoreAsync();
         }
     }
     catch
     {
         //break;
     }
 }
        //</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);
        }
Ejemplo n.º 13
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();
            }
        }
Ejemplo n.º 14
0
        // ---------------------------------------------------
        //     Hardware Configuration Helper Functions
        // ---------------------------------------------------

        // Retrieve Barometer Calibration data
        private async void calibrateBarometer()
        {
            GattDeviceService gattService = serviceList[BAROMETRIC_PRESSURE];

            if (gattService != null)
            {
                // Set Barometer configuration to 2, so that calibration data is saved
                var characteristicList = gattService.GetCharacteristics(new Guid("F000AA42-0451-4000-B000-000000000000"));
                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        writer.WriteByte((Byte)0x02);
                        await characteristic.WriteValueAsync(writer.DetachBuffer());
                    }
                }

                // Save Barometer calibration data
                characteristicList = gattService.GetCharacteristics(new Guid("F000AA43-0451-4000-B000-000000000000"));
                if (characteristicList != null)
                {
                    GattReadResult result = await characteristicList[0].ReadValueAsync(BluetoothCacheMode.Uncached);
                    baroCalibrationData = new byte[result.Value.Length];
                    DataReader.FromBuffer(result.Value).ReadBytes(baroCalibrationData);
                }
            }
        }
Ejemplo n.º 15
0
        //req:
        //  path file exist
        //  m_words has words
        private async void saveData(StorageFile file)
        {
            //Debug.Assert(path != null);
            //Debug.Assert(System.IO.File.Exists(path));
            Debug.Assert(m_words != null);

            //StorageFile file = await StorageFile.GetFileFromPathAsync(path);

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

            var outputStream = stream.GetOutputStreamAt(0);
            var dataWriter   = new Windows.Storage.Streams.DataWriter(outputStream);

            foreach (var w in m_words)
            {
                dataWriter.WriteString(w.ToString() + "\r\n");
            }
            await dataWriter.StoreAsync();

            await outputStream.FlushAsync();

            dataWriter.Dispose();
            outputStream.Dispose();
            stream.Dispose();
        }
Ejemplo n.º 16
0
        private void PublishLaunchApp()
        {
            proximityDevice = Windows.Networking.Proximity.ProximityDevice.GetDefault();

            if (proximityDevice != null)
            {
                // The format of the app launch string is: "<args>\tWindows\t<AppName>".
                // The string is tab or null delimited.

                // The <args> string must have at least one character.
                string launchArgs = "user=default";

                // The format of the AppName is: PackageFamilyName!PRAID.
                string praid = "MyAppId"; // The Application Id value from your package.appxmanifest.

                string appName = Windows.ApplicationModel.Package.Current.Id.FamilyName + "!" + praid;

                string launchAppMessage = launchArgs + "\tWindows\t" + appName;

                var dataWriter = new Windows.Storage.Streams.DataWriter();
                dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
                dataWriter.WriteString(launchAppMessage);
                publishedUriId =
                    proximityDevice.PublishBinaryMessage(
                        "NDEF:WriteTag", dataWriter.DetachBuffer(), proximityWriteTagLaunchAppMessageTransmitCallback);
            }
        }
Ejemplo n.º 17
0
        public async void ProccesImage(StorageFile imageFile)
        {
            var data = await FileIO.ReadBufferAsync(imageFile);

            // create a stream from the file
            var ms = new InMemoryRandomAccessStream();
            var dw = new DataWriter(ms);
            dw.WriteBuffer(data);
            await dw.StoreAsync();
            ms.Seek(0);

            // find out how big the image is, don't need this if you already know
            var bm = new BitmapImage();
            await bm.SetSourceAsync(ms);

            // create a writable bitmap of the right size
            var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
            ms.Seek(0);

            // load the writable bitpamp from the stream
            await wb.SetSourceAsync(ms);

            Bitmap bmp = (Bitmap)wb;

            //var filter1 = Grayscale.CommonAlgorithms.BT709;

            //bmp = filter1.Apply(bmp);

            wb = (WriteableBitmap)bmp;

            var file = await this.WriteableBitmapToStorageFile(wb, FileFormat.Jpeg);
        }
Ejemplo n.º 18
0
 public async Task<bool> Init()
 {
     var res = true;
     ClearExceptions();
     for (int i = 0; i < 20; i++)
     {
         try
         {
             var value = new byte[3];
             value[0] = 0x1;
             value[1] = (byte)(i + 1);
             value[2] = (byte)(i + 1);
             var buffer = new DataWriter();
             buffer.WriteBytes(value);
             await _initCount1To20Char.WriteValueAsync(buffer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);
             await Sleep(50);
         }
         catch (Exception exception)
         {
             res = false;
             AddException(exception);
         }
     }
     return res;
 }
 //Connects to server
 public async Task connect(string address, int port)
 {
     if (!this.connected)
     {
         try
         {
             this.socket = new StreamSocket();
             this.hostname = new HostName(address);
             this.port = port;
             await this.socket.ConnectAsync(this.hostname, port.ToString());
             this.writer = new DataWriter(this.socket.OutputStream);
             this.reader = new DataReader(this.socket.InputStream);
             this.reader.InputStreamOptions = InputStreamOptions.Partial;
             connected = true;
         }
         catch (Exception e)
         {
             connected = false;
             Debug.WriteLine(e.Message);
         }
     }
     else
     {
         await new MessageDialog("Already connected", "Information").ShowAsync();
         connected = true;
         
     }
 }
Ejemplo n.º 20
0
 protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
 {
     if (args.ShareOperation.Data.Contains(StandardDataFormats.WebLink))
     {
         Uri uri = await args.ShareOperation.Data.GetWebLinkAsync();
         if (null != uri)
         try
         {
             using (var socket = new MessageWebSocket())
             {
                 socket.Control.MessageType = SocketMessageType.Utf8;
                 await socket.ConnectAsync(new Uri("ws://" + settings["Host"].ToString() + ":" + settings["Port"].ToString()));
                 using (var writer = new DataWriter(socket.OutputStream))
                 {
                     writer.WriteString(uri.AbsoluteUri);
                     await writer.StoreAsync();
                     args.ShareOperation.ReportCompleted();
                 }
             }
         }
         catch
         {
             show();
         }
     }
 }
Ejemplo n.º 21
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;
            }
        }
Ejemplo n.º 22
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();
 }
Ejemplo n.º 23
0
 private async void WriteToStreamButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         rootPage.ResetScenarioOutput(OutputTextBlock);
         StorageFile file = rootPage.sampleFile;
         if (file != null)
         {
             string userContent = InputTextBox.Text;
             if (!String.IsNullOrEmpty(userContent))
             {
                 using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync())
                 {
                     using (DataWriter dataWriter = new DataWriter(transaction.Stream))
                     {
                         dataWriter.WriteString(userContent);
                         transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file
                         await transaction.CommitAsync();
                         OutputTextBlock.Text = "The following text was written to '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + userContent;
                     }
                 }
             }
             else
             {
                 OutputTextBlock.Text = "The text box is empty, please write something and then click 'Write' again.";
             }
         }
     }
     catch (FileNotFoundException)
     {
         rootPage.NotifyUserFileNotExist();
     }
 }
Ejemplo n.º 24
0
 public async Task ConnectToDevice(DeviceInformation device)
 {
     this.State = ConnectionState.Connecting;
     try
     {
         serialConnection = await SerialDevice.FromIdAsync(device.Id);
         if (serialConnection != null)
         {
             serialConnection.BaudRate = 115200;
             serialConnection.DataBits = 8;
             serialConnection.Parity = SerialParity.None;
             writer = new DataWriter(serialConnection.OutputStream);
             reader = new DataReader(serialConnection.InputStream);
             Task listen = ListenForMessagesAsync();
             this.State = ConnectionState.Connected;
         }
         else {
             Debugger.ReportToDebugger(this, "Unable to create service.\nMake sure that the 'serialcommunication' capability is declared with a function of type 'name:serialPort' in Package.appxmanifest.", Debugger.Device.Pc);
             this.State = ConnectionState.Failure;
         }
     }
     catch (TaskCanceledException ex)
     {
         this.State = ConnectionState.Failure;
         Debugger.ReportToDebugger(this, ex.Message, Debugger.Device.Pc);
     }
     catch (Exception ex)
     {
         this.State = ConnectionState.Failure;
         Debugger.ReportToDebugger(this, ex.Message, Debugger.Device.Pc);
     }
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Extension method to SmartCardConnection class to perform a transparent exchange to the ICC
        /// </summary>
        /// <param name="connection">
        /// SmartCardConnection object
        /// </param>
        /// <param name="commandData">
        /// Command object to send to the ICC
        /// </param>
        /// <returns>Response received from the ICC</returns>
        public static async Task<byte[]> TransparentExchangeAsync(this SmartCardConnection connection, byte[] commandData)
        {
            byte[] responseData = null;
            ManageSessionResponse apduRes = await TransceiveAsync(connection, new ManageSession(new byte[2] { (byte)ManageSession.DataObjectType.StartTransparentSession, 0x00 })) as ManageSessionResponse;

            if (!apduRes.Succeeded)
            {
                throw new Exception("Failure to start transparent session, " + apduRes.ToString());
            }

            using (DataWriter dataWriter = new DataWriter())
            {
                dataWriter.WriteByte((byte)TransparentExchange.DataObjectType.Transceive);
                dataWriter.WriteByte((byte)commandData.Length);
                dataWriter.WriteBytes(commandData);

                TransparentExchangeResponse apduRes1 = await TransceiveAsync(connection, new TransparentExchange(dataWriter.DetachBuffer().ToArray())) as TransparentExchangeResponse;

                if (!apduRes1.Succeeded)
                {
                    throw new Exception("Failure transceive with card, " + apduRes1.ToString());
                }

                responseData = apduRes1.IccResponse;
            }

            ManageSessionResponse apduRes2 = await TransceiveAsync(connection, new ManageSession(new byte[2] { (byte)ManageSession.DataObjectType.EndTransparentSession, 0x00 })) as ManageSessionResponse;

            if (!apduRes2.Succeeded)
            {
                throw new Exception("Failure to end transparent session, " + apduRes2.ToString());
            }

            return responseData;
        }
Ejemplo n.º 26
0
        private async void SendData(GattCharacteristic characteristic, string str)
        {
            var dataWriter = new Windows.Storage.Streams.DataWriter();

            dataWriter.WriteString(str);
            await characteristic.WriteValueAsync(dataWriter.DetachBuffer());
        }
Ejemplo n.º 27
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();
                }
            }
        }
Ejemplo n.º 28
0
        private async void ButtonAction2_Click(object sender, RoutedEventArgs e)
        {
            DevicesInformation = string.Empty;
            foreach (var rsCharacteristic in _dicCharacteristics)
            {
                DevicesInformation += $"  Try to write to {rsCharacteristic.Value.CharName}{Environment.NewLine}";
                bool writeOk = true;
                try
                {
                    var charToTest = rsCharacteristic.Value.Characteristic;
                    byte[] arr = { 4, 1, 2, 0, 1, 0 };
                    var writer = new DataWriter();
                    writer.WriteBytes(arr);
                    await charToTest.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Indicate);
                    await charToTest.WriteValueAsync(writer.DetachBuffer());
                    DevicesInformation += $"  - OK{Environment.NewLine}";
                }
                catch
                {
                    DevicesInformation += $"  - ERROR{Environment.NewLine}";
                    writeOk = false;
                }

                var msg = $"{rsCharacteristic.Value.CharName}, {writeOk}, {rsCharacteristic.Value.Characteristic.CharacteristicProperties}, {rsCharacteristic.Value.Characteristic.Uuid}";
                Debug.WriteLine(msg);

                await Task.Delay(TimeSpan.FromMilliseconds(100));
            }
        }
 public void Open()
 {
   OpenConnection();
   dataReader = new DataReader(streamSocket.InputStream);
   dataWriter = new DataWriter(streamSocket.OutputStream);
   readable = writeable = true;
 }
Ejemplo n.º 30
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value != null && value is byte[])
            {

                //WriteableBitmap bitmap = new WriteableBitmap(100, 100);

                //System.IO.Stream bitmapStream = null;
                //bitmapStream = bitmap.PixelBuffer.AsStream();
                //bitmapStream.Position = 0;
                //bitmapStream.Write(value as byte[], 0, (value as byte[]).Length);

                //bitmapStream.Flush();

                InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
                writer.WriteBytes(value as byte[]);
                var x = writer.StoreAsync().AsTask().Result;
                BitmapImage image = new BitmapImage();
                image.SetSource(randomAccessStream);

                return image;
            }

            return null;
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value != null)
            {

                byte[] bytes = (byte[])value;
                BitmapImage myBitmapImage = new BitmapImage();
                if (bytes.Count() > 0)
                {


                    InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
                    DataWriter writer = new DataWriter(stream.GetOutputStreamAt(0));

                    writer.WriteBytes(bytes);
                    writer.StoreAsync().GetResults();
                    myBitmapImage.SetSource(stream);
                }
                else
                {
                    myBitmapImage.UriSource = new Uri("ms-appx:///Assets/firstBackgroundImage.jpg");
                }

                return myBitmapImage;
            }
            else
            {
                return new BitmapImage();
            }
        }
Ejemplo n.º 32
0
        private async void OnLoadingFile(object sender, GestureEventArgs e)
        {
            var city = new City
            {
                Name = "Leipzig",
                State = "Saxony",
                Country = "Germany",
                Population = 550000
            };

            string json = JsonConvert.SerializeObject(city);

            var cityFile = 
              await ApplicationData.Current
                                   .LocalFolder.CreateFileAsync(
                                     "leipzig.city",
                                     CreationCollisionOption.ReplaceExisting);

            using (var stream = await cityFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var writer = new DataWriter(stream))
                {
                    writer.WriteString(json);
                    await writer.StoreAsync();
                }
            }

            Launcher.LaunchFileAsync(cityFile);
        }
Ejemplo n.º 33
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());
			}
		}
Ejemplo n.º 34
0
        // WebSockets Button
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //creates a new MessageWebSocket and connects to WebSocket server and sends data to server
                
                //Make a local copy
                MessageWebSocket webSocket = messageWebSocket;

                //Have we connected yet?
                if (webSocket == null)
                {

                    Uri server = new Uri(ServerAddressField.Text.Trim());
                    webSocket = new MessageWebSocket();
                    webSocket.Control.MessageType = SocketMessageType.Utf8;
                    webSocket.MessageReceived += MessageReceived;
                    webSocket.Closed += Closed;
                    await webSocket.ConnectAsync(server);
                    messageWebSocket = webSocket;
                    messageWriter = new DataWriter(webSocket.OutputStream);
                }

                //InputField is a textbox in the xaml
                string message = InputField.Text;
                messageWriter.WriteString(message);
                await messageWriter.StoreAsync();
            }
            catch (Exception ex)
            {
                String.Format("There is an error in connection"); 
            }
        }
Ejemplo n.º 35
0
        async void datagramSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            i++;
            DataReader dataReader = args.GetDataReader();
            uint length = dataReader.UnconsumedBufferLength;
            string content = dataReader.ReadString(length);
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            msgList.Children.Add(new TextBlock { Text = "服务器收到的消息:" + content }));

            //HostName hostName = new HostName("localhost");
            //DatagramSocket datagramSocket = new DatagramSocket();
            //IOutputStream outputStream = await datagramSocket.GetOutputStreamAsync(hostName, "22112");
            DataWriter writer = new DataWriter(sender.OutputStream);
            writer.WriteString(content + "|" + i);
            try
            {
                await writer.StoreAsync();
                msgList.Children.Add(new TextBlock { Text = "服务器发送的消息:" + content + "|" + i });
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {

                }
            }
        }
Ejemplo n.º 36
0
        public async void Send(string data)
        {
            UInt32 bytesWritten = 0;
            try
            {
                if (_serialPort != null)
                {
                    // Create the DataWriter object and attach to OutputStream
                    _dataWriteObject = new DataWriter(_serialPort.OutputStream);

                    //Launch the WriteAsync task to perform the write
                    byte[] bytes = Encoding.ASCII.GetBytes(data);
                    bytesWritten = await WriteAsync(bytes);
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                // Cleanup once complete
                if (_dataWriteObject != null)
                {
                    _dataWriteObject.DetachStream();
                    _dataWriteObject = null;
                }
            }
        }
Ejemplo n.º 37
0
        public async Task<BitmapImage> Base64ToBitmapImage(string base64String)
        {

            BitmapImage img = new BitmapImage();
            if (string.IsNullOrEmpty(base64String))
                return img;

            using (var ims = new InMemoryRandomAccessStream())
            {
                byte[] bytes = Convert.FromBase64String(base64String);
                base64String = "";

                using (DataWriter dataWriter = new DataWriter(ims))
                {
                    dataWriter.WriteBytes(bytes);
                    bytes = null;
                    await dataWriter.StoreAsync();
                                 

                ims.Seek(0);

              
               await img.SetSourceAsync(ims); //not in RC
               
               
                return img;
                }
            }

        }
Ejemplo n.º 38
0
        private async void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            if (saveLogin)
            {
                configSF = await storageFolder.CreateFileAsync("config.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                var stream = await configSF.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                using (var outputStream = stream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        string  combo  = Username.Text + " " + Password.Password;
                        IBuffer comboB = await SampleDataProtectionStream(strDescriptor, combo, encoding);

                        dataWriter.WriteBuffer(comboB);
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose();
            }
            else
            {
                configSF = await storageFolder.CreateFileAsync("config.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
            }
        }
Ejemplo n.º 39
0
        private async void WriteCharacteristicValue_Click(object sender, RoutedEventArgs args)
        {
            WriteCharacteristicValueButton.IsEnabled = false;
            try
            {
                var heartRateControlPointCharacteristic = HeartRateService.Instance.Service.GetCharacteristics(
                    GattCharacteristicUuids.HeartRateControlPoint)[0];
                 
                DataWriter writer = new DataWriter();
                writer.WriteByte(1);

                GattCommunicationStatus status = await heartRateControlPointCharacteristic.WriteValueAsync(
                    writer.DetachBuffer());

                if (status == GattCommunicationStatus.Success)
                {
                    rootPage.NotifyUser("Expended Energy successfully reset.", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("Your device is unreachable, most likely the device is out of range, " +
                        "or is running low on battery, please make sure your device is working and try again.",
                        NotifyType.StatusMessage);
                }
            }
            catch (Exception e)
            {
                rootPage.NotifyUser("Error: " + e.Message, NotifyType.ErrorMessage);
            }
            WriteCharacteristicValueButton.IsEnabled = true;
        }
Ejemplo n.º 40
0
        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[]>();
        }
        public SocketHandler(StreamSocket socket)
        {
            this.socket = socket;

            this.reader = new DataReader(this.socket.InputStream);
            this.writer = new DataWriter(this.socket.OutputStream);
        }
Ejemplo n.º 42
0
        //public static async Task<bool> FileExist()
        //{
        //    try
        //    {
        //        var folders = ApplicationData.Current.LocalFolder;
        //        var file = await folders.GetFileAsync(PersonalDataFileName);
        //        var buildingFile = await folders.GetFileAsync(BuildingDataFileName);
        //        if (file.Path != null)
        //            return false;
        //        else
        //            return true;
        //    }
        //    catch
        //    {
        //        return true;
        //    }
        //}

        //public static void SavePersonalDataToJson(AccountInfo accountInfo)
        //{
        //    string jsonContents = JsonConvert.SerializeObject(accountInfo);
        //    JObject o = (JObject)JToken.FromObject(accountInfo);


        //}
        //public static async void SavePersonalDataToJson(AccountInfo account)
        //{
        //    // Serialize our Product class into a string
        //    // Changed to serialze the List

        //    // Get the app data folder and create or replace the file we are storing the JSON in.
        //    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
        //    StorageFile textFile = await localFolder.CreateFileAsync(PersonalDataFileName, CreationCollisionOption.ReplaceExisting);

        //    // Open the file...

        //    string jsonContents = JsonConvert.SerializeObject(account);
        //    using (IRandomAccessStream mysteream = await textFile.OpenAsync(FileAccessMode.ReadWrite))
        //    {
        //        using (DataWriter textWriter = new DataWriter(mysteream))
        //        {
        //            textWriter.WriteString(jsonContents);
        //            await textWriter.StoreAsync();
        //        }

        //    }
        //}

        public static async Task <bool> SavePersonalDataToJson(List <AccountInfo> list)
        {
            // Serialize our Product class into a string
            // Changed to serialze the List

            // Get the app data folder and create or replace the file we are storing the JSON in.
            if (personalTextFile == null)
            {
                personalTextFile = await StorageFolder.CreateFileAsync(PersonalDataFileName, CreationCollisionOption.ReplaceExisting);
            }

            // Open the file...
            string jsonContents = JsonConvert.SerializeObject(UserToUserData(list));
            var    stream       = await personalTextFile.OpenAsync(FileAccessMode.ReadWrite);

            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString(jsonContents);
                    await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }
            stream.Dispose();
            return(true);
        }
Ejemplo n.º 43
0
        public static void Connect(string address, string port)
        {
            if (!connected)
            {
                clientSocket = new StreamSocket();

                try
                {
                    serverHost = new HostName(address);
                    serverPort = port;
                    serverHostnameString = address;
                    writer = new DataWriter(clientSocket.OutputStream);

                    clientSocket.ConnectAsync(serverHost, serverPort);
                    connected = true;
                }
                catch (Exception)
                {
                    clientSocket.Dispose();
                    clientSocket = null;

                    throw new ConnectionErrorException();
                }
            }
            else
            {
                clientSocket.Dispose();
                clientSocket = null;
                connected = false;

                GamepadClient.Connect(address, port);
            }
        }
        // Write function for adding control points to a server
        private async Task HandleSensorControlPoint(string data)
        {
            if (!string.IsNullOrEmpty(data))
            {
                // Get current service from base class.
                var service = await GetService();
                // Get current characteristic from current service using the selected values from the base class.
                var characteristic = service.GetCharacteristics(this.SelectedService.Guid)[this.SelectedIndex];

                //Create an instance of a data writer which will write to the relevent buffer.
                DataWriter writer = new DataWriter();
                byte[] toWrite = System.Text.Encoding.UTF8.GetBytes(data);
                writer.WriteBytes(toWrite);

                // Attempt to write the data to the device, and whist doing so get the status.
                GattCommunicationStatus status = await characteristic.WriteValueAsync(writer.DetachBuffer());

                // Displays a message box to tell user if the write operation was successful or not.
                if (status == GattCommunicationStatus.Success)
                {
                    MessageHelper.DisplayBasicMessage("Sensor control point has been written.");
                }
                else
                {
                    MessageHelper.DisplayBasicMessage("There was a problem writing the sensor control value, Please try again later.");
                }
            }
        }
Ejemplo n.º 45
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);
        }
Ejemplo n.º 46
0
        private async Task <bool> SendPowerOffCommand()
        {
            var   writer = new Windows.Storage.Streams.DataWriter();
            short val    = CMD_OFF;

            writer.WriteInt16(val);
            GattCommunicationStatus writeResult = await _writeCharacteristic.WriteValueAsync(writer.DetachBuffer());

            bool success = writeResult == GattCommunicationStatus.Success;

            return(success);
        }
Ejemplo n.º 47
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();
            }
        }
Ejemplo n.º 48
0
        private async Task <Windows.Storage.Streams.IRandomAccessStream> toStream(Windows.Storage.Streams.IBuffer ibuffer)
        {
            var stream       = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var outputStream = stream.GetOutputStreamAt(0);
            var datawriter   = new Windows.Storage.Streams.DataWriter(outputStream);

            datawriter.WriteBuffer(ibuffer);
            await datawriter.StoreAsync();

            await outputStream.FlushAsync();

            return(stream);
        }
        void InitializeServiceSdpAttributes(RfcommServiceProvider provider)
        {
            Windows.Storage.Streams.DataWriter writer = new Windows.Storage.Streams.DataWriter();

            // First write the attribute type
            writer.WriteByte(SERVICE_VERSION_ATTRIBUTE_TYPE);
            // Then write the data
            writer.WriteUInt32(MINIMUM_SERVICE_VERSION);

            IBuffer data = writer.DetachBuffer();

            provider.SdpRawAttributes.Add(SERVICE_VERSION_ATTRIBUTE_ID, data);
        }
Ejemplo n.º 50
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;
            }
        }
Ejemplo n.º 51
0
        /// <summary>
        /// Restores the applications data using a backup from the current user's OneDrive.
        /// <para>Note: Application requires restart after restoring data</para>
        /// </summary>
        /// <param name="itemId">Unique item identifier within a DriveItem (i.e., a folder/file facet).</param>
        /// <param name="filename">Name of the datafile.</param>
        /// <returns></returns>
        public static async Task RestoreFileFromOneDriveAsync(string itemId, string dataFilename)
        {
            try
            {
                // Local storage folder
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;

                // Our local ktdatabase.db file
                Windows.Storage.StorageFile originalDataFile =
                    await storageFolder.GetFileAsync(dataFilename);

                // Stream for the backed up data file
                var backedUpFileStream = await GraphClient.Me.Drive.Items[itemId].ItemWithPath(dataFilename).Content
                                         .Request()
                                         .GetAsync();

                // Backed up file
                var backedUpFile = await storageFolder.CreateFileAsync("temp", CreationCollisionOption.ReplaceExisting);

                var newStream = await backedUpFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

                // Write data to new file
                using (var outputStream = newStream.GetOutputStreamAt(0))
                {
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        var buffer = backedUpFileStream.ToByteArray();
                        dataWriter.WriteBytes(buffer);

                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }

                // Copy and replace local file
                await backedUpFile.CopyAsync(storageFolder, dataFilename, NameCollisionOption.ReplaceExisting);
            }

            catch (ServiceException ex)
            {
                if (ex.StatusCode == HttpStatusCode.Forbidden)
                {
                    Console.WriteLine($"Access Denied: {ex.Message}");
                }

                Console.WriteLine($"Service Exception, Error uploading file to signed-in users one drive: {ex.Message}");
                // return null;
            }
        }
Ejemplo n.º 52
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();
            }
        }
Ejemplo n.º 53
0
        private async void btnColor_Click(object sender, RoutedEventArgs e)
        {
            //Change the color of the NeoPixel by writing the hex color bytes to the Write characteristic
            //that is currently being monitored by our Flora sketch
            Button btnColor = (Button)sender;
            var    color    = ((SolidColorBrush)btnColor.Background).Color;

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

            writer.WriteBytes(new byte[] { color.R, color.G, color.B });

            txtProgress.Text = "Writing color to Writable GATT characteristic ...";
            await _writeCharacteristic.WriteValueAsync(writer.DetachBuffer());

            txtProgress.Text = "Writable GATT characteristic written";
        }
Ejemplo n.º 54
0
            public static async Task TurnOnSensor(SensorChars sensorCharacteristics)
            {
                SensorServicesCls.SensorIndexes sensor = sensorCharacteristics.Sensor_Index;
                Debug.WriteLine("Begin turn on sensor: " + sensor.ToString());
                // Turn on sensor
                try
                {
                    if (sensor >= 0 && sensor != SensorServicesCls.SensorIndexes.KEYS && sensor != SensorServicesCls.SensorIndexes.IO_SENSOR && sensor != SensorServicesCls.SensorIndexes.REGISTERS)
                    {
                        if (sensorCharacteristics.Charcteristics.Keys.Contains(SensorServicesCls.CharacteristicTypes.Enable))
                        {
                            GattCharacteristic characteristic = sensorCharacteristics.Charcteristics[SensorServicesCls.CharacteristicTypes.Enable];
                            if (characteristic != null)
                            {
                                if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                                {
                                    var writer = new Windows.Storage.Streams.DataWriter();
                                    if (sensor == SensorServicesCls.SensorIndexes.MOVEMENT)
                                    {
                                        byte[] bytes = new byte[] { 0x7f, 0x00 };
                                        writer.WriteBytes(bytes);
                                    }
                                    else
                                    {
                                        writer.WriteByte((Byte)0x01);
                                    }

                                    var status = await characteristic.WriteValueAsync(writer.DetachBuffer());
                                }
                            }
                        }
                        else
                        {
                        }
                    }
                    //IncProgressCounter();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error: TurnOnSensor() : " + sensor.ToString() + " " + ex.Message);
                }

                Debug.WriteLine("End turn on sensor: " + sensor.ToString());
            }
Ejemplo n.º 55
0
        private async Task PlaceIconAsync(string tag, double probability, Rect boundingBox)
        {
            if (probability < 0.4)
            {
                foreach (var stroke in _sessionStrokes)
                {
                    _allStrokes.Add(stroke);
                }
            }
            else
            {
                var icon = await GetIconFileAsync(tag);

                if (icon == null)
                {
                    return;
                }

                var bytes = await FileIO.ReadBufferAsync(icon);

                var ms = new InMemoryRandomAccessStream();
                var dw = new Windows.Storage.Streams.DataWriter(ms);
                dw.WriteBuffer(bytes);
                await dw.StoreAsync();

                ms.Seek(0);

                var bm = new BitmapImage();
                await bm.SetSourceAsync(ms);

                var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
                ms.Seek(0);

                await wb.SetSourceAsync(ms);

                var newBitmap = wb.Resize((int)boundingBox.Width, (int)boundingBox.Height, WriteableBitmapExtensions.Interpolation.Bilinear);
                var image     = new Image();
                image.Source = newBitmap;
                Canvas.SetTop(image, boundingBox.Top);
                Canvas.SetLeft(image, boundingBox.Left);
                iconCanvas.Children.Add(image);
            }
        }
Ejemplo n.º 56
0
        //
        public async static void WriteTextFileAsync(string filename, string content)
        {
            var storageFolder = ApplicationData.Current.LocalFolder;
            var textFile      = await storageFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);

            var textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite);

            using (var outputStream = textStream.GetOutputStreamAt(textStream.Size))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString("\n" + content);
                    await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }
            textStream.Dispose();
        }
Ejemplo n.º 57
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();
        }
Ejemplo n.º 58
0
        private async Task updateImage(Image cameraImage, string url)
        {
            // Download the image into memory as a stream
            System.Net.Http.HttpClient          client        = new System.Net.Http.HttpClient();
            System.Net.Http.HttpResponseMessage imageResponse = await client.GetAsync(url);

            InMemoryRandomAccessStream randomAccess =
                new Windows.Storage.Streams.InMemoryRandomAccessStream();

            DataWriter writer =
                new Windows.Storage.Streams.DataWriter(randomAccess.GetOutputStreamAt(0));

            writer.WriteBytes(await imageResponse.Content.ReadAsByteArrayAsync());
            await writer.StoreAsync();

            BitmapImage bit = new BitmapImage();
            await bit.SetSourceAsync(randomAccess);

            cameraImage.Source = bit;
        }
Ejemplo n.º 59
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;
            }
        }
Ejemplo n.º 60
0
        public async void setSensorPeriod(int period)
        {
            GattDeviceService gattService = GattService;

            if (SensorIndex != SensorIndexes.KEYS && SensorIndex != SensorIndexes.IO_SENSOR && gattService != null)
            {
                var characteristicList = gattService.GetCharacteristics(new Guid(UUIDBase[(int)SensorIndex] + SENSOR_PERIOD_GUID_SUFFFIX));
                if (characteristicList != null)
                {
                    GattCharacteristic characteristic = characteristicList[0];

                    if (characteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Write))
                    {
                        var writer = new Windows.Storage.Streams.DataWriter();
                        // Accelerometer period = [Input * 10]ms
                        writer.WriteByte((Byte)(period / 10));
                        await characteristic.WriteValueAsync(writer.DetachBuffer());
                    }
                }
            }
        }