WriteString() публичный Метод

public WriteString ( string value ) : void
value string
Результат void
       private void OnWriteableTagArrived(ProximityDevice sender, ProximityMessage message)
       {
    
           var dataWriter = new DataWriter();
           dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf16LE;
           string appLauncher = string.Format(@"mywaiter:MainPage?source=3");
 
           dataWriter.WriteString(appLauncher);
           pubId = sender.PublishBinaryMessage("WindowsUri:WriteTag", dataWriter.DetachBuffer());
   
       }
Пример #2
0
        /// <summary>
        /// Send the message to the server
        /// </summary>
        /// <param name="type">KB or M</param>
        /// <param name="message">Single character or x,y</param>
        /// <param name="hold">0=default, 1=press, 2=release</param>
        public void send(string type, string message, int hold = 0)
        {
            try
            {
                //NetworkStream clientStream = client.GetStream();
                DataWriter writer = new DataWriter(client.OutputStream);

                
                //ASCIIEncoding encoder = new ASCIIEncoding();

                string buffer = type + ';' + message + ';' + hold + "\n";
                writer.WriteUInt32(writer.MeasureString(buffer));
                writer.WriteString(buffer);
                /*
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
                 * */
                writer.WriteString(buffer);
            }
            catch
            {
                //Console.WriteLine("Connection Lost");
                startClient();
            }
        }
        //</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);
        }
Пример #4
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);
        }
Пример #5
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[]>();
        }
Пример #6
0
        private async void SendData(GattCharacteristic characteristic, string str)
        {
            var dataWriter = new Windows.Storage.Streams.DataWriter();

            dataWriter.WriteString(str);
            await characteristic.WriteValueAsync(dataWriter.DetachBuffer());
        }
        public async void PerformPeerDiscovery()
        {
            timer.Interval = new TimeSpan(0, 0, 5);
            timer.Start();

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

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

            using (var outputStream = await socket.GetOutputStreamAsync(new HostName("230.0.0.1"), "22003"))
            {
                using (DataWriter wr = new DataWriter(outputStream))
                {
                    wr.WriteString("**BECHARMING DISCOVERY**");
                    await wr.FlushAsync();
                    await wr.StoreAsync();
                }
            }
        }
        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);
            }
        }
Пример #9
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();
        }
Пример #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
        public async Task Send(WemosMessage msg)
        {
            if (msg != null)
            {
                var str = msg.ToDto();
                if (!string.IsNullOrEmpty(str))
                {
                    try
                    {
                        // GetOutputStreamAsync can be called multiple times on a single DatagramSocket instance to obtain
                        // IOutputStreams pointing to various different remote endpoints. The remote hostname given to
                        // GetOutputStreamAsync can be a unicast, multicast or broadcast address.
                        IOutputStream outputStream = await listenerSocket.GetOutputStreamAsync(new HostName(remoteMulticastAddress), remoteService);

                        DataWriter writer = new DataWriter(outputStream);
                        writer.WriteString(str);
                        await writer.StoreAsync();
                    }
                    catch (Exception exception)
                    {
                        // If this is an unknown status it means that the error is fatal and retry will likely fail.
                        if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                            throw;

                        //rootPage.NotifyUser("Send failed with error: " + exception.Message, NotifyType.ErrorMessage);
                    }
                }
            }
        }
Пример #12
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());
			}
		}
Пример #13
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();
         }
     }
 }
Пример #14
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) { }
        }
Пример #15
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);
        }
Пример #16
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();
 }
Пример #17
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;
     }
 }
Пример #18
0
        private async void doShipping(Order order)
        {
            try
            {
                StorageFile file = await KnownFolders.DocumentsLibrary.CreateFileAsync("dispatch-" + order.OrderID.ToString() + ".txt");
                if (file != null)
                {
                    string dispatchNote = "Order Summary: " + 
                                          "\r\nOrder ID: " + order.OrderID +
                                          "\r\nOrder Total: " + String.Format("{0:C}", order.TotalValue);

                    var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
                    var writeStream = stream.GetOutputStreamAt(0);
                    DataWriter writer = new DataWriter(writeStream);
                    writer.WriteString(dispatchNote);
                    await writer.StoreAsync();
                    await writeStream.FlushAsync();
                    writeStream.Dispose();
                }
                else
                {
                    MessageDialog dlg = new MessageDialog(String.Format("Unable to save to file: {0}", file.DisplayName), "Not saved");
                    dlg.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                MessageDialog dlg = new MessageDialog(ex.Message, "Exception");
                dlg.ShowAsync();
            }
        }
 public void WriteAllText(string filename, string text, Action completed)
 {
     StorageFolder localFolder = 
                     ApplicationData.Current.LocalFolder;
     IAsyncOperation<StorageFile> createOp = 
                     localFolder.CreateFileAsync(filename,
                         CreationCollisionOption.ReplaceExisting);
     createOp.Completed = (asyncInfo1, asyncStatus1) =>
     {
         IStorageFile storageFile = asyncInfo1.GetResults();
         IAsyncOperation<IRandomAccessStream> openOp = 
                 storageFile.OpenAsync(FileAccessMode.ReadWrite);
         openOp.Completed = (asyncInfo2, asyncStatus2) =>
         {
             IRandomAccessStream stream = asyncInfo2.GetResults();
             DataWriter dataWriter = new DataWriter(stream);
             dataWriter.WriteString(text);
             DataWriterStoreOperation storeOp = 
                     dataWriter.StoreAsync();
             storeOp.Completed = (asyncInfo3, asyncStatus3) =>
             {
                 dataWriter.Dispose();
                 completed();
             };
         };
     };
 }
Пример #20
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();
     }
 }
