コード例 #1
0
 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);
             };
         };
     };
 }
コード例 #2
0
ファイル: IOStream.cs プロジェクト: nghia2080/CProject
        /// <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;
            }
        }
コード例 #3
0
        private async void ReceiveImage(StreamSocket socket)
        {
            // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
            var reader = new DataReader(socket.InputStream);

            // Anzahl der Bytes abrufen, aus denen das Bild besteht
            // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
            await reader.LoadAsync(4);
            int imageSize = reader.ReadInt32();

            // Bytearray des Bildes laden
            await reader.LoadAsync((uint)imageSize);
            byte[] imageBytes = new byte[imageSize];
            reader.ReadBytes(imageBytes);
            
            // Bytearray in Stream laden und anzeigen
            using (var ms = new MemoryStream(imageBytes))
            {
                var image = new BitmapImage();
                image.SetSource(ms);

                ReceivedImage.Source = image;
            }
            Status.Text = "Bild empfangen.";

            // Ressourcen freigeben
            reader.Dispose();
            socket.Dispose();
        }
コード例 #4
0
        private async void send_file_tcp(String ipadd, int port)
        {            
            try
            {  
                _tcpclient = new StreamSocket();

                await _tcpclient.ConnectAsync(new HostName(ipadd), port.ToString());
                _datawriter = new DataWriter(_tcpclient.OutputStream);

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.GetFileAsync(this.filepath);

                IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync();
                
                _datareader = new DataReader(filestream);

                while ((_length = await _datareader.LoadAsync(63 * 1024)) != 0)
                {
                    _tosend = new byte[_length];

                    _datareader.ReadBytes(_tosend);

                    _datawriter.WriteBytes(_tosend);
                    await _datawriter.StoreAsync();
                }

                filestream.Dispose();
                _datareader.Dispose();
                _datawriter.Dispose();

                _tcpclient.Dispose();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _stopwatch.Stop();
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, ipadd);
            }            
        }
コード例 #5
0
        async private void recieveData()
        {
            StreamSocketListener listener = new StreamSocketListener();
            DataReader dr = new DataReader(newSocket.InputStream);
            dr.InputStreamOptions = InputStreamOptions.Partial;
            string msg = null;
            try
            {
                var count = await dr.LoadAsync(8192);
                if (count > 0)
                    msg = dr.ReadString(count);
            }
            catch { }
            dr.DetachStream();
            dr.Dispose();

            try
            {
                pdu2 = new PDU(msg);
                Execution temp = pdu2.Data.ToObject(typeof(Execution));
                _stepCollection.Clear();
                foreach (Step steps in temp.CurrentSequence.StepList)
                {
                    _stepCollection.Add(steps);
                }
            }

            catch (Exception e) { }
            Execution temp2 = pdu2.Data.ToObject(typeof(Execution));
            if (temp2.State == Execution.ExecutionStates.FINISHED || temp2.State == Execution.ExecutionStates.TERMINATED)
            {
                PDU pdu3 = new PDU(){
                    MessageID = (int)CommandMessageID.ResetTS,
                    MessageDescription = "Server please, reset TS",
                    MessageType = "Command",
                    Source = "Demo.Client",
                    Data = new JObject()
                };
                sendData(pdu3);
            } else { recieveData(); }
            
        }
コード例 #6
0
        private async void ReceiveImage(PeerInformation peer)
        {
            try
            {
                Status.Text = "Verbinde mit Peer...";
                StreamSocket peerSocket = await PeerFinder.ConnectAsync(peer);
                Status.Text = "Verbunden. Empfange Daten...";

                // DataReader erzeugen, um arbeiten mit Bytes zu vereinfachen
                var reader = new DataReader(peerSocket.InputStream);

                // Anzahl der Bytes abrufen, aus denen das Bild besteht
                // Anzahl = int = 4 Bytes => 4 Bytes vom Socket laden
                await reader.LoadAsync(4);
                int imageSize = reader.ReadInt32();

                // Bytearray des Bildes laden
                await reader.LoadAsync((uint)imageSize);
                byte[] imageBytes = new byte[imageSize];
                reader.ReadBytes(imageBytes);

                // Bytearray in Stream laden und anzeigen
                using (var ms = new MemoryStream(imageBytes))
                {
                    var image = new BitmapImage();
                    image.SetSource(ms);

                    ReceivedImage.Source = image;
                }
                Status.Text = "Bild empfangen.";

                // Ressourcen freigeben
                reader.Dispose();
                peerSocket.Dispose();

                // Wieder Verbindungen akzeptieren
                PeerFinder.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: " + ex.Message);
                Status.Text = "Bereit.";
            }
        }
