ReadString() public méthode

public ReadString ( ) : string
Résultat string
        async void OnFileOpenButtonClick(object sender, RoutedEventArgs args) {
            FileOpenPicker picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".txt");
            StorageFile storageFile = await picker.PickSingleFileAsync();

            // If user presses Cancel, result is null
            if (storageFile == null)
                return;

            Exception exception = null;

            try {
                using (IRandomAccessStream stream = await storageFile.OpenReadAsync()) {
                    using (DataReader dataReader = new DataReader(stream)) {
                        uint length = (uint)stream.Size;
                        await dataReader.LoadAsync(length);
                        txtbox.Text = dataReader.ReadString(length);
                    }
                }
            }
            catch (Exception exc) {
                exception = exc;
            }

            if (exception != null) {
                MessageDialog msgdlg = new MessageDialog(exception.Message, "File Read Error");
                await msgdlg.ShowAsync();
            }
        }
 private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
 {
     StorageFile file = rootPage.sampleFile;
     if (file != null)
     {
         try
         {
             using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
             {
                 using (DataReader dataReader = new DataReader(readStream))
                 {
                     UInt64 size = readStream.Size;
                     if (size <= UInt32.MaxValue)
                     {
                         UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
                         string fileContent = dataReader.ReadString(numBytesLoaded);
                         rootPage.NotifyUser(String.Format("The following text was read from '{0}' using a stream:{1}{2}", file.Name, Environment.NewLine, fileContent), NotifyType.StatusMessage);
                     }
                     else
                     {
                         rootPage.NotifyUser(String.Format("File {0} is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.", file.Name), NotifyType.ErrorMessage);
                     }
                 }
             }
         }
         catch (FileNotFoundException)
         {
             rootPage.NotifyUserFileNotExist();
         }
     }
     else
     {
         rootPage.NotifyUserFileNotExist();
     }
 }
        public async Task<IEnumerable<Event>> Read() 
        {
            List<Event> events = null;
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            try
            {
                StorageFile textFile = await localFolder.GetFileAsync("SavedContent");
                events = new List<Event>();
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        string jsonContents = textReader.ReadString(textLength);
                        events = JsonConvert.DeserializeObject<IList<Event>>(jsonContents) as List<Event>;
                    }
                    return events;
                }
            }
            catch (Exception ex)
            {
                return null;
            }

        }
        private async Task<string> readHTTPMessage(DataReader dr)
        {
            // Make sure we are allowed to return early
            dr.InputStreamOptions = InputStreamOptions.Partial;

            // This is the value we will return
            string ret = "";

            // This is the amount of data ready to be read in
            uint readyLen;
            while (true)
            {
                // Wait until we've got a kilobyte, or the stream closed
                readyLen = await dr.LoadAsync(1024 * 1024);

                // Check to see if we actually have any data
                if (readyLen > 0)
                {
                    // Read in that string, append it to ret
                    ret += dr.ReadString(readyLen);

                    // Check for the "\r\n\r\n" at the end of messages
                    if (ret.Substring(ret.Length - 4, 4) == "\r\n\r\n")
                        break;
                }
                else
                {
                    // If not, the connection is closed!
                    return ret;
                }
            }

            // Finally, return that string
            return ret;
        }
        public async void OnOpen()
        {
            try
            {
                var picker = new FileOpenPicker()
                {
                    SuggestedStartLocation = PickerLocationId.DocumentsLibrary
                };
                picker.FileTypeFilter.Add(".txt");

                StorageFile file = await picker.PickSingleFileAsync();
                if (file != null)
                {
                    IRandomAccessStreamWithContentType stream = await file.OpenReadAsync();
                    using (var reader = new DataReader(stream))
                    {
                        await reader.LoadAsync((uint)stream.Size);

                        text1.Text = reader.ReadString((uint)stream.Size);
                    }
                }
            }
            catch (Exception ex)
            {
                var dlg = new MessageDialog(ex.Message, "Error");
                await dlg.ShowAsync();
            }
        }
 private async void ReadFromStreamButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         rootPage.ResetScenarioOutput(OutputTextBlock);
         StorageFile file = rootPage.sampleFile;
         if (file != null)
         {
             using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
             {
                 using (DataReader dataReader = new DataReader(readStream))
                 {
                     UInt64 size = readStream.Size;
                     if (size <= UInt32.MaxValue)
                     {
                         UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
                         string fileContent = dataReader.ReadString(numBytesLoaded);
                         OutputTextBlock.Text = "The following text was read from '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + fileContent;
                     }
                     else
                     {
                         OutputTextBlock.Text = "File " + file.Name + " is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync.";
                     }
                 }
             }
         }
     }
     catch (FileNotFoundException)
     {
         rootPage.NotifyUserFileNotExist();
     }
 }
 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());
 }
        private async void ReadBlock_Click(object sender, RoutedEventArgs e)
        {
            var fx2Device = DeviceList.Current.GetSelectedDevice();

            if (fx2Device == null)
            {
                rootPage.NotifyUser("Fx2 device not connected or accessible", NotifyType.ErrorMessage);
                return;
            }

            var button = (Button)sender;
            button.IsEnabled = false;

            var dataReader = new DataReader(fx2Device.InputStream);

            // load the data reader from the stream.  For purposes of this 
            // sample, assume all messages read are < 64 bytes

            int counter = readCounter++;

            LogMessage("Read {0} begin", counter);
            await dataReader.LoadAsync(64);
            
            // Get the message string out of the buffer
            var message = dataReader.ReadString(dataReader.UnconsumedBufferLength);

            LogMessage("Read {0} end: {1}", counter, message);

            button.IsEnabled = true;
        }
 public void ReadAllText(string filename, Action<string> completed)
 {
     StorageFolder localFolder = 
                     ApplicationData.Current.LocalFolder;
     IAsyncOperation<StorageFile> createOp = 
                     localFolder.GetFileAsync(filename);
     createOp.Completed = (asyncInfo1, asyncStatus1) =>
     {
         IStorageFile storageFile = asyncInfo1.GetResults();
         IAsyncOperation<IRandomAccessStreamWithContentType> 
             openOp = storageFile.OpenReadAsync();
         openOp.Completed = (asyncInfo2, asyncStatus2) =>
         {
             IRandomAccessStream stream = asyncInfo2.GetResults();
             DataReader dataReader = new DataReader(stream);
             uint length = (uint)stream.Size;
             DataReaderLoadOperation loadOp = 
                                 dataReader.LoadAsync(length);
             loadOp.Completed = (asyncInfo3, asyncStatus3) =>
             {
                 string text = dataReader.ReadString(length);
                 dataReader.Dispose();
                 completed(text);
             };
         };
     };
 }