Пример #21
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)
                {

                }
            }
        }
Пример #22
0
 public async void WriteToSerialPort(string message)
 {
     var writer = new DataWriter(_realDevice.OutputStream);
     writer.WriteString(AddNewLine(message));
     await writer.StoreAsync().AsTask();
     writer.DetachStream();
 }
Пример #23
0
        private async Task WriteBlecOmmand(string command)
        {
            try
            {
                _commandExecuting = true;

                BluetoothLEDevice oygenBluetoothLeDevice = null;
                GattCharacteristic writeCharacteristics = null;

                oygenBluetoothLeDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(0x000780067cf1);


                var srv =
                    oygenBluetoothLeDevice.GattServices.FirstOrDefault(
                        gs => gs.Uuid.ToString().Equals("2ac94b65-c8f4-48a4-804a-c03bc6960b80"));

                Debug.WriteLine(oygenBluetoothLeDevice.Name);

                writeCharacteristics =
                    srv
                        .GetAllCharacteristics()
                        .FirstOrDefault(ch => ch.Uuid.ToString().Equals("50e03f22-b496-4a73-9e85-335482ed4b12"));

                var writer = new DataWriter();

                writer.WriteString(command + "\n");

                await writeCharacteristics.WriteValueAsync(writer.DetachBuffer());
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Bluetooth Problem.");
                Debug.WriteLine(ex.Message);
            }
        }
Пример #24
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());
 }
Пример #25
0
        private void OnSocketConnected(object sender, EventArgs eventArgs)
        {
            try
            {


                _writer = new DataWriter(_clientSocket.OutputStream);

                var connectionstring = GetConnectionstring();

                var handshake = new Rfc6455Handshake(connectionstring, this.Client.Origin, this.Client);

                _writer.WriteString(handshake.ToString());
                _writer.StoreAsync();

                //read handshake
                _reader = new DataReader(_clientSocket.InputStream);
                _reader.InputStreamOptions = InputStreamOptions.Partial;

                var data = _reader.LoadAsync(1024);

                data.Completed = (info, status) =>
                {
                    switch (status)
                    {
                        case AsyncStatus.Completed:
                            //read complete message
                            uint byteCount = _reader.UnconsumedBufferLength;

                            byte[] bytes = new byte[byteCount];
                            _reader.ReadBytes(bytes);

                            var r = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                            //Debug.WriteLine(r);

                            Connected = true;
                            //Start receive thread
                            FrameHandler = CreateFrameHandler();
                            Task.Factory.StartNew(Read);

                            if (this.OnConnected != null)
                                this.OnConnected.Invoke(this, null);

                            return;

                        case AsyncStatus.Error:
                            if (this.OnError != null) this.OnError.Invoke(this, new Exception("Error when doing handshake"));
                            this.Disconnect();
                            break;
                        case AsyncStatus.Canceled:
                            this.Disconnect();
                            break;
                    }
                };
            }
            catch
            {
            }
        }
 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();
 }
		private async Task ExecuteDiscoveryTask()
		{
			int repeatTime = EndpointController.REPEAT_DISCOVERY_TASK / 2;

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

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

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

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

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

					socketSent = null;
					socketReplay = null;
				}

				if (running)
				{
					Debug.WriteLine(">> [DiscoveryCloudletMulticast]: Retry Discovery Cloudlet, in " + repeatTime + " ms");
					await Task.Delay(repeatTime);
				}
				else
				{
					Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Finished Discovery Cloudlet");
				}
			}
		}
 async public static Task WriteAllTextAsync(this StorageFile storageFile, string content)
 {
     var inputStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite);
     var writeStream = inputStream.GetOutputStreamAt(0);
     var writer = new DataWriter(writeStream);
     writer.WriteString(content);
     await writer.StoreAsync();
     await writeStream.FlushAsync();
 }
Пример #29
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();
			}
		}
Пример #30
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();
         }
     }
 }
Пример #31
0
 private static async Task<IInputStream> GetStreamForByteArray(string content2)
 {
     var ras = new InMemoryRandomAccessStream();
     var datawriter = new DataWriter(ras);
     datawriter.WriteString(content2);
     //datawriter.WriteBytes(content2);
     await datawriter.StoreAsync();
     await datawriter.FlushAsync();
     return ras.GetInputStreamAt(0);
 }
Пример #32
0
        async void InitStreamInfo()
        {
            _stream = new InMemoryRandomAccessStream();

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

            var data = await writer.StoreAsync();
            writer.DetachStream();
        }