コード例 #7
0
        public override void Run()
        {
            #if WINRT
            StorageFile file = Package.Current.InstalledLocation.GetFileAsync(_path).AsTask().Result;
            using(var raStream = file.OpenReadAsync().AsTask().Result)
            {
                byte[] blob = new byte[CHUNK_SIZE];

                while (IsRunning && raStream.CanRead)
                {
                    DataReader reader = new DataReader(raStream.GetInputStreamAt(0));
                    reader.InputStreamOptions = InputStreamOptions.Partial;
                    try
                    {
                        reader.LoadAsync((uint)blob.Length).AsTask().Wait();
                        int bytesRead = 0;
                        while (reader.UnconsumedBufferLength > 0)
                        {
                            blob[bytesRead++] = reader.ReadByte();
                        }

                        if (bytesRead > 0)
                        {
                            HandleData(blob, bytesRead);
                        }
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        reader.DetachStream();
                        reader.Dispose();
                    }

                    if (raStream.Position >= raStream.Size)
                    {
                        Terminate();
                        break;
                    }

                    Task.Delay(INTERVAL).Wait();
                }
            }
            #else
            byte [] blob = new byte[CHUNK_SIZE];

            while(IsRunning && _fileStream.CanRead)
            {
                int read = _fileStream.Read(blob, 0, CHUNK_SIZE);

                if( read > 0 )
                {
                    HandleData(blob, read);
                }

                if(_fileStream.CanSeek && _fileStream.Position >= _fileStream.Length)
                {
                    Terminate();
                    break;
                }

                Thread.Sleep(INTERVAL);
            }
            #endif
        }
コード例 #8
0
        private void DoNextRead(byte[] blob)
        {
            DataReader reader = new DataReader(_socket.InputStream);
            reader.InputStreamOptions = InputStreamOptions.Partial;

            var task = Task.Run(() =>
            {
                try
                {
                    reader.LoadAsync((uint)blob.Length).AsTask().Wait();
                    uint bytesRead = 0;
                    while(reader.UnconsumedBufferLength > 0)
                    {
                        blob[bytesRead++] = reader.ReadByte();
                    }

                    if(bytesRead > 0)
                    {
                        OnReceive(blob, bytesRead);
                    }
                }
                catch(Exception)
                {
                }
                finally
                {
                    reader.DetachStream();
                    reader.Dispose();
                }
            });
        }
コード例 #9
0
        private async void _tcp_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                scan_transfer_speed();
                
                _datareader = new DataReader(args.Socket.InputStream);
                _datareader.InputStreamOptions = InputStreamOptions.Partial;

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting);

                IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite);
                IOutputStream filewriter = filestream.GetOutputStreamAt(0);

                _datawriter = new DataWriter(filewriter);

                while (!((_length = await _datareader.LoadAsync(63 * 1024)) == 0))
                {
                    _buffer = new byte[_length];
                    _datareader.ReadBytes(_buffer);

                    _transferspeed += _length;

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

                        _transferspeed = 0;
                        _write = false;
                    }

                    _datawriter.WriteBytes(_buffer);
                    await _datawriter.StoreAsync();
                }

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

                _timer.Cancel();

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

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _tcplistener.Dispose();                

                _stopwatch.Stop();

            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, "");
            }
        }