Exemple #10
0
        public static async Task<AppModel> DeserializeAppData()
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            AppModel appModel = null;
            try
            {
                // Getting JSON from file if it exists, or file not found exception if it does not  
                StorageFile textFile = await localFolder.GetFileAsync("app.json");
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    // Read text stream     
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        //get size                       
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        // read it                    
                        string jsonContents = textReader.ReadString(textLength);
                        // deserialize back to our product!  
                        appModel = JsonConvert.DeserializeObject<AppModel>(jsonContents);
                       
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return appModel;
        }
Exemple #11
0
        async private void OpenGraphFile_Click(object sender, RoutedEventArgs e)
        {
            var picker = new FileOpenPicker();
            picker.FileTypeFilter.Add(".txt");
            picker.ViewMode = PickerViewMode.Thumbnail;
            picker.SettingsIdentifier = "GraphPicker";
            picker.CommitButtonText = "Select Files";

            var selectedFile = await picker.PickSingleFileAsync();
            using (IRandomAccessStream stream = await selectedFile.OpenReadAsync())
            {
                using (DataReader reader = new DataReader(stream))
                {
                    uint length = (uint)stream.Size;
                    await reader.LoadAsync(length);
                    string[] s = reader.ReadString(length).Split('\r');
                    string[][] str = new string[s.Length][];
                    for (int i = 0; i < s.Length; i++)
                        str[i] = s[i].Replace('\n', ' ').Split(' ');
                    int n = int.Parse(s[0]);
                    int[,] adjMatrix = new int[n, n];
                    for (int i = 0; i < n; i++)
                        for (int j = 0; j < n; j++)
                            adjMatrix[i, j] = int.Parse(str[i + 1][j + 1]);
                    adjMatrix[0, 0] += 0;
                    graph = new Graph(adjMatrix, n);
                }
            }
        }
