Beispiel #1
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();
 }
Beispiel #2
0
		private async Task WriteToOutputStreamAsync(byte[] bytes)
		{

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

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

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

				_writer.DetachStream();
				_writer.Dispose();
			}
			catch (Exception exception)
			{
				// If this is an unknown status it means that the error if fatal and retry will likely fail.
				if (global::Windows.Networking.Sockets.SocketError.GetStatus(exception.HResult) == global::Windows.Networking.Sockets.SocketErrorStatus.Unknown)
				{
					// TODO abort any retry attempts on Unity side
					throw;
				}
			}
		}
Beispiel #3
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();
        }
 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();
             };
         };
     };
 }
        private async Task Download(string url,StorageFile file,bool cover)
        {
            var http = new HttpClient();
            byte[] response = { };
            string betterUrl = url;
            if(cover)
            {
                var pos = betterUrl.IndexOf(".jpg");
                if (pos != -1)
                    betterUrl = betterUrl.Insert(pos, "l");
            }

            //get bytes
            try
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(betterUrl));
            }
            catch (Exception)
            {
                await Task.Run(async () => response = await http.GetByteArrayAsync(url));
            }

            var fs = await file.OpenStreamForWriteAsync(); //get stream
            var writer = new DataWriter(fs.AsOutputStream());

            writer.WriteBytes(response); //write
            await writer.StoreAsync();
            await writer.FlushAsync();

            writer.Dispose();
        }
 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();
     }
 }
 private async void SendButton_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         DataWriter writer = new DataWriter(connectedSocket.OutputStream);
         writer.WriteBytes(Encoding.UTF8.GetBytes(SendMessageTextBox.Text));
         await writer.StoreAsync();
         writer.DetachStream();
         writer.Dispose();
     }
     catch(Exception exception)
     {
         rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);
     }
 }
Beispiel #8
0
        private async Task<IRandomAccessStream> ConvertToRandomAccessStream(byte[] bytes)
        {
            var randomAccessStream = new InMemoryRandomAccessStream();
            using (var writer = new DataWriter(randomAccessStream))
            {
                writer.WriteBytes(bytes);
                await writer.StoreAsync();
                await writer.FlushAsync();
                writer.DetachStream();
                writer.Dispose();
            }
            randomAccessStream.Seek(0);

            return randomAccessStream;
        }
        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);
            }            
        }
        private async void TransferImage(StreamSocket socket)
        {
            var writer = new DataWriter(socket.OutputStream);

            UpdateStatus("Übertrage Bild...");

            // Anzahl der zu übertragenden Bytes übertragen
            writer.WriteInt32(App.ImageBytesToTransfer.Length);
            await writer.StoreAsync();

            // Image-Bytes übertragen
            writer.WriteBytes(App.ImageBytesToTransfer);
            await writer.StoreAsync();
            await writer.FlushAsync();

            // Ressourcen freigeben
            writer.Dispose();
            UpdateStatus("Übertragung abgeschlossen");
        }
        public void Save(string filename)
        {
            string text = this.Title + "\n" + this.Text;

#if !WINDOWS_PHONE // iOS and Android

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

#else // Windows Phone

            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();
                    };
                };
            };
     
#endif
        }