コード例 #10
0
        public override async void send_file(String devicename, String bluid, int not)
        {
            try {
                _stopwatch.Start();

                PeerFinder.AllowBluetooth = true;
                PeerFinder.AlternateIdentities["Bluetooth:SDP"] = "{" + bluid + "}";

                var peers = await PeerFinder.FindAllPeersAsync();

                foreach (var p in peers)
                {
                    if (p.DisplayName.Equals(devicename))
                    {
                        _peer_info = p;
                        break;
                    }
                }

                _bluetooth_client = new StreamSocket();

                if (_peer_info.ServiceName.Equals(""))
                {
                    await _bluetooth_client.ConnectAsync(_peer_info.HostName, "{" + bluid + "}");
                }
                else
                {
                    await _bluetooth_client.ConnectAsync(_peer_info.HostName, _peer_info.ServiceName);
                }

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.GetFileAsync(this.filepath);

                IRandomAccessStreamWithContentType filestream = await file.OpenReadAsync();

                _length = (uint)filestream.Size;

                _ibuffer = new Windows.Storage.Streams.Buffer(_length);

                _datareader = new DataReader(filestream);
                await _datareader.LoadAsync(_length);
                _ibuffer = _datareader.ReadBuffer(_length);

                _datawriter = new DataWriter(_bluetooth_client.OutputStream);
                _datawriter.WriteBuffer(_ibuffer);
                await _datawriter.StoreAsync();

                filestream.Dispose();
                _datareader.Dispose();
                _datawriter.Dispose();
                               
                _datareader = new DataReader(_bluetooth_client.InputStream);
                _datareader.InputStreamOptions = InputStreamOptions.Partial;

                scan_received_acks();

                while (true)
                {
                    uint count = await _datareader.LoadAsync(4);
                    byte[] ack = new byte[count];

                    _datareader.ReadBytes(ack);

                    _counter_all_acks += BitConverter.ToInt32(ack, 0);

                    if ((uint)_counter_all_acks == _length) break;
                }

                _datareader.Dispose();
                _bluetooth_client.Dispose();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _ack_timer.Cancel();
                _stopwatch.Stop();
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, devicename);
            }
        }
コード例 #11
0
ファイル: _DataWriter.xaml.cs プロジェクト: forehalo/UWP-dev
        private async void OnRead(Object sender, RoutedEventArgs e)
        {
            StorageFolder local = ApplicationData.Current.LocalFolder;

            StorageFile file = await local.GetFileAsync("demo.dat");
            if(file != null)
            {
                string strres = "读到的内容:\n";
                using(IRandomAccessStream stream = await file.OpenReadAsync())
                {
                    DataReader dr = new DataReader(stream);
                    dr.UnicodeEncoding = UnicodeEncoding.Utf8;
                    await dr.LoadAsync((uint)stream.Size);
                    bool b = dr.ReadBoolean();
                    strres += b.ToString() + "\n";
                    DateTimeOffset dt = dr.ReadDateTime();
                    strres += dt.ToString("yyyy-M-d") + "\n";
                    uint len = dr.ReadUInt32();
                    if(len > 0)
                    {
                        strres += dr.ReadString(len);
                    }
                    dr.Dispose();
                }
                tbResult.Text = strres;
            }
        }
コード例 #12
0
        public void Load(string filename)
        {

#if !WINDOWS_PHONE // iOS and Android

            string docsPath = Environment.GetFolderPath(
                                    Environment.SpecialFolder.Personal);
            string filepath = Path.Combine(docsPath, filename);
            string text = File.ReadAllText(filepath);

            // Break string into Title and Text.
            int index = text.IndexOf('\n');
            this.Title = text.Substring(0, index);
            this.Text = text.Substring(index + 1);

#else // Windows Phone

            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();

                        // Break string into Title and Text.
                        int index = text.IndexOf('\n');
                        this.Title = text.Substring(0, index);
                        this.Text = text.Substring(index + 1);
                    };
                };
            };
     
#endif

        }
コード例 #13
0
 async void PeerFinder_StartReader(DataReader socketReader)
 {
     try
     {
         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);
                 this.NotifyUser("Got message: " + message, NotifyType.PeerMessage);
                 PeerFinder_StartReader(socketReader); // Start another reader
             }
             else
             {
                 SocketError("The remote side closed the socket");
                 socketReader.Dispose();
             }
         }
         else
         {
             SocketError("The remote side closed the socket");
             socketReader.Dispose();
         }
     }
     catch (Exception e)
     {
         if (!_socketClosed)
         {
             SocketError("Reading from socket failed: " + e.Message);
         }
         socketReader.Dispose();
     }
 }