Exemple #12
0
		public static async Task<bool> LoadFrom ( ObservableCollection<RecentData> datas )
		{
			try
			{
				StorageFile sf = await ApplicationData.Current.LocalFolder.GetFileAsync ( "data.dat" );
				FileRandomAccessStream stream = await sf.OpenAsync ( FileAccessMode.Read ) as FileRandomAccessStream;
				DataReader dr = new DataReader ( stream );
				dr.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
				dr.ByteOrder = ByteOrder.LittleEndian;

				await dr.LoadAsync ( ( uint ) stream.Size );

				int len = dr.ReadInt32 ();
				for ( int i = 0; i < len; i++ )
				{
					RecentData data = new RecentData ();
					uint srclen = dr.ReadUInt32 ();
					data.Source = dr.ReadString ( srclen );
					data.SourceIndex = dr.ReadInt32 ();
					data.TargetIndex = dr.ReadInt32 ();
					datas.Add ( data );
				}

				stream.Dispose ();
			}
			catch { return false; }
			return true;
		}
Exemple #13
0
        public async Task <string> ReadLogFile(string fileName)
        {
            if (fileName != this.FQP)
            {
                int index = fileName.IndexOf(DIRECTORY_NAME);
                fileName = fileName.Substring(index);
                var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

                if (file == null)
                {
                    return("");
                }

                return(await Windows.Storage.FileIO.ReadTextAsync(file));
            }

            if (_logFile != null)
            {
                using (var inputStream = _stream.GetInputStreamAt(0))
                {
                    Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inputStream);
                    await reader.LoadAsync((uint)_stream.Size);

                    string data = reader.ReadString((uint)_stream.Size);
                    reader.DetachStream();
                    return(data);
                }
            }

            return("");
        }
Exemple #14
0
        public async void LoadSettings()
        {
            try
            {
                string contents;

                StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                StorageFile textFile = await localFolder.GetFileAsync("settingV2");

                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                    using (DataReader textReader = new DataReader(textStream))
                    {
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        contents = textReader.ReadString(textLength);
                    }
                }

                string[] lines = contents.Split('\n');

                bool.TryParse(lines[0], out AutoJoinChat);
                bool.TryParse(lines[1], out LockLandscape);
                bool.TryParse(lines[2], out LiveTilesEnabled);
            }

            catch { }
        }