Пример #33
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);
 }
Пример #34
0
 /// <summary>
 /// 连接并发送信息给对方
 /// </summary>
 /// <param name="peerInformation"></param>
 private async void ConnectToPeer(PeerInformation peer)
 {
     dataReader = new DataReader(socket.InputStream);
     dataWriter = new DataWriter(socket.OutputStream);
     string message = "测试消息";
     uint strLength = dataWriter.MeasureString(message);
     dataWriter.WriteUInt32(strLength);
     dataWriter.WriteString(message);
     uint numBytesWritten = await dataWriter.StoreAsync();
 }
Пример #35
0
    /// <summary>
    /// Returns list of bridge IPs
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<string>> LocateBridgesAsync(TimeSpan timeout)
    {
      if (timeout <= TimeSpan.Zero)
        throw new ArgumentException("Timeout value must be greater than zero.", "timeout");

      var discoveredDevices = new List<string>();
      var multicastIP = new HostName("239.255.255.250");
      
      using (var socket = new DatagramSocket())
      {

        //Handle MessageReceived
        socket.MessageReceived += (sender, e) =>
        {
          var reader = e.GetDataReader();
          var bytesRemaining = reader.UnconsumedBufferLength;
          var receivedString = reader.ReadString(bytesRemaining);

          var location = receivedString.Substring(receivedString.ToLower().IndexOf("location:", System.StringComparison.Ordinal) + 9);
          receivedString = location.Substring(0, location.IndexOf("\r", System.StringComparison.Ordinal)).Trim();

          discoveredDevices.Add(receivedString);
        };

        await socket.BindEndpointAsync(null, string.Empty);
        socket.JoinMulticastGroup(multicastIP);

        var start = DateTime.Now;

        do
        {
          using (var stream = await socket.GetOutputStreamAsync(multicastIP, "1900"))
          using (var writer = new DataWriter(stream))
          {
            string request = "M-SEARCH * HTTP/1.1\r\n" +
                         "HOST:239.255.255.250:1900\r\n" +
                         //"ST:urn:schemas-upnp-org:device:Basic:1\r\n" + //Alternative
                         // "ST:upnp:rootdevice\r\n" +                    //Alternative
                         "ST:SsdpSearch:all\r\n" +
                         "MAN:\"ssdp:discover\"\r\n" +
                         "MX:3\r\n\r\n\r\n";

            writer.WriteString(request.ToString());
            await writer.StoreAsync();

          }

        }
        while (DateTime.Now.Subtract(start) < timeout); // try for thee seconds
      }

      return await FilterBridges(discoveredDevices);

    }
Пример #36
0
 private IBuffer GetBufferFromString(String str)
 {
     using (InMemoryRandomAccessStream memoryStream = new InMemoryRandomAccessStream())
     {
         using (DataWriter dataWriter = new DataWriter(memoryStream))
         {
             dataWriter.WriteString(str);
             return dataWriter.DetachBuffer();
         }
     }
 }
Пример #37
0
        private async void InitializeConnection()
        {
            await _socket.ConnectAsync(new HostName("127.0.0.1"), "41337");
            var dataWriter = new DataWriter(_socket.OutputStream);
            var dataReader = new DataReader(_socket.InputStream);

            var message = CreateHandshakeMessage();

            dataWriter.WriteString(message);
            var response = dataReader.ReadString(100);
        }
Пример #38
0
        public async Task SaveAsync(string fileName, string content)
        {
            var folder = ApplicationData.Current.LocalFolder;
            var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

            using (var stream = await file.OpenReadAsync())
            using (var writer = new DataWriter(stream))
            {
                writer.WriteString(content);
                await writer.StoreAsync();
            }
        }
Пример #39
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;
            }
        }
Пример #40
0
    /// <summary>
    /// Send the given data to the server using the established connection
    public async void SendString(string message)
    {
        DatagramSocket socket = new DatagramSocket();
        await socket.ConnectAsync(new HostName(ServerIP), ConnectionPort.ToString());

        using (var writer = new Windows.Storage.Streams.DataWriter(socket.OutputStream))
        {
            var data = Encoding.UTF8.GetBytes(message);

            //writer.WriteBytes(data);
            writer.WriteString(message);
            await writer.StoreAsync();

            //Debug.Log("Sent: " + message);
        }
    }
Пример #41
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");
    }
Пример #42
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();
        }
Пример #43
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();
        }
Пример #44
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;
            }
        }