コード例 #14
0
        async private void recieveData()
        {
            StreamSocketListener listener = new StreamSocketListener();
            DataReader dr = new DataReader(socket.InputStream);
            dr.InputStreamOptions = InputStreamOptions.Partial;
            string msg = null;
            var count = await dr.LoadAsync(4096);

            if (count > 0)
                msg = dr.ReadString(count);
            recievedMessage.Text = msg;

            dr.DetachStream();
            dr.Dispose();

            try
            {
                PDU pdu2 = new PDU(msg);
                Procedure temp = pdu2.Data.ToObject(typeof(Procedure));
                _kakecollection.Add(new kakeclass { Name = temp.Name, Description = temp.Description, Date = temp.Date });
            }
            catch (Exception e) { recievedMessage.Text = "Failed to cast incomming message to usable type: PDU"; }

            try
            {
                listener.ConnectionReceived += listener_ConnectionReceived;
                await listener.BindServiceNameAsync(socketString);
                

            }
            catch (Exception e) { recievedMessage.Text = e.ToString(); }

        }
コード例 #15
0
        async void StartReceiveData(DataReader socketReader)
        {
            try
            {
                uint bytesRead = await socketReader.LoadAsync(sizeof(uint));
                if (bytesRead > 0)
                {
                    uint strLength = (uint)socketReader.ReadUInt32();
                    bytesRead = await socketReader.LoadAsync(strLength);
                    if (bytesRead > 0)
                    {
                        byte[] bytesIn = new byte[bytesRead];

                        Debug.WriteLine("ReadBytes");
                        socketReader.ReadBytes(bytesIn);
                        Debug.WriteLine("ReadBytes End");

                       
                        if (DataReceived != null)
                        {
                            DataReceivedEventArgs args = new DataReceivedEventArgs();
                            args.Bytes = bytesIn;
                            DataReceived(this, args);
                        }

                        StartReceiveData(socketReader); // Start another reader
                    }
                    else
                    {
                        SocketError("The remote side closed the socket");
                        socketReader.Dispose();
                        UpdateConnectionStatus(ConnectionStatus.Disconnected);
                    }
                }
                else
                {
                    SocketError("The remote side closed the socket");
                    socketReader.Dispose();
                    UpdateConnectionStatus(ConnectionStatus.Disconnected);
                }
            }
            catch (Exception e)
            {
                if (!_socketClosed)
                {
                    SocketError("Reading from socket failed: " + e.Message);
                }
                socketReader.Dispose();
            }
        }
コード例 #16
0
ファイル: SocketClass.cs プロジェクト: Chrislaos/MetroSocket2
        async private void recieveData()
        {
            StreamSocketListener listener = new StreamSocketListener();
            DataReader dr = new DataReader(socket.InputStream);
            dr.InputStreamOptions = InputStreamOptions.Partial;
            string msg = null;
            var count = await dr.LoadAsync(8192);

            if (count > 0)
                msg = dr.ReadString(count);

            dr.DetachStream();
            dr.Dispose();

            try
            {
                pdu2 = new PDU(msg);
                ListOfProcedures temp = pdu2.Data.ToObject(typeof(ListOfProcedures));
                foreach (Procedure pro in temp.ProcedureList)
                {
                    _kakecollection.Add(pro);
                }
            }
            catch (Exception e) { recievedMessage.Text = "Failed to cast incomming message to usable type: PDU"; }
        }
コード例 #17
0
 private async Task<FileImportResult> DoImportFromCSV()
 {
     string contents = "";
     FileImportResult res;
     try
     {
         using (IRandomAccessStream stream = await sf.OpenAsync(FileAccessMode.Read))
         {
             using (DataReader textReader = new DataReader(stream))
             {
                 uint textLength = (uint)stream.Size;
                 await textReader.LoadAsync(textLength);
                 contents = textReader.ReadString(textLength);
                 textReader.Dispose();
             }
             stream.Dispose();
         }
         res = fileController.ImportFromCSV(contents, contactMode);
         return res;
     }
     catch(Exception importException)
     {
         //Access Denied!
         System.Diagnostics.Debug.WriteLine(importException.Message);
         res = new FileImportResult();
         res.errorCode = FileImExportController.CODE_FILE_IN_USE;
         return res;
     }
                     
 }