Exemple #15
0
        /// <summary>
        /// Read string content from file.
        /// </summary>
        /// <param name="path">Location of file, separate by //.</param>
        /// <param name="rootFolder"> </param>
        /// <returns>Content of file.</returns>
        public async Task<string> ReadFromFileAsync(string path, StorageFolder rootFolder = null)
        {
            if (path == null)
            {
                return null;
            }

            try
            {
                var file = await GetFileToReadAsync(path, rootFolder);

                if (file == null)
                {
                    return null;
                }

                var readStream = await file.OpenAsync(FileAccessMode.Read);

                var inputStream = readStream.GetInputStreamAt(0);
                var dataReader = new DataReader(inputStream);

                var numBytesLoaded = await dataReader.LoadAsync((uint)readStream.Size);
                var content = dataReader.ReadString(numBytesLoaded);
                dataReader.DetachStream();
                dataReader.Dispose();
                inputStream.Dispose();
                readStream.Dispose();

                return content;
            }
            catch
            {
                return null;
            }
        }
        private async void OnForegroundSocketClicked(object sender, RoutedEventArgs e)
        {
            socket = new StreamSocket();
            HostName host = new HostName("localhost");

            try
            {
                await socket.ConnectAsync(host, "1983");

                isConnected = true;
                while (isConnected)
                {
                    try
                    {
                        DataReader reader;

                        using (reader = new DataReader(socket.InputStream))
                        {
                            // Set the DataReader to only wait for available data (so that we don't have to know the data size)
                            reader.InputStreamOptions = InputStreamOptions.Partial;
                            // The encoding and byte order need to match the settings of the writer we previously used.
                            reader.UnicodeEncoding = UnicodeEncoding.Utf8;
                            reader.ByteOrder = ByteOrder.LittleEndian;

                            // Send the contents of the writer to the backing stream. 
                            // Get the size of the buffer that has not been read.
                            await reader.LoadAsync(256);

                            // Keep reading until we consume the complete stream.
                            while (reader.UnconsumedBufferLength > 0)
                            {
                                string readString = reader.ReadString(reader.UnconsumedBufferLength);
                                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    messages.Add(readString);
                                });
                                Debug.WriteLine(readString);
                                await reader.LoadAsync(256);
                            }

                            reader.DetachStream();

                        }

                    }
                    catch (Exception exc)
                    {
                        MessageDialog dialog = new MessageDialog("Error reading the data");
                        await dialog.ShowAsync();
                    }
                }
            }
            catch (Exception exc)
            {
                MessageDialog dialog = new MessageDialog("Error connecting to the socket");
                await dialog.ShowAsync();
            }
        }
 public static async Task<string> LoadAndRemoveBOM(this StorageFile storageFile)
 {
     IRandomAccessStream readStream = await storageFile.OpenAsync(FileAccessMode.Read);
     IInputStream inputSteam = readStream.GetInputStreamAt(0);
     DataReader dataReader = new DataReader(inputSteam);
     uint numBytesLoaded = await dataReader.LoadAsync((uint)readStream.Size);
     string output = dataReader.ReadString(numBytesLoaded);
     return output.Trim(UTF8_BYTE_ORDER_MARK.ToCharArray());
 }
 async public static Task<string> ReadAllTextAsync(this StorageFile storageFile)
 {
     var inputStream = await storageFile.OpenAsync(FileAccessMode.Read);
     var readStream = inputStream.GetInputStreamAt(0);
     var reader = new DataReader(readStream);
     uint fileLength = await reader.LoadAsync((uint)inputStream.Size);
     string content = reader.ReadString(fileLength);
     return content;
 }
Exemple #19
0
        private void ReadDataFromDevice(DataReader reader)
        {
            reader.InputStreamOptions = InputStreamOptions.Partial;
            reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
            var size = reader.UnconsumedBufferLength;
            var message = reader.ReadString(size);
            SendDataToDevice("Ack " + message);
            ProcessMessage(message).Wait();

        }
Exemple #20
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);
        }
        /// <summary>
        /// Gets intent and entities from a text string
        /// </summary>
        /// <returns>Unprocessed result from a server</returns>
        public async Task<string> GetAsync()
        {
            return await Task.Run<string>(async () =>
            {
                try
                {
                    var socket = new StreamSocket();

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

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

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

                    writer.WriteBytes(headersPayload);

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

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

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

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

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

                        WitLog.Log(body);

                        return body;
                    }
                    else
                    {
                        return null;
                    }
                }
                catch
                {
                    return null;
                }
            });
        }
        public async Task <T> LoadASync(string FileName)
        {
            FileName = FileName + ".xml";
            try
            {
                StorageFile   file   = null;
                StorageFolder folder = GetFolder(storageType);
                file = await folder.GetFileAsync(FileName);

                //using (var readStream = await file.OpenAsync(FileAccessMode.Read))
                //{
                //    Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(readStream);

                //    await reader.LoadAsync((uint)readStream.Size);
                //    string data = reader.ReadString((uint)readStream.Size);

                //    if (data == null)
                //    {
                //    }
                //}


                using (var readStream = await file.OpenAsync(FileAccessMode.Read))
                {
                    //Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result;
                    //return (T)serializer.Deserialize(inStream);

                    var inStream = readStream.GetInputStreamAt(0);
                    Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(inStream);
                    await reader.LoadAsync((uint)readStream.Size);

                    string data = reader.ReadString((uint)readStream.Size);
                    reader.DetachStream();

                    MemoryStream ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(data));
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                    T result = (T)ser.ReadObject(ms);
                    return(result);
                }
            }
            catch (FileNotFoundException)
            {
                //file not existing is perfectly valid so simply return the default
                return(default(T));
                //throw;
            }
            catch (Exception)
            {
                //Unable to load contents of file
                throw;
            }
        }