Пример #45
0
        internal async Task <bool> SendBLEData(StringBuilder sbCmd)
        {
            try
            {
                if (currentCharacteristic != null)
                {
                    using (var writer = new Windows.Storage.Streams.DataWriter())
                    {
                        writer.WriteString(sbCmd.ToString());
                        GattCommunicationStatus status = await currentCharacteristic.WriteValueAsync(writer.DetachBuffer(), GattWriteOption.WriteWithoutResponse);

                        return(status == GattCommunicationStatus.Success);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

            return(false);
        }
Пример #46
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);
    }
        async private Task <int> SaveXMLDoc(XmlDocument xdoc, StorageFile file)
        {
            using (var stream = await file.OpenStreamForWriteAsync())
            {
                stream.SetLength(0);
            }

            IRandomAccessStream existingFileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            using (IOutputStream outputStream = existingFileStream.GetOutputStreamAt(0))
            {
                using (DataWriter dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    dataWriter.WriteString(CreateXMLStringWithNewlines(ref xdoc));


                    await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }
            existingFileStream.Dispose();
            return(0);
        }
Пример #48
0
        public async Task <int> saveWords(StorageFile file, List <word> words)
        {
            var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

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

            uint len = 0;

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

            await outputStream.FlushAsync();

            dataWriter.Dispose();
            outputStream.Dispose();
            stream.Size = len;
            stream.Dispose();

            return(0);
        }
Пример #49
0
            public void StartAdvertisement(
                string serviceName,
                bool autoAccept,
                bool preferGO,
                string pin,
                IList <WiFiDirectServiceConfigurationMethod> configMethods,
                WiFiDirectServiceStatus status,
                uint customStatus,
                string serviceInfo,
                string deferredServiceInfo,
                IList <String> prefixList
                )
            {
                ThrowIfDisposed();

                // Create Advertiser object for the service
                // NOTE: service name is internally limited to up to 255 bytes in UTF-8 encoding
                // Valid characters include alpha-numeric, '.', '-', and any multi-byte character
                // characters a-z, A-Z are case-insensitive when discovering services
                WiFiDirectServiceAdvertiser advertiser = new WiFiDirectServiceAdvertiser(serviceName);

                // Auto-accept services will connect without interaction from advertiser
                // NOTE: if the config method used for a connection requires a PIN, then the advertiser will have to accept the connection
                advertiser.AutoAcceptSession = autoAccept;

                // Set the Group Owner intent to a large value so that the advertiser will try to become the group owner (GO)
                // NOTE: The GO of a P2P connection can connect to multiple clients while the client can connect to a single GO only
                advertiser.PreferGroupOwnerMode = preferGO;

                // Default status is "Available", but services may use a custom status code (value > 1) if applicable
                advertiser.ServiceStatus           = status;
                advertiser.CustomServiceStatusCode = customStatus;

                // Service information can be up to 65000 bytes.
                // Service Seeker may explicitly discover this by specifying a short buffer that is a subset of this buffer.
                // If seeker portion matches, then entire buffer is returned, otherwise, the service information is not returned to the seeker
                // This sample uses a string for the buffer but it can be any data
                if (serviceInfo != null && serviceInfo.Length > 0)
                {
                    using (var tempStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                    {
                        using (var serviceInfoDataWriter = new Windows.Storage.Streams.DataWriter(tempStream))
                        {
                            serviceInfoDataWriter.WriteString(serviceInfo);
                            advertiser.ServiceInfo = serviceInfoDataWriter.DetachBuffer();
                        }
                    }
                }
                else
                {
                    advertiser.ServiceInfo = null;
                }

                // This is a buffer of up to 144 bytes that is sent to the seeker in case the connection is "deferred" (i.e. not auto-accepted)
                // This buffer will be sent when auto-accept is false, or if a PIN is required to complete the connection
                // For the sample, we use a string, but it can contain any data
                if (deferredServiceInfo != null && deferredServiceInfo.Length > 0)
                {
                    using (var tempStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                    {
                        using (var deferredSessionInfoDataWriter = new Windows.Storage.Streams.DataWriter(tempStream))
                        {
                            deferredSessionInfoDataWriter.WriteString(deferredServiceInfo);
                            advertiser.DeferredSessionInfo = deferredSessionInfoDataWriter.DetachBuffer();
                        }
                    }
                }
                else
                {
                    advertiser.DeferredSessionInfo = null;
                }

                // The advertiser supported configuration methods
                // Valid values are PIN-only (either keypad entry, display, or both), or PIN (keypad entry, display, or both) and WFD Services default
                // WFD Services Default config method does not require explicit PIN entry and offers a more seamless connection experience
                // Typically, an advertiser will support PIN display (and WFD Services Default), and a seeker will connect with either PIN entry or WFD Services Default
                if (configMethods != null)
                {
                    advertiser.PreferredConfigurationMethods.Clear();
                    foreach (var configMethod in configMethods)
                    {
                        advertiser.PreferredConfigurationMethods.Add(configMethod);
                    }
                }

                // Advertiser may also be discoverable by a prefix of the service name. Must explicitly specify prefixes allowed here.
                if (prefixList != null && prefixList.Count > 0)
                {
                    advertiser.ServiceNamePrefixes.Clear();
                    foreach (var prefix in prefixList)
                    {
                        advertiser.ServiceNamePrefixes.Add(prefix);
                    }
                }

                // For this sample, we wrap the advertiser in our own object which handles the advertiser events
                AdvertisementWrapper advertiserWrapper = new AdvertisementWrapper(advertiser, this, pin);

                AddAdvertiser(advertiserWrapper);

                RootPage.NotifyUser("Starting service...", NotifyType.StatusMessage);

                try
                {
                    // This may fail if the driver is unable to handle the request or if services is not supported
                    // NOTE: this must be called from the UI thread of the app
                    advertiser.Start();
                }
                catch (Exception ex)
                {
                    RootPage.NotifyUser(String.Format(CultureInfo.InvariantCulture, "Failed to start service: {0}", ex.Message), NotifyType.ErrorMessage);
                    throw;
                }
            }
Пример #50
0
        public async Task OpenAppFile(string fileName)
        {
            try // Create a local files (open and add text if exist) for writing a short text
            {
                // Create sample file, open if exists
                string fn = fileName + "-Sequensial.txt";
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile sampleFile =
                    await storageFolder.CreateFileAsync(fn,
                                                        Windows.Storage.CreationCollisionOption.OpenIfExists);

                // Writing to the file
                await Windows.Storage.FileIO.AppendTextAsync(sampleFile, "Swift as a shadow" + Environment.NewLine);
            }
            catch (Exception ex)
            {
                DebugTextBox.Text += ex.Message;
            }

            try // Create a local files (open and add text if exist) for writing a short text
            {
                // Create sample stream file, open if exists
                string fn = fileName + "-Stream.txt";
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;
                Windows.Storage.StorageFile sampleFile =
                    await storageFolder.CreateFileAsync(fn,
                                                        Windows.Storage.CreationCollisionOption.OpenIfExists);

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

                using (var outputStream = stream.GetOutputStreamAt(stream.Size))
                {
                    // We'll add more code here in the next step.
                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                    {
                        dataWriter.WriteString("DataWriter has methods to write to various types, such as DataTimeOffset." + Environment.NewLine);
                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();
                    }
                }
                stream.Dispose(); // Or use the stream variable (see previous code snippet) with a using statement as well.
            }
            catch (Exception ex)
            {
                DebugTextBox.Text += ex.Message;
            }

            try // Initial/create OneDrive stream for write/append text
            {
                // Create file Stream towards OneDrive datastore
            }
            catch (Exception ex)
            {
                DebugTextBox.Text += ex.Message;
            }

            //OK, then we are ready to read/write file

            /*            try // Try to open file at USB drive
             *          {
             *              var removableDevices = KnownFolders.RemovableDevices;
             *              var externalDrives = await removableDevices.GetFoldersAsync();
             *              var usbDrive = externalDrives.Single(e => e.DisplayName.Contains("USB DISK"));
             *              string fn = usbDrive.Name + string.Format("{0}.jpg", fileName);
             *
             *              DebugTextBox.Text += "Will try to open:" + fn + " on USB Drive:" + usbDrive.Name;
             *
             *              StorageFile appconfig = await usbDrive.CreateFileAsync(
             *                  fn,
             *                  CreationCollisionOption.OpenIfExists);
             *
             *              using (StreamReader reader = new StreamReader(await appconfig.OpenStreamForReadAsync()))
             *              {
             *                  var data = await reader.ReadToEndAsync();
             *                  AppData = Newtonsoft.Json.JsonConvert.DeserializeObject<MyAppData>(data);
             *              }
             *          }
             *          catch (Exception ex)
             *          {
             *              // error
             *              DebugTextBox.Text += ex.Message;
             *          }
             */
            try
            {
                // Open and read the file

                // Create/open sample file; replace if exists.

                string fn = fileName + ".jpg";
                Windows.Storage.StorageFolder storageFolder =
                    Windows.Storage.ApplicationData.Current.LocalFolder;

                DebugTextBox.Text += "Will try to open: " + fn + " in " + storageFolder.Path;

                StorageFile appconfig = await storageFolder.CreateFileAsync(fn,
                                                                            Windows.Storage.CreationCollisionOption.OpenIfExists);

                using (StreamReader reader = new StreamReader(await appconfig.OpenStreamForReadAsync()))
                {
                    var data = await reader.ReadToEndAsync();

                    AppData = Newtonsoft.Json.JsonConvert.DeserializeObject <MyAppData>(data);
                }
            }
            catch (Exception ex)
            {
                // Exceptopn
                DebugTextBox.Text += ex.Message;
            }
        }
Пример #51
0
        public async Task DoStuff()
        {
            ProgressBar.Visibility = Visibility.Visible;

            var ocrEngine = OcrEngine.TryCreateFromUserProfileLanguages();
            var startTime = new TimeSpan(0, 19, 30);
            var endTime   = new TimeSpan(0, 28, 00);

            //00070 at 1566,215,98,25
            //00.8 at 1770,213,69,25
            var speedRect = new Rect(1550, 210, 120, 35);
            //var speedRect = new Rect( 1566, 215, 97, 25 );
            var altitudeRect = new Rect(1750, 210, 90, 35);


            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".mp4");

            var flight = new List <FlightPoint>();

            StorageFile file = await openPicker.PickSingleFileAsync();

            var fileSavePicker = new FileSavePicker
            {
                SuggestedFileName      = file.DisplayName,
                SuggestedStartLocation = PickerLocationId.Downloads
            };

            fileSavePicker.FileTypeChoices.Add("CSV File", new List <string> {
                ".csv"
            });

            StorageFile csvFile = await fileSavePicker.PickSaveFileAsync();

            var mediaClip = await MediaClip.CreateFromFileAsync(file);

            var mediaComposition = new MediaComposition();

            mediaComposition.Clips.Add(mediaClip);

            var ocrTime    = endTime - startTime;
            var ocrSeconds = (int)ocrTime.TotalSeconds;

            var speed    = 0m;
            var altitude = 0m;

            this.ProgressBar.Maximum = ocrSeconds;

            //var width = PreviewImage.Width;
            //var height = PreviewImage.Height;

            //var encodingProperties = mediaClip.GetVideoEncodingProperties();
            //var videoWidth = encodingProperties.Width;
            //var videoHeight = encodingProperties.Height;

            //var widthFactor = (width / videoWidth);
            //var heightFactor = height / videoHeight;

            //OutlineOcrSection(speedRect, widthFactor, heightFactor);
            //OutlineOcrSection(altitudeRect, widthFactor, heightFactor);


            for (var i = 0; i < ocrSeconds; i++)
            {
                var currentTime = startTime + TimeSpan.FromSeconds(i);
                var thumbnail   = await mediaComposition.GetThumbnailAsync(currentTime, 0, 0, VideoFramePrecision.NearestFrame);

                var decoder = await BitmapDecoder.CreateAsync(thumbnail);

                var bitmap = await decoder.GetSoftwareBitmapAsync();

                await SetPreviewImage(bitmap);

                var result = await ocrEngine.RecognizeAsync(bitmap);

                bool velPassed   = false;
                bool speedPassed = false;

                foreach (var line in result.Lines)
                {
                    // Iterate over words in line.
                    foreach (var word in line.Words)
                    {
                        //if (speedRect.Contains(new Point(word.BoundingRect.X + word.BoundingRect.Width / 2, word.BoundingRect.Y + word.BoundingRect.Height / 2)))
                        //    //&& speedRect.Contains(new Point(word.BoundingRect.X + word.BoundingRect.Width, word.BoundingRect.Y + word.BoundingRect.Height)))
                        //{
                        //    decimal tempSpeed;
                        //    if (decimal.TryParse(word.Text, out tempSpeed))
                        //    {
                        //        speed = Math.Abs(tempSpeed);
                        //        this.Velocity.Text = speed.ToString(CultureInfo.InvariantCulture);
                        //        velPassed = true;
                        //    }

                        //}

                        //if (altitudeRect.Contains(new Point(word.BoundingRect.X, word.BoundingRect.Y)))
                        //    //&& speedRect.Contains(new Point(word.BoundingRect.X + word.BoundingRect.Width, word.BoundingRect.Y + word.BoundingRect.Height)))
                        //{
                        //    decimal tempAltitude;
                        //    if (decimal.TryParse(word.Text, out tempAltitude))
                        //    {
                        //        altitude = Math.Abs(tempAltitude);
                        //        Altitude.Text = altitude.ToString(CultureInfo.InvariantCulture);
                        //        speedPassed = true;
                        //    }
                        //}
                    }
                }

                if (!speedPassed || !velPassed)
                {
                    Debug.WriteLine(result.Text);
                }

                var time = TimeSpan.FromSeconds(i);
                this.Time.Text = time.ToString();

                var point = new FlightPoint {
                    Velocity = speed, Altitude = altitude, Time = time
                };
                Debug.WriteLine($"{point.Time}, {point.Altitude}, {point.Velocity}");
                flight.Add(point);

                ProgressBar.Value = i;
            }

            // Get information about the preview
            //var previewProperties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview) as VideoEncodingProperties;

            using (IRandomAccessStream stream = await csvFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(stream))
                {
                    dataWriter.WriteString("time,altitude,velocity,acceleration");
                    decimal prevVelocity = 0;
                    var     prevTime     = TimeSpan.Zero;
                    foreach (var entry in flight)
                    {
                        var timeDelta = (decimal)(entry.Time - prevTime).TotalSeconds;
                        var ac        = 0m;
                        if (timeDelta > 0)
                        {
                            ac = (entry.Velocity - prevVelocity) / timeDelta;
                        }

                        prevVelocity = entry.Velocity;
                        prevTime     = entry.Time;

                        dataWriter.WriteString($"{entry.Time}, {entry.Altitude}, {entry.Velocity}, {ac}{Environment.NewLine}");
                    }
                    await dataWriter.StoreAsync();

                    await stream.FlushAsync();
                }
            }

            this.ProgressBar.Visibility = Visibility.Collapsed;
        }
        // Handles PeerFinder_AdvertiseButton click
        void PeerFinder_StartAdvertising(object sender, RoutedEventArgs e)
        {
            // If PeerFinder is started, stop it, so that new properties
            // selected by the user (Role/DiscoveryData) can be updated.
            if (_peerFinderStarted)
            {
                PeerFinder.Stop();
                _peerFinderStarted = false;
            }

            rootPage.NotifyUser("", NotifyType.ErrorMessage);
            if (!_peerFinderStarted)
            {
                // attach the callback handler (there can only be one PeerConnectProgress handler).
                PeerFinder.TriggeredConnectionStateChanged += new TypedEventHandler <object, TriggeredConnectionStateChangedEventArgs>(TriggeredConnectionStateChangedEventHandler);
                // attach the incoming connection request event handler
                PeerFinder.ConnectionRequested += new TypedEventHandler <object, ConnectionRequestedEventArgs>(PeerConnectionRequested);

                // Set the PeerFinder.Role property
                if (_launchByTap)
                {
                    PeerFinder.Role = rootPage.GetLaunchRole();
                }
                else
                {
                    switch (PeerFinder_SelectRole.SelectionBoxItem.ToString())
                    {
                    case "Peer":
                        PeerFinder.Role = PeerRole.Peer;
                        break;

                    case "Host":
                        PeerFinder.Role = PeerRole.Host;
                        break;

                    case "Client":
                        PeerFinder.Role = PeerRole.Client;
                        break;
                    }
                }

                // Set DiscoveryData property if the user entered some text
                if ((PeerFinder_DiscoveryData.Text.Length > 0) && (PeerFinder_DiscoveryData.Text != "What's happening today?"))
                {
                    using (var discoveryDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()))
                    {
                        discoveryDataWriter.WriteString(PeerFinder_DiscoveryData.Text);
                        PeerFinder.DiscoveryData = discoveryDataWriter.DetachBuffer();
                    }
                }

                // start listening for proximate peers
                PeerFinder.Start();
                _peerFinderStarted = true;
                if (_browseConnectSupported && _triggeredConnectSupported)
                {
                    rootPage.NotifyUser("Tap another device to connect to a peer or click Browse for Peers button.", NotifyType.StatusMessage);
                    PeerFinder_BrowsePeersButton.Visibility = Visibility.Visible;
                    PeerFinder_SelectRole.Visibility        = Visibility.Visible;
                    PeerFinder_DiscoveryData.Visibility     = Visibility.Visible;
                }
                else if (_triggeredConnectSupported)
                {
                    rootPage.NotifyUser("Tap another device to connect to a peer.", NotifyType.StatusMessage);
                    PeerFinder_SelectRole.Visibility = Visibility.Visible;
                }
                else if (_browseConnectSupported)
                {
                    rootPage.NotifyUser("Click Browse for Peers button.", NotifyType.StatusMessage);
                    PeerFinder_BrowsePeersButton.Visibility = Visibility.Visible;
                    PeerFinder_SelectRole.Visibility        = Visibility.Visible;
                    PeerFinder_DiscoveryData.Visibility     = Visibility.Visible;
                }
            }
        }
Пример #53
0
        ///------------------------------------------ SAVE DATA TO STREAM -------------------------------------------------------------
        public async Task saveToCSV(IData data, bool stop)
        {
            try
            {
                /* Ways to reduce:
                 * Do not write any values that are repeating over the previous one
                 *
                 */

                var data_quaternion = data.Value <EulerAngles>();
                var data_q_ts       = data.FormattedTimestamp;
                var data_q_H        = data_quaternion.Heading;

                string1 = data_q_ts + "," + trial_time_ms.ToString() + "," + data_q_H + "," + array3 + "," + array4 + "," + angle_actual_maze + "," + processed_x + "," + processed_y + "\r\n";

                if (stop == false)
                {
                    if (i < 1)
                    {
                        builder.Append(string1);
                        i++;
                    }

                    else
                    {
                        builder.Append(string1);
                        string innerString = builder.ToString();
                        using (var outputStream = csv_stream.GetOutputStreamAt(csv_stream.Size))
                        {
                            using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                            {
                                dataWriter.WriteString(innerString);
                                await dataWriter.StoreAsync();

                                await outputStream.FlushAsync();
                            }
                        }

                        innerString = ""; //flush varaible
                        builder.Clear();
                        i = 0;            //reset counter
                    }
                }

                if (stop == true)
                {
                    builder.Append(string1);
                    string innerString = builder.ToString();
                    using (var outputStream = csv_stream.GetOutputStreamAt(csv_stream.Size))
                    {
                        using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                        {
                            dataWriter.WriteString(innerString);
                            await dataWriter.StoreAsync();

                            await outputStream.FlushAsync();
                        }
                    }

                    innerString = ""; //flush varaible
                    builder.Clear();
                    i = 0;            //reset counter
                }


                if (toggle_data_rec_set_already_trig == false)
                {
                    toggle_data_rec_set_success      = true;
                    toggle_data_rec_set_already_trig = true;
                }
            }

            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("save to csv error" + ex.Message);
            }
        }