Beispiel #12
0
		static async void multicastSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs eventArguments) {
			try {
				HostName remoteHostAddress = eventArguments.RemoteAddress;
				uint len = eventArguments.GetDataReader().UnconsumedBufferLength;
				string message = eventArguments.GetDataReader().ReadString(len).Trim();
				int p = message.IndexOf(':');
				if (p != -1) {
					string serverLogToken = message.Substring(0, p);
					int port = Int32.Parse(message.Substring(p + 1));

					if (serverLogToken == logToken && port > 0 && port < 65535) {
						Debug.WriteLine("[LOGGER] Found a Titanium log server: " + remoteHostAddress.DisplayName + ":" + port);

						try {
							tcpSocket = new StreamSocket();
							tcpSocket.Control.KeepAlive = true;
							await tcpSocket.ConnectAsync(remoteHostAddress, port.ToString());
							tcpWriter = new DataWriter(tcpSocket.OutputStream);

							// shutdown the multicast socket and start the tcp connection
							multicastSocket.Dispose();
						} catch {
							if (tcpWriter != null) {
								tcpWriter.Dispose();
								tcpWriter = null;
							}
							if (tcpSocket != null) {
								tcpSocket.Dispose();
								tcpSocket = null;
							}
						}
					}
				}
			} catch (Exception ex) {
				if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) {
					throw;
				}
				Debug.WriteLine(ex.ToString());
			}
		}
        private async void TransferPicture(StreamSocket socket)
        {
            // DataWriter erzeugen, um Byte-Umwandlung erledigen zu lassen...
            var writer = new DataWriter(socket.OutputStream);

            // Anzahl der zu übertragenden Bytes übertragen
            writer.WriteInt32(App.PhotoBytesToShare.Length);
            await writer.StoreAsync();

            // Image-Bytes übertragen
            writer.WriteBytes(App.PhotoBytesToShare);
            await writer.StoreAsync();
            await writer.FlushAsync();
            UpdateStatus("Übertragung abgeschlossen.");

            // Ressourcen freigeben
            writer.Dispose();
            socket.Dispose();

            // Beenden der Annahme von Client-Verbindungen
            _listener.Dispose();
        }
Beispiel #14
0
 public async void sendMail(string strSendTo,string strContent , Boolean hasPicture)
 {
     HostName hostName = new HostName(hostIP);
     StreamSocket socket = new StreamSocket();
     List<string[]> storeList = new List<string[]>();
     try
     {
         await socket.ConnectAsync(hostName, port);
     }
     catch (Exception exception)
     {
         if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
         {
             throw;
         }
     }
     StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("Temp");
     StorageFile pic = await folder.GetFileAsync("MyPainter.png");
     IBuffer buffer = await FileIO.ReadBufferAsync(pic);
     DataWriter writer = new DataWriter(socket.OutputStream);
     writer.WriteUInt32(writer.MeasureString(strSendTo));
     writer.WriteString(strSendTo);
     writer.WriteUInt32(writer.MeasureString(strContent));
     writer.WriteString(strContent);
     if (hasPicture)
     {
         writer.WriteUInt32((uint)buffer.Length);
         writer.WriteBuffer(buffer);
     }
     else
     {
         writer.WriteUInt32(0);
         writer.WriteString("");
     }
     await writer.StoreAsync();
     writer.DetachStream();
     writer.Dispose();
     socket.Dispose();
 }
Beispiel #15
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);
        }