Exemple #23
0
        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("Connection Received on Port {0}", sender.Information.LocalPort);
            StreamSocket streamSocket = args.Socket;
            if (streamSocket != null)
            {
                DataReader reader = new DataReader(streamSocket.InputStream);
                try
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    if (sizeFieldCount != sizeof(uint))
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    // Read the length of the 'packet'.
                    uint length = reader.ReadUInt32();
                    uint actualLength = await reader.LoadAsync(length);
                    if (length != actualLength)
                    {
                        // The underlying socket was closed before we were able to read the whole data.
                        return;
                    }

                    string name = reader.ReadString(actualLength);
                    Speaker speaker = new Speaker()
                    {
                        Name = name,
                        Address = streamSocket.Information.RemoteAddress.DisplayName,
                        Status = "Connected",
                        Socket = streamSocket
                    };

                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                    () =>
                    {
                        Speakers.Add(speaker);
                    });

                    reader.DetachStream();

                    Debug.WriteLine("New speaker added " + name);

                }
                catch (Exception e)
                {
                    Debug.WriteLine("Error in connection received: " + e);
                }
            }
        }
        public async Task<string> ReadAsync(string fileName)
        {
            var folder = ApplicationData.Current.LocalFolder;
            var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists);

            using (var stream = await file.OpenReadAsync())
            using (var textReader = new DataReader(stream))
            {
                var textLength = (uint) stream.Size;
                await textReader.LoadAsync(textLength);
                return textReader.ReadString(textLength);
            }
        }
 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     var deferral = taskInstance.GetDeferral();
     try
     {
         var details = taskInstance.TriggerDetails as SocketActivityTriggerDetails;
         var socketInformation = details.SocketInformation;
         switch (details.Reason)
         {
             case SocketActivityTriggerReason.SocketActivity:
                 var socket = socketInformation.StreamSocket;
                 DataReader reader = new DataReader(socket.InputStream);
                 reader.InputStreamOptions = InputStreamOptions.Partial;
                 await reader.LoadAsync(250);
                 var dataString = reader.ReadString(reader.UnconsumedBufferLength);
                 ShowToast(dataString);
                 socket.TransferOwnership(socketInformation.Id);
                 break;
             case SocketActivityTriggerReason.KeepAliveTimerExpired:
                 socket = socketInformation.StreamSocket;
                 DataWriter writer = new DataWriter(socket.OutputStream);
                 writer.WriteBytes(Encoding.UTF8.GetBytes("Keep alive"));
                 await writer.StoreAsync();
                 writer.DetachStream();
                 writer.Dispose();
                 socket.TransferOwnership(socketInformation.Id);
                 break;
             case SocketActivityTriggerReason.SocketClosed:
                 socket = new StreamSocket();
                 socket.EnableTransferOwnership(taskInstance.Task.TaskId, SocketActivityConnectedStandbyAction.Wake);
                 if (ApplicationData.Current.LocalSettings.Values["hostname"] == null)
                 {
                     break;
                 }
                 var hostname = (String)ApplicationData.Current.LocalSettings.Values["hostname"];
                 var port = (String)ApplicationData.Current.LocalSettings.Values["port"];
                 await socket.ConnectAsync(new HostName(hostname), port);
                 socket.TransferOwnership(socketId);
                 break;
             default:
                 break;
         }
         deferral.Complete();
     }
     catch (Exception exception)
     {
         ShowToast(exception.Message);
         deferral.Complete();
     }
 }