Пример #54
0
        public async void SaveToFile(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            //Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
            //Windows.Storage.StorageFile surveyFile = await storageFolder.GetFileAsync("testSurveyPage.html");
            //CurrentBenefitCollection[0].BenefitLabel = Benefit1TitleBox.Text;
            //CurrentBenefitCollection[0].BenefitText = Benefit1TextBox.Text;
            //CurrentBenefitCollection[1].BenefitLabel = Benefit1TitleBox.Text;
            //CurrentBenefitCollection[1].BenefitText = Benefit2TextBox.Text;
            //CurrentBenefitCollection[2].BenefitLabel = Benefit1TitleBox.Text;
            //CurrentBenefitCollection[2].BenefitText = Benefit3TextBox.Text;
            //CurrentBenefitCollection[3].BenefitLabel = Benefit1TitleBox.Text;
            //CurrentBenefitCollection[3].BenefitText = Benefit4TextBox.Text;

            //ShuffleIndexes();

            //Debug.WriteLine("Hey: " + CurrentBenefitCollection[indexArray[0]].BenefitImage);

            /*surveyTemplateString = staticTemplateArray[0]
             + CurrentBenefitCollection[0].BenefitLabel + staticTemplateArray[1]
             + rootURL + CurrentBenefitCollection[indexArray[0]].BenefitImage.OriginalString.Substring(10) + staticTemplateArray[2]
             + CurrentBenefitCollection[indexArray[0]].BenefitText + staticTemplateArray[3]
             + CurrentBenefitCollection[1].BenefitLabel + staticTemplateArray[4]
             + rootURL + CurrentBenefitCollection[indexArray[1]].BenefitImage.OriginalString.Substring(10) + staticTemplateArray[5]
             + CurrentBenefitCollection[indexArray[1]].BenefitText + staticTemplateArray[6]
             + CurrentBenefitCollection[2].BenefitLabel + staticTemplateArray[7]
             + rootURL + CurrentBenefitCollection[indexArray[2]].BenefitImage.OriginalString.Substring(10) + staticTemplateArray[8]
             + CurrentBenefitCollection[indexArray[2]].BenefitText + staticTemplateArray[9]
             + CurrentBenefitCollection[3].BenefitLabel + staticTemplateArray[10]
             + rootURL + CurrentBenefitCollection[indexArray[3]].BenefitImage.OriginalString.Substring(10) + staticTemplateArray[11]
             + CurrentBenefitCollection[indexArray[3]].BenefitText + staticTemplateArray[12]
             + pageNumber + staticTemplateArray[13];*/

            //StorageFile tempImageFile = await storageFolder.CreateFileAsync("tempImageFile.png");
            //await UploadOpAsync(CurrentBenefitCollection[3].BenefitImage.UriSource, tempImageFile);



            //Windows.Storage.StorageFolder filesFolder = ApplicationData.Current.LocalFolder;//.GetFolderAsync("TestSurveyApp/Surveys");//await folderPicker.PickSingleFolderAsync();


            //folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
            //folderPicker.FileTypeFilter.Add("*");

            /*Windows.Storage.StorageFolder filesFolder = await folderPicker.PickSingleFolderAsync();
             * if (filesFolder.TryGetItemAsync(surveyName) != null)
             * {
             *  surveyFolder = await filesFolder.CreateFolderAsync(surveyName);
             * }
             * else
             * {
             *  surveyFolder = await filesFolder.GetFolderAsync(surveyName);
             * }*/
            /*if (surveyFolder != null)
             * {
             *  surveyName = surveyFolder.Name;//await filesFolder.CreateFolderAsync(surveyName);
             * }*/
            //if (surveyFolder != null)
            //{
            //for (int i = 0; i < 8; i++)
            //{
            var stream2    = new MemoryStream();
            var serializer = new DataContractJsonSerializer(typeof(ObservableCollection <ObservableCollection <Benefit> >));

            serializer.WriteObject(stream2, App.SurveyBenefitCollection.FinalBenefitList);

            filePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads;
            Windows.Storage.StorageFile surveyFile = await filePicker.PickSaveFileAsync();

            App.surveyFile   = surveyFile;
            stream2.Position = 0;
            var streamReader = new StreamReader(stream2);
            //dataWriter.WriteString(streamReader.ReadToEnd());
            //Debug.WriteLine(streamReader.ReadToEnd());
            //var pageFile = await surveyFolder.CreateFileAsync(surveyName + "Page" + ".html");
            var stream = await surveyFile.OpenAsync(FileAccessMode.ReadWrite);

            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    //Debug.WriteLine("Should Write Stuff.");
                    //string pageTemplateString = staticTemplateArray[0] + App.surveyFile.Name + staticTemplateArray[1];

                    //dataWriter.WriteString(pageTemplateString);
                    dataWriter.WriteString(streamReader.ReadToEnd());

                    stream.Size = await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }
            stream.Dispose();

            StorageFile surveyLogic = await App.surveyFolder.CreateFileAsync("surveyLogic.php", CreationCollisionOption.ReplaceExisting);

            stream = await surveyLogic.OpenAsync(FileAccessMode.ReadWrite);

            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    //Debug.WriteLine("Should Write Stuff.");
                    string pageTemplateString = staticTemplateArray[0] + App.surveyFile.Name + staticTemplateArray[1];

                    dataWriter.WriteString(pageTemplateString);

                    await dataWriter.StoreAsync();

                    await outputStream.FlushAsync();
                }
            }
            stream.Dispose();
        }