Beispiel #16
0
        private async void DownloadUserAvatar(string url, string userid)
        {
            try
            {
                var hc = new HttpClient();
                var response = await hc.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var bitmapByte = await response.Content.ReadAsByteArrayAsync();

                var userFile =
                    await
                    AntaresBaseFolder.Instance.RoamingFolder.CreateFileAsync("Cache\\ProfilePic.jpg",
                                                                             CreationCollisionOption.ReplaceExisting);
                var writeStream = await userFile.OpenAsync(FileAccessMode.ReadWrite);
                var outputStream = writeStream.GetOutputStreamAt(0);
                var dataWriter = new DataWriter(outputStream);

                dataWriter.WriteBytes(bitmapByte);

                await dataWriter.StoreAsync();
                await outputStream.FlushAsync();

                writeStream.Dispose();
                outputStream.Dispose();
                dataWriter.Dispose();

                var userPic = new BitmapImage();
                userPic.SetSource(await userFile.OpenAsync(FileAccessMode.Read));
                UserPic.Source = userPic;
            }
            catch
            {
            }
        }
        private async void TransferPicture_Click(object sender, RoutedEventArgs e)
        {
            var selectedPeer = PeersList.SelectedItem as PeerInformation;
            if (selectedPeer == null)
            {
                MessageBox.Show("Bitte Emfängergerät wählen");
                return;
            }

            try
            {
                Status.Text = "Verbinde mit Peer...";
                var peerSocket = await PeerFinder.ConnectAsync(selectedPeer);
                var writer = new DataWriter(peerSocket.OutputStream);

                Status.Text = "Verbunden. Übertrage Bild...";

                // Anzahl der zu übertragenden Bytes übertragen
                writer.WriteInt32(App.ImageBytesToTransfer.Length);
                await writer.StoreAsync();

                // Image-Bytes übertragen
                writer.WriteBytes(App.ImageBytesToTransfer);
                await writer.StoreAsync();
                await writer.FlushAsync();

                // Ressourcen freigeben
                writer.Dispose();
                peerSocket.Dispose();
                Status.Text = "Übertragung abgeschlossen";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: " + ex.Message);
                Status.Text = "Bereit.";
            }
        }
		protected override async void SendAsync(NetworkingStream stream)
		{
			try
			{
				DataWriter writer = new DataWriter(socket.OutputStream);
				//uint length = writer.MeasureString(message);
				writer.WriteBytes(stream.Bytes.byteArr);
				// Try to store (send?) synchronously
				await writer.StoreAsync();

				OnDataSent(stream);

				writer.DetachStream();
				writer.Dispose();
			}
			catch (Exception e)
			{
				// If this is an unknown status, 
				// it means that the error is fatal and retry will likely fail.
				if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown)
					throw;
				
				ErrorDisconnect(e.Message);
			}
		}
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            this.serviceDeferral = taskInstance.GetDeferral();
            try {
                var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
                if (triggerDetails != null && triggerDetails.Name == "CortanaCommandService")
                {

                    voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                    var voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();
                    Debug.WriteLine(voiceCommand.CommandName);

                    MainViewModel viewModel = new MainViewModel();
                    var vm = await DataLoadAsync();
                    if (vm != null)
                    {
                        viewModel = vm;
                    }

                    var cols = voiceCommand.CommandName.Split('_');
                    var commandName = cols[0];
                    var stateName = cols[1];

                    var commandViewModel = viewModel.CommandList.First(q => q.Name == commandName);
                    
                    commandViewModel.CurrentStateNum++;
                    var stateViewModel = commandViewModel.StateList.ElementAt(commandViewModel.CurrentStateNum - 1);
                    if (commandViewModel.CurrentStateNum>=commandViewModel.StateList.Count)
                    {
                        commandViewModel.CurrentStateNum = 0;
                    }

                    if(stateViewModel is SuccessStateViewModel)
                    {
                        var state = stateViewModel as SuccessStateViewModel;
                        if (string.IsNullOrEmpty(state.Utterance))
                        {
                            state.Utterance = "";
                        }
                        var message = new VoiceCommandUserMessage();
                        message.SpokenMessage = state.Utterance;
                        message.DisplayMessage = state.Utterance;
                        var response = VoiceCommandResponse.CreateResponse(message);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else if(stateViewModel is ScriptStateViewModel)
                    {
                        var state = stateViewModel as ScriptStateViewModel;
                        if (!string.IsNullOrEmpty(state.Script))
                        {
                            try {
                                ConnectionData connectionData = new ConnectionData();
                                connectionData.AcceptPass = viewModel.PassCode;
                                connectionData.Script = state.Script.Replace("\n", ";").Replace("\r", "").Replace("\t", "");
                                string json = JsonConvert.SerializeObject(connectionData);
                                var byteData = Encoding.UTF8.GetBytes(json);
                                StreamSocket socket = new StreamSocket();

                                await socket.ConnectAsync(new HostName("127.0.0.1"), SettingManager.ServerPort);
                                var writer = new DataWriter(socket.OutputStream);
                                writer.WriteBytes(byteData);
                                await writer.StoreAsync();
                                await writer.FlushAsync();
                                writer.Dispose();
                                socket.Dispose();
                                
                            }
                            catch (Exception)
                            {
                                var errorMsg = new VoiceCommandUserMessage();
                                string msg = "スクリプトの実行を試みましたがサーバーが起動してませんでした";
                                errorMsg.SpokenMessage = msg;
                                errorMsg.DisplayMessage = msg;
                                var errorResponse = VoiceCommandResponse.CreateResponse(errorMsg);
                                await voiceServiceConnection.ReportFailureAsync(errorResponse);
                                return;
                            }
                        }


                        if (string.IsNullOrEmpty(state.Utterance))
                        {
                            state.Utterance = "";
                        }
                        var message = new VoiceCommandUserMessage();
                        message.SpokenMessage = state.Utterance;
                        message.DisplayMessage = state.Utterance;
                        var response = VoiceCommandResponse.CreateResponse(message);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }

                    await DataSaveAsync(viewModel);
                }

            }catch(Exception e)
            {
                var message = new VoiceCommandUserMessage();
                message.SpokenMessage = "何かしらのエラーが起きました";
                message.DisplayMessage = e.Message;
                var response = VoiceCommandResponse.CreateResponse(message);
                await voiceServiceConnection.ReportSuccessAsync(response);

                var toast = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText01);
                ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toast));
            }
            

            this.serviceDeferral.Complete();
        }
 private async void LoadImageFromUriAsync(Uri url)
 {
     HttpClient httpClient = new HttpClient();
     HttpResponseMessage result = httpClient.GetAsync(url).Result;
     byte[] array = await result.Content.ReadAsByteArrayAsync();
     InMemoryRandomAccessStream inMemoryRandomAccessStream = new InMemoryRandomAccessStream();
     DataWriter dataWriter = new DataWriter(inMemoryRandomAccessStream.GetOutputStreamAt(0uL));
     dataWriter.WriteBytes(array);
     await dataWriter.StoreAsync();
     BitmapImage bitmapImage = new BitmapImage();
     bitmapImage.SetSource(inMemoryRandomAccessStream);
     this._image = bitmapImage;
     httpClient.Dispose();
     result.Dispose();
     array = null;
     inMemoryRandomAccessStream.Dispose();
     dataWriter.Dispose();
     bitmapImage = null;
 }
        public override async void receive_file(String devicename, String add, int not)
        {
            try
            {
                _httpurl = new Uri(add);
                _httpprogress = new Progress<HttpProgress>(ProgressHandler);

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

                _httpclient = new HttpClient(filter);

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

                scan_network_speed();
                _stopwatch.Start();

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

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

                _timer.Cancel();

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

                _stopwatch.Stop();

                _buffer = await _httpresponse.Content.ReadAsBufferAsync();

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

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

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

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, "");
            }            
        }
        private void DoPing()
        {
            byte[] reqPacket = { 0x10 };

            //Task.Run(()=>
            //    {
            DataWriter writer = new DataWriter(_socket.OutputStream);
            writer.WriteBytes(reqPacket);
            writer.StoreAsync().AsTask().Wait();
            writer.DetachStream();
            writer.Dispose();
            //}
        }
 private async Task Write(string value)
 {
     var writer = new DataWriter(device.OutputStream);
     writer.WriteString(value);
     await writer.StoreAsync();
     writer.DetachStream();
     writer.Dispose();
 }
        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, "");
            }
        }
        // функция для отправки состояния кнопки на сервер
        private async void sendkey(string key)
        {
            if (!connected)
            {
                StatusText.Text = "необходимо подключение";
                return;
            }

            //Int32 len = 0; // Gets the UTF-8 string length.

            try
            {

                StatusText.Text = "попытка отправки данных ...";

                // add a newline to the text to send
               
                DataWriter writer = new DataWriter(clientSocket.OutputStream);
                //Int32 len = writer.MeasureString(sendData); // Gets the UTF-8 string length.
                writer.WriteString(key);
                // Call StoreAsync method to store the data to a backing stream
                await writer.StoreAsync();

                StatusText.Text = "отправка успешна" + Environment.NewLine;

                // detach the stream and close it
                //попробуем не закрывать сокет
                writer.DetachStream();
                writer.Dispose();

            }
            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;
                }

                StatusText.Text = "Не удалось оправить данные ";// +exception.Message;
                // Could retry the connection, but for this simple example
                // just close the socket.

                closing = true;
                clientSocket.Dispose();
                clientSocket = null;
                connected = false;

            }

           
        }