Exemple #26
0
 public async Task<String> ReadTextAsync(string filename)
 {
     StorageFolder localFolder = ApplicationData.Current.LocalFolder;
     IStorageFile storageFile = await localFolder.GetFileAsync(filename);
     using(IRandomAccessStream stream = await storageFile.OpenReadAsync())
     {
         using(DataReader dataReader = new DataReader(stream))
         {
             uint length = (uint)stream.Size;
             await dataReader.LoadAsync(length);
             return dataReader.ReadString(length);
         }
     }
 }
        private async void ReadviaStream_Click(object sender, RoutedEventArgs e)
        {
            var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);

            var size = stream.Size;

            using (var inputStream = stream.GetInputStreamAt(0))
            {
                // Add code to use the stream to read your file
                DataReader dataReader = new DataReader(inputStream);
                uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
                string text = dataReader.ReadString(numBytesLoaded);
                txtbox.Text = text;
            }

        }
 internal static async Task<string> ReadTextAsync(this StorageFile file)
 {
     using (var fs = await file.OpenAsync(FileAccessMode.Read))
     {
         using (var inStream = fs.GetInputStreamAt(0))
         {
             using (var dataReader = new DataReader(inStream))
             {
                 await dataReader.LoadAsync((uint)fs.Size);
                 var data = dataReader.ReadString((uint)fs.Size);
                 dataReader.DetachStream();
                 return data;
             }
         }
     }
 }
Exemple #29
0
        public static async void LoadFromFile() {
            var loadPicker = new Windows.Storage.Pickers.FileOpenPicker();
            loadPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
            loadPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
            // Dropdown of file types the user can save the file as
            loadPicker.FileTypeFilter.Add(".json");

            StorageFile file = await loadPicker.PickSingleFileAsync();

            if (file != null) {
                var inputStream = await file.OpenAsync(FileAccessMode.Read);
                var readStream = inputStream.GetInputStreamAt(0);
                var reader = new DataReader(readStream);
                uint fileLength = await reader.LoadAsync((uint)inputStream.Size);
                dataStore.ImportFromJson(reader.ReadString(fileLength));
            }
        }
Exemple #30
0
        internal static async Task<String> ReadFile(string filename)
        {
            string contents;
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            StorageFile textFile = await localFolder.GetFileAsync(filename);

            using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
            {
                using (DataReader textReader = new DataReader(textStream))
                {
                    uint textLength = (uint)textStream.Size;
                    await textReader.LoadAsync(textLength);
                    contents = textReader.ReadString(textLength);
                }
            }
            return contents;

        }
        public async Task<string> ReadFile(string file)
        {
            try
            {
                var storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(file);
                IRandomAccessStream readStream = await storageFile.OpenAsync(FileAccessMode.Read);

                // Read the file to an IInputStream stream, then get and load the DataReader.
                IInputStream inputStream = readStream.GetInputStreamAt(0);
                DataReader dataReader = new DataReader(inputStream);
                uint numBytesLoaded = await dataReader.LoadAsync((uint)readStream.Size);

                return dataReader.ReadString(numBytesLoaded);
            }
            catch (FileNotFoundException)
            {
                return null;
            }
        }
        async Task<string> ReadTextAsync(StorageFile file)
        {
#if NETFX_CORE
            var text = await FileIO.ReadTextAsync(file);
#else
            var text = default(string);
            using (var stream = await file.OpenReadAsync())
            {
                var size = stream.Size;
                using (var inputStream = stream.GetInputStreamAt(0))
                {
                    var dataReader = new DataReader(inputStream);
                    uint numBytesLoaded = await dataReader.LoadAsync((uint)size);
                    text = dataReader.ReadString(numBytesLoaded);
                }
            }
#endif
            return text;
        }
Exemple #33
0
    private void WebSocket_MessageReceived(Windows.Networking.Sockets.MessageWebSocket sender, Windows.Networking.Sockets.MessageWebSocketMessageReceivedEventArgs args)
    {
        try
        {
            using (Windows.Storage.Streams.DataReader dataReader = args.GetDataReader())
            {
                dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                string message = dataReader.ReadString(dataReader.UnconsumedBufferLength);
                Debug.Log("Message received from MessageWebSocket: " + message);
                cmds.Enqueue(message);
                //m_Socket.Dispose();
            }
        }
        catch (Exception ex)
        {
            Windows.Web.WebErrorStatus webErrorStatus = Windows.Networking.Sockets.WebSocketError.GetStatus(ex.GetBaseException().HResult);
            // Add additional code here to handle exceptions.
        }

    }
Exemple #34
0
        public async void StartReader(ConnectedPeer connectedPeer)
        {
            try
            {
                using (var socketReader = new Windows.Storage.Streams.DataReader(connectedPeer._socket.InputStream))
                {
                    // Read the message sent by the remote peer
                    uint bytesRead = await socketReader.LoadAsync(sizeof(uint));

                    if (bytesRead > 0)
                    {
                        uint strLength = (uint)socketReader.ReadUInt32();
                        bytesRead = await socketReader.LoadAsync(strLength);

                        if (bytesRead > 0)
                        {
                            String message = socketReader.ReadString(strLength);
                            OnRaiseMessageEvent(new MessageEventArgs("Got message: " + message));
                            StartReader(connectedPeer); // Start another reader
                        }
                        else
                        {
                            OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                        }
                    }
                    else
                    {
                        OnRaiseSocketErrorEvent(new SocketEventArgs("The remote side closed the socket"));
                    }

                    socketReader.DetachStream();
                }
            }
            catch (Exception e)
            {
                if (!connectedPeer._socketClosed)
                {
                    OnRaiseSocketErrorEvent(new SocketEventArgs("Reading from socket failed: " + e.Message));
                }
            }
        }
Exemple #35
0
        private async void Sck_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            //[email protected]("Message received " + args);

            if (args.MessageType == SocketMessageType.Utf8)
            {
                Windows.Storage.Streams.DataReader messageReader = args.GetDataReader();
                messageReader.UnicodeEncoding = UnicodeEncoding.Utf8;
                string messageString = messageReader.ReadString(messageReader.UnconsumedBufferLength);
                com.codename1.io.websocket.WebSocket.messageReceived(id, messageString);
            }
            else
            {
                Windows.Storage.Streams.IInputStream readStream = args.GetDataStream();
                byte[] readBuffer = new byte[4096];
                try
                {
                    while (true)
                    {
                        if (sender != sck)
                        {
                            return;
                        }

                        IBuffer res = await readStream.ReadAsync(readBuffer.AsBuffer(), (uint)readBuffer.Length, 0);

                        if (res.Length == 0)
                        {
                            return;
                        }
                        byte[] resArr = new byte[res.Length];
                        res.CopyTo(resArr);
                        com.codename1.io.websocket.WebSocket.messageReceived(1, resArr);
                    }
                } catch (Exception ex)
                {
                    com.codename1.io.websocket.WebSocket.errorReceived(id, ex.Message, ex.HResult);
                }
            }
        }
        private async Task TryPostJsonAsync()
        {
            try
            {
                // Construct the HttpClient and Uri. This endpoint is for test purposes only.
                //var myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                //myFilter.AllowUI = false;

                //Windows.Web.Http.Filters.HttpBaseProtocolFilter filter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
                //Windows.Storage.StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
                fileOpenPicker.FileTypeFilter.Add(".json");

                /*fileOpenPicker.FileTypeFilter.Add(".txt");
                 * Windows.Storage.StorageFile credentialsFile = await fileOpenPicker.PickSingleFileAsync();
                 * string text = await Windows.Storage.FileIO.ReadTextAsync(credentialsFile);
                 * string username = text.Split(',')[0];
                 * string password = text.Split(',')[1];
                 * string domain = text.Split(',')[2];*/

                HttpClientHandler handler = new HttpClientHandler();
                handler.Credentials = new NetworkCredential("", "", "");

                System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(handler);

                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                Uri uri = new Uri("https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json");

                // Construct the JSON to post.
                //fileOpenPicker.FileTypeChoices.Add("JSON", new List<string>() { ".json" });

                IStorageFile jsonFile = await fileOpenPicker.PickSingleFileAsync();

                IRandomAccessStream stream = await jsonFile.OpenAsync(FileAccessMode.Read);

                System.Net.Http.MultipartFormDataContent postContent = new MultipartFormDataContent();

                if (stream != null)
                {
                    using (var dataReader = new Windows.Storage.Streams.DataReader(stream))
                    {
                        uint numBytesLoaded = await dataReader.LoadAsync((uint)stream.Size);

                        string jsonText = dataReader.ReadString(numBytesLoaded);

                        System.Net.Http.StringContent streamContent = new System.Net.Http.StringContent(jsonText);
                        streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                        postContent.Add(streamContent);
                        System.Net.Http.HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
                            "https://prodigalcompany.com/npjTest/SurveyStuff/testSurveyFile.json",
                            postContent);

                        // Make sure the post succeeded, and write out the response.
                        httpResponseMessage.EnsureSuccessStatusCode();
                        var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();

                        Debug.WriteLine(httpResponseBody);
                    }
                }
                else
                {
                    Debug.WriteLine("stream is NULL.");
                }

                //HttpStringContent content = await jsonFile.OpenReadAsync();
                // Post the JSON and wait for a response.
            }
            catch (Exception ex)
            {
                // Write out any exceptions.
                Debug.WriteLine(ex);
            }
        }