Beispiel #26
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sData"></param>
        private async void SendMsg(byte[] sData)
        {
            if (!connected)
            {
                StatusText.Text = "Must be connected to send!";
                return;
            }

            try
            {
                //StatusText.Text = "Trying to send data ...";

                byte[] sendData = ConvSendMsg(sData, 0);
                DataWriter writer = new DataWriter(clientSocket.OutputStream);
                //把数据写入到发送流
                writer.WriteBytes(sendData);
                //异步发送
                await writer.StoreAsync();

                //显示发送的消息内容
                StatusText.Text = System.Text.UnicodeEncoding.UTF8.GetString(sendData, 40, sData.Length) + " was sent";

                // detach the stream and close it
                writer.DetachStream();
                writer.Dispose();

            }
            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;
                }
                StatusText.Text = "Send data or receive failed with error: " + exception.Message;
                // Could retry the connection, but for this simple example
                // just close the socket.
                closing = true;
                clientSocket.Dispose();
                clientSocket = null;
                connected = false;
            }
        }
        public async Task UsingDataWriter()
        {
            var inMem = new InMemoryRandomAccessStream();

            var datawriter = new DataWriter(inMem);
            var starterBytes = CryptographicBuffer.GenerateRandom(32).AsBytes();
            var mStream = CryptographicBuffer.GenerateRandom(1024 * 1024).AsBytes();

            MemoryStream outStream = new System.IO.MemoryStream();
            var tinyStream = ConfigureStream(outStream, PwCompressionAlgorithm.GZip, true);
            await tinyStream.WriteAsync(starterBytes, 0, starterBytes.Length);
            await tinyStream.WriteAsync(mStream, 0, mStream.Length);
            tinyStream.Dispose();
            byte[] bb = outStream.ToArray();
            var source = bb.AsBuffer();
            var aesKey = CryptographicBuffer.GenerateRandom(32);
            var iv = CryptographicBuffer.GenerateRandom(16);
            var encrypted = EncryptDatabase(source, aesKey, iv);

            CollectionAssert.AreNotEqual(mStream, encrypted.AsBytes());

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

            datawriter.DetachStream();
            datawriter.Dispose();
             var i = inMem.GetInputStreamAt(0);
             var datareader = new DataReader(i);
             datareader.ByteOrder = ByteOrder.LittleEndian;
            await datareader.LoadAsync((uint)inMem.Size);
             var fromStrea = datareader.ReadBuffer(datareader.UnconsumedBufferLength);

             var decryped = DecryptDatabase(fromStrea, aesKey, iv);

             Stream bigStream = ConfigureStream(new MemoryStream(decryped.AsBytes()), PwCompressionAlgorithm.GZip, false);
             System.IO.MemoryStream bigStreamOut = new System.IO.MemoryStream();
             bigStream.CopyTo(bigStreamOut);

            var buffer1 = CryptographicBuffer.CreateFromByteArray(bigStreamOut.ToArray());
            var reader = DataReader.FromBuffer(buffer1);
            var x = reader.ReadBuffer(32).AsBytes();
            CollectionAssert.AreEqual(starterBytes, x);
        }
        public void WriteAsync(SocketEventArgs args)
        {
            if (_socket == null)
            {
                args.SocketException = new InvalidOperationException("No server connection has been established.");
                args.Complete();
                return;
            }

            try
            {
                // Write data to the socket
                var writer = new DataWriter(_socket.OutputStream);
                writer.WriteBytes(args.MessageToSend.Serialize());
                writer.StoreAsync().Completed += (info, status) =>
                {
                    writer.DetachStream();
                    writer.Dispose();

                    if (args.MessageToSend is IMqttIdMessage)
                    {
                        var msgWithId = args.MessageToSend as IMqttIdMessage;
                        _logger.LogMessage("Socket", LogLevel.Verbose, string.Format("Sent message type '{0}', ID={1} to server.", msgWithId.MessageType, msgWithId.MessageId));
                    }
                    else
                    {
                        _logger.LogMessage("Socket", LogLevel.Verbose, string.Format("Sent message type '{0}' to server.", args.MessageToSend.MessageType));
                    }

                    if (info.Status == AsyncStatus.Error)
                    {
                        args.SocketException = info.ErrorCode;
                    }
                    args.Complete();
                };
            }
            catch (Exception ex)
            {
                args.SocketException = ex;
                args.Complete();
            }
        }