Exemple #37
0
        private async Task <string> ExecuteCommandLineString(string CommandString)
        {
            const string CommandLineProcesserExe         = "c:\\windows\\system32\\cmd.exe";
            const uint   CommandStringResponseBufferSize = 8192;
            string       currentDirectory = "C:\\";

            StringBuilder textOutput  = new StringBuilder((int)CommandStringResponseBufferSize);
            uint          bytesLoaded = 0;

            if (string.IsNullOrWhiteSpace(CommandString))
            {
                return("");
            }

            var commandLineText = CommandString.Trim();

            var standardOutput = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var standardError  = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var options        = new Windows.System.ProcessLauncherOptions {
                StandardOutput = standardOutput,
                StandardError  = standardError
            };

            try {
                var args   = "/C \"cd \"" + currentDirectory + "\" & " + commandLineText + "\"";
                var result = await Windows.System.ProcessLauncher.RunToCompletionAsync(CommandLineProcesserExe, args, options);

                //First write std out
                using (var outStreamRedirect = standardOutput.GetInputStreamAt(0)) {
                    using (var dataReader = new Windows.Storage.Streams.DataReader(outStreamRedirect)) {
                        while ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0)
                        {
                            textOutput.Append(dataReader.ReadString(bytesLoaded));
                        }

                        new System.Threading.ManualResetEvent(false).WaitOne(10);
                        if ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0)
                        {
                            textOutput.Append(dataReader.ReadString(bytesLoaded));
                        }
                    }
                }

                //Then write std err
                using (var errStreamRedirect = standardError.GetInputStreamAt(0)) {
                    using (var dataReader = new Windows.Storage.Streams.DataReader(errStreamRedirect)) {
                        while ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0)
                        {
                            textOutput.Append(dataReader.ReadString(bytesLoaded));
                        }

                        new System.Threading.ManualResetEvent(false).WaitOne(10);
                        if ((bytesLoaded = await dataReader.LoadAsync(CommandStringResponseBufferSize)) > 0)
                        {
                            textOutput.Append(dataReader.ReadString(bytesLoaded));
                        }
                    }
                }

                return(textOutput.ToString());
            } catch (UnauthorizedAccessException uex) {
                return("ERROR - " + uex.Message + "\n\nCmdNotEnabled");
            } catch (Exception ex) {
                return("ERROR - " + ex.Message + "\n");
            }
        }