Beispiel #29
0
        public static async Task DownloadProfileImg()
        {
            if (!Credentials.Authenticated)
                return;
            try
            {
                var folder = ApplicationData.Current.LocalFolder;
                var thumb = await folder.CreateFileAsync("UserImg.png", CreationCollisionOption.ReplaceExisting);

                var http = new HttpClient();
                byte[] response = { };
                switch (Settings.SelectedApiType)
                {
                    case ApiType.Mal:
                        await Task.Run(async () => response = await http.GetByteArrayAsync($"https://myanimelist.cdn-dena.com/images/userimages/{Credentials.Id}.jpg"));
                        break;
                    case ApiType.Hummingbird:
                        var avatarLink = await new ProfileQuery().GetHummingBirdAvatarUrl();
                        await Task.Run(async () => response = await http.GetByteArrayAsync(avatarLink));
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                //get bytes

                var fs = await thumb.OpenStreamForWriteAsync(); //get stream
                var writer = new DataWriter(fs.AsOutputStream());

                writer.WriteBytes(response); //write
                await writer.StoreAsync();
                await writer.FlushAsync();

                writer.Dispose();

                await ViewModelLocator.GeneralHamburger.UpdateProfileImg(false);
            }
            catch (Exception)
            {
                //
            }
            await Task.Delay(2000);
            await ViewModelLocator.GeneralHamburger.UpdateProfileImg(false);
        }
Beispiel #30
0
        private async Task ConnectClientInternal()
        {
            if (_socket != null)
            {
                throw new Exception("connect() is already called");
            }

            await Task.Factory.StartNew(async () =>
                  {

                      try
                      {
                          int port = (_uri.Port != -1) ? _uri.Port : (_uri.Scheme.Equals("wss") ? 443 : 80);
                          string path = (_uri.AbsolutePath != null) ? _uri.AbsolutePath : "/";
                          if (_uri.Query != null)
                          {
                              path += "?" + _uri.Query;
                          }
                          string originScheme = _uri.Scheme.Equals("wss") ? "https" : "http";
                          Uri origin = new Uri(originScheme + "://" + _uri.Host);
                          // To fix: get Origin from extraHeaders if set there.
                          this._socket = new InternalSocket();
                          await this._socket.ConnectAsync(_uri.Host, port);
                          if (_uri.Scheme.Equals("wss"))
                          {
                              await this._socket.UpgradeToSslAsync(_uri.Host);
                          }
                          string key = CreateSecKey();
                          DataWriter writer = new DataWriter(_socket.OutputStream);
                          writer.WriteString("GET " + path + " HTTP/1.1\r\n");
                          writer.WriteString("Upgrade: websocket\r\n");
                          writer.WriteString("Connection: Upgrade\r\n");
                          writer.WriteString("Host: " + _uri.Host + "\r\n");
                          writer.WriteString("Origin: " + origin.ToString() + "\r\n");
                          writer.WriteString("Sec-WebSocket-Key: " + key + "\r\n");
                          writer.WriteString("Sec-WebSocket-Version: 13\r\n");

                          if (_extraRequestHeaders != null)
                          {
                              foreach (Http.Header header in _extraRequestHeaders)
                              {
                                  writer.WriteString(header.ToString() + "\r\n");
                              }
                          }
                          writer.WriteString("\r\n");
                          await writer.StoreAsync();  //异步发送数据
                          writer.DetachStream();  //分离
                          writer.Dispose();  //结束writer
                          DataReader reader = new DataReader(_socket.InputStream);
                          reader.ByteOrder = ByteOrder.LittleEndian;
                          //// Read HTTP response status line.
                          var startLine = await ReadLine(reader);
                          if (startLine == null)
                          {
                              throw new Exception("Received no reply from server.");
                          }
                          Http.StatusLine statusLine = new Http.StatusLine(startLine);
                          int statusCode = statusLine.StatusCode;
                          if (statusCode != 101)
                          {
                              throw new Exception("wrong HTTP response code: " + statusCode);
                          }

                          // Read HTTP response headers.
                          string line;
                          while ((line = await ReadLine(reader)) != null && line.Length > 0)
                          {
                              Http.Header header = new Http.Header(line);
                              Debug.WriteLine(line);

                              if (header.HeaderName.Equals("Sec-WebSocket-Accept", StringComparison.OrdinalIgnoreCase))
                              {
                                  string receivedAccept = header.HeaderValue;
                                  string shouldBeAccept = CreateAccept(key);
                                  if (!receivedAccept.Equals(shouldBeAccept))
                                      throw new Exception("Wrong Sec-WebSocket-Accept: " + receivedAccept + " should be: " + shouldBeAccept);
                              }
                              if (_serverResponseHeaders == null)
                              {
                                  _serverResponseHeaders = new List<Http.Header>();
                              }
                              _serverResponseHeaders.Add(header);

                          }
                          if (this.Opened != null)
                          {
                              this.Opened(this, EventArgs.Empty);
                          }
                          //Upgrade: websocket
                          //Connection: Upgrade
                          //Sec-WebSocket-Accept: 1xY289lHcEMbLpEBgOYRBBL9N9c=
                          //Sec-WebSocket-Protocol: chat
                          //Content-Type: application/octet-stream
                          //Seq-Id: 667035124
                          // Read & process frame
                          while (true)
                          {
                              FrameParser.Frame frame = await FrameParser.ReadFrame(reader);

                              if (frame != null)
                              {
                                  await ProcessIncomingFrame(frame);
                              }

                          }
                      }
                      catch (IOException ex)
                      {
                          if (this.Closed != null)
                          {
                              this.Closed(this, new WebSocketClosedEventArgs(0, "EOF"));
                          }
                      }
                      catch (Exception ex)
                      {
                          if (this.Closed != null)
                          {
                              this.Closed(this, new WebSocketClosedEventArgs(0, "Exception"));
                          }
                      }
                      finally
                      {
                          Disconnect();
                      }

                  });
        }
Beispiel #31
0
        private async Task<Image> DataToImage(Tile tile)
        {
            BitmapImage bitmapImage = new BitmapImage();
            if (tile.IsSuccessd)
            {
                InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
                DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
                writer.WriteBytes(tile.MapImage.Data);
                await writer.StoreAsync();

                bitmapImage.SetSource(randomAccessStream);
                writer.Dispose();
                randomAccessStream.Dispose();
            }
            Image image = new Image()
            {
                Opacity = 1.0,
                Tag = tile,
                IsHitTestVisible = false,
                Name = tile.TileKey,
                Stretch = Stretch.Fill,
                Source = bitmapImage
            };

            double resolution = tile.Resolution;
            LayerContainer.SetBounds(image, GetTilesBounds(tile.Column, tile.Row, tile.Resolution));//计算该image的范围
            return image;
        }
Beispiel #32
0
        private async Task SendFrame(byte[] frame)
        {
            await Task.Factory.StartNew(async () =>
                  {
                      try
                      {
                          var outputStream = _socket.OutputStream;
                          DataWriter writer = new DataWriter(outputStream);
                          writer.WriteBytes(frame);
                          await writer.StoreAsync();  //异步发送数据
                          writer.DetachStream();  //分离
                          writer.Dispose();  //结束writer
                      }
                      catch (IOException ex)
                      {
                          if (this.OnError != null)
                          {
                              this.OnError(this, ex);
                          }
                      }

                  });
        }