protected override async void OnLaunched(LaunchActivatedEventArgs e) { //is the application being launched by the jumplist? //if so then the tileid is set to app and there would be arguments supplied. var jumpList = e.TileId == "App" && !string.IsNullOrEmpty(e.Arguments); if (jumpList) { try { //if it is a jumplist item, then you can locate the file by the path provided in the arguments. var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(e.Arguments); if (RootFrame.Content == null) { // then navigate to the page passing the file. RootFrame.Navigate(typeof(MyNotepad.Views.MainPage), file); } else { // if we've already navigated to the file, because the content is not null, then no need in // navigating again. FileReceived?.Invoke(this, file); } } catch (Exception) { throw; } } else { RootFrame.Navigate(typeof(MyNotepad.Views.MainPage), e.Arguments); } Window.Current.Activate(); }
private void DecoderOnMessageDecoded(object sender, MessageDecodedEventArgs eventArgs) { if (eventArgs.Message != null) { try { if (eventArgs.Message is DataFrame dataFrame && dataFrame.Items != null) { DataPointValue[] files = dataFrame.Items.Where(i => i is OPCUAFile) .ToArray(); foreach (OPCUAFile file in files) { dataFrame.Items.Remove(file); FileReceived?.Invoke(this, new FileReceivedEventArgs(file, eventArgs.Topic, dataFrame.NetworkMessageHeader.PublisherID.Value)); } if (dataFrame.Items.Count > 0) { MessageReceived?.Invoke(this, eventArgs); } } else if (eventArgs.Message is MetaFrame metaFrame) { MetaMessageReceived?.Invoke(this, eventArgs); } else { UnknownMessageReceived?.Invoke(this, eventArgs); } }
private void dataGridView1_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { var files = (string[])e.Data.GetData(DataFormats.FileDrop); try { toolStripProgressBar1.Visible = true; toolStripProgressBar1.Value = 0; toolStripProgressBar1.Maximum = files.Length; foreach (var file in files) { tslFileCount.Text = System.IO.Path.GetFileName(file); toolStripProgressBar1.Value++; var item = FileReceived?.Invoke(file); // do your upload or local copy here if (item != null) { Add(item); } } } catch (Exception exc) { MessageBox.Show(exc.Message); } finally { UpdateStatusBar(); toolStripProgressBar1.Visible = false; } } }
private void ListenData(Connection connection) { while (true) { try { var data = connection.TransferProtocol.Read(); if (data.Type == TrasnsferDataType.Command) { _logger.LogMessage("Command received from " + connection.Id + " " + connection.Name); CommandReceived?.Invoke(connection.Id, (CommandTrasnsferData)data); } else if (data.Type == TrasnsferDataType.DataObject) { _logger.LogMessage("Data received from " + connection.Id + " " + connection.Name); DataReceived?.Invoke(connection.Id, (ObjectTrasnsferData)data); } else { _logger.LogMessage("File received from " + connection.Id + " " + connection.Name); FileReceived?.Invoke(connection.Id, (FileTransferData)data); } } catch (Exception ex) { _logger.LogError("Disconected: " + connection.Id + " " + connection.Name + " Error connection: " + ex.Message); Disconect(connection); return; } } }
private async void _scheduler_Trigger(object sender, MessageEventArgs e) { if (!_running || _executing) { return; } _executing = true; try { var files = await _client.ReceiveFilesAsync(_path, _fileMask); if (files != null) { foreach (var file in files.Where(x => !x.IsError)) { FileReceived?.Invoke(this, new ReceiveFileEventArgs(file)); } } } catch (Exception ex) { _logger?.Error($"Reading files from path '{_path}' using filemask '{_fileMask}' was unsuccessful.", ex); } _executing = false; }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { var jumpList = e.TileId == "App" && !string.IsNullOrEmpty(e.Arguments); if (jumpList) { try { var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(e.Arguments); if (RootFrame.Content == null) { //RootFrame.Navigate(typeof(MainPage), file); RootFrame.Navigate(typeof(MainPage /*RichBox*/), file); } else { FileReceived?.Invoke(this, file); } } catch (Exception) { throw; } } else { //RootFrame.Navigate(typeof(MainPage), e.Arguments); RootFrame.Navigate(typeof(MainPage /*RichBox*/), e.Arguments); } Window.Current.Activate(); }
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { string arguments = string.Empty; if (DetermineStartCause(args) == AdditionalKinds.JumpListItem) { arguments = (args as LaunchActivatedEventArgs).Arguments; FileReceived?.Invoke(this, arguments); } NavigationService.Navigate(typeof(Views.MainPage), arguments); }
public void TreatFileReceived(string ipAddress, int port) { try { IPAddress ip = IPAddress.Parse(ipAddress); TcpListener tcpListener = new TcpListener(ip, port); tcpListener.Start(); while (true) { Socket socket = tcpListener.AcceptSocket(); if (socket.Connected) { string fileName = string.Empty; NetworkStream networkStream = new NetworkStream(socket); int thisRead = 0; int blockSize = 1024; Byte[] dataByte = new Byte[blockSize]; lock (this) { string pathDirectory = @"C:\Users\D-bugging\Desktop\TEMP\"; socket.Receive(dataByte); int fileNameLenght = BitConverter.ToInt32(dataByte, 0); fileName = Encoding.ASCII.GetString(dataByte, 4, fileNameLenght); Stream fileStream = File.OpenWrite(pathDirectory + fileName); fileStream.Write(dataByte, 4 + fileNameLenght, (1024 - (4 + fileNameLenght))); while (true) { thisRead = networkStream.Read(dataByte, 0, blockSize); fileStream.Write(dataByte, 0, thisRead); if (thisRead == 0) { break; } } fileStream.Close(); } FileReceived?.Invoke(this, fileName); socket = null; } } } catch { throw; } }
private void WriteFullFile(FileSystemInfo directory, TransportFileDelivery delivery, bool overwrite) { var fileName = delivery.TransportFile.Name; var filePath = Path.Combine(directory.FullName, fileName); if (overwrite) { DeleteExistingFile(delivery, directory); } using (var fs = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read)) delivery.TransportFile.WriteTo(fs); FileReceived?.Invoke(filePath); }
protected override void OnFileActivated(FileActivatedEventArgs args) { if (!args.Files.Any()) { return; } if (args.PreviousExecutionState == ApplicationExecutionState.Running) { FileReceived?.Invoke(this, args.Files.First() as Windows.Storage.StorageFile); } else { RootFrame.Navigate(typeof(MainPage /*RichBox*/), args.Files.First()); } //RootFrame.Navigate(typeof(MainPage), args.Files.First()); Window.Current.Activate(); }
/// <summary> /// Bind this event to the server or client so that it can process incoming packets, otherwise this class is useless /// </summary> /// <example>client.PacketReceived += (sender, packet) => fileTransfer.OnPacketReceived(server, packet);</example> /// <example>server.PacketReceived += (sender, packetArgs) => fileTransfer.OnPacketReceived(packetArgs.Client.EndPoint, packetArgs.Packet);</example> /// <param name="endPoint">The endpoint from which we received the packet. This is mostly used server side to prevent id clashes.</param> /// <param name="packet">The packet that was received</param> public void OnPacketReceived(EndPoint endPoint, IPacket packet) { if (!(packet is ChunkedDataPacket p)) { return; } var f = receivingFiles.FirstOrDefault(x => x.UniqueId == p.UniqueId && x.EndPoint == endPoint); if (f == null) { f = new ReceivingFileProcess(CreateNewTempFile(), p.UniqueId, endPoint); receivingFiles.Add(f); Logger.Info("Receiving a new file from {endPoint}, saving it to {path}", endPoint, f.Stream.Name); } f.Stream.Position = p.Offset; f.Stream.Write(p.Data, 0, p.Data.Length); f.Stream.Flush(); f.ReceivedChunks++; Logger.Debug("Received file chunk {chunk}/{totalChunks} ({pct})", f.ReceivedChunks, p.TotalChunks, (float)f.ReceivedChunks / p.TotalChunks); if (f.ReceivedChunks == p.TotalChunks) { Logger.Info("Received all file chunks"); f.Stream.Position = 0; if (FileReceived != null && FileReceived.GetInvocationList().Length > 0) { FileReceived.Invoke(this, f.Stream); } else { f.Stream.Close(); } receivingFiles.RemoveAll(x => x.UniqueId == p.UniqueId && x.EndPoint == endPoint); } }
/// <summary> /// Fires when a packet is received - Processes packets /// </summary> /// <param name="packet"></param> private void OnPacketReceived(Packet packet) { try { PacketReceived?.Invoke(packet); if (packet.PacketNumber + 1 != packet.TotalPackets) { tempPackets.Add(packet); } else { var fileData = PacketHandler.FromPackets(tempPackets.ToArray()); FileReceived?.Invoke(fileData); tempPackets.Clear(); } } catch (Exception ex) { TcpError?.Invoke(ex); } }
public void EndReceive() { if (_remainingData > 0) { throw new InvalidOperationException("_remainingData is not 0"); } _stream.Dispose(); _stream = null; if (!string.IsNullOrEmpty(_temporaryFile)) { var path = Path.GetDirectoryName(LocalPath); if (path.Length > 0) { Directory.CreateDirectory(path); // make sure directory exists } System.IO.File.Copy(_temporaryFile, LocalPath, true); new FileInfo(LocalPath).LastWriteTimeUtc = FileDateUtc; } FileReceived?.Invoke(this); }
//this event fires when a user double-clicks on a text file. protected override void OnFileActivated(FileActivatedEventArgs args) { //should this be removed or called prior to custom code. //base.OnFileActivated(args); //if no files passed, gracefully exit event handler. if (!args.Files.Any()) { return; } //if the application is already running, no need to navigate, just raise the event handler to load the file. //otherwise navigate to the main page and pass in the file to the OnNavigatedTo event handler. if (args.PreviousExecutionState == ApplicationExecutionState.Running) { FileReceived?.Invoke(this, args.Files.First() as Windows.Storage.StorageFile); } else { RootFrame.Navigate(typeof(MyNotepad.Views.MainPage), args.Files.First()); } Window.Current.Activate(); }
private void WriteChunkedFile(FileSystemInfo directory, TransportFileDelivery delivery, FileTransferProperties props, bool overwrite) { var fileName = delivery.TransportFile.Name; var filePath = GenerateUniqueFileName(Path.Combine(directory.FullName, fileName), overwrite); var uniqueTransferId = props.TransferId ?? 0; var tmpName = Path.ChangeExtension(filePath, $".{uniqueTransferId}.temp"); _log.LogDebug($"Processing chunk no. {props.ChunkNumber} - is last {props.LastChunk}"); if (filePath == null) { return; // only to make static code analysis happy. } try { long maxChunks; if (props.LastChunk) { maxChunks = props.ChunkNumber + 1; } else { maxChunks = props.FileSize / props.ChunkSize; maxChunks += props.FileSize % props.ChunkSize != 0 ? 1 : 0; } var headerSizeInBytes = ChunkedFileHeader.GetHeaderLengthInBytes(maxChunks); // Wait here to write to file var log = _log; // needed to make static code analysis happy (avoid using variable in and outside synchronization blocks warning) lock (string.Intern(tmpName)) { var tmpFileSize = headerSizeInBytes + props.FileSize; CheckTempFileConsistency(tmpName, uniqueTransferId, tmpFileSize); using (var fs = new FileStream(tmpName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) { using (var mmf = MemoryMappedFile.CreateFromFile(fs, null, tmpFileSize, MemoryMappedFileAccess.ReadWrite, HandleInheritability.Inheritable, false)) { var fileHeader = ChunkedFileHeader.ReadFromMemoryMappedFile(mmf, maxChunks); using (var accessor = mmf.CreateViewStream(headerSizeInBytes + props.ChunkOffset, 0)) { delivery.TransportFile.WriteTo(accessor); } fileHeader.ChunksReceived[props.ChunkNumber] = true; fileHeader.WriteToMemoryMappedFile(mmf); var isFileComplete = fileHeader.ChunksReceived.All(b => b); if (!isFileComplete) { return; } try { if (overwrite) { DeleteExistingFile(delivery, directory); } SaveCompletedFileContent(mmf, filePath, headerSizeInBytes, props.FileSize); log.LogInformation($"File written to {filePath}"); } catch (IOException e) { log.LogError($"Could not move file from {tmpName} to {filePath} because of {e.Message}"); throw; } } } File.Delete(tmpName); } FileReceived?.Invoke(filePath); } catch (IOException e) { _log.LogError($"Could not handle file {tmpName} -> {filePath}: '{e.Message}'"); } }
internal void InvokeFileReceived(string filePath) { FileReceived?.Invoke(this, filePath); }
/// <summary> /// Raises the FileReceived event; /// </summary> /// <param name="e"></param> protected override void OnFileReceived(FileEventArgs e) { FileReceived?.Invoke(this, e); }
internal void InvokeFileReceived(int id, string filePath) { FileReceived?.Invoke(id, filePath); }
// Opens a socket with the given Ip and Port and closes all other sockets associated with this method public static void OpenSocket(IPAddress ip, int port) { // Try catch used to make sure that any internal errors are caught and the program doesn't crash try { // Task.Run in conjunction with a lambda function allows for asynchronous in-line codeblocks Task.Run(() => { // The using statement allows an instance of the Socket class to be easily disposed when the method returns using (var _soc = new Socket(SocketType.Dgram, ProtocolType.Udp) { SendBufferSize = 131072, ReceiveBufferSize = 131072 }) { // Queues the newly created socket _openSockets.Enqueue(_soc); // Closes all excess sockets created by this method while (_openSockets.Count > 1) { // Grabs the first socket in the queue var _closeSoc = _openSockets.Dequeue(); // Raises the StatusUpdated event in order to notify the UI of a socket closing StatusUpdated?.Invoke("Closed " + _closeSoc.LocalEndPoint.ToString()); // Closes the socket _closeSoc.Close(); _closeSoc = null; } // Creates an endpoint which is either derived from the given IP or any ip if the given ip is null var _localEndPoint = (ip == null) ? new IPEndPoint(IPAddress.Any, port) : new IPEndPoint(ip, port); // Creates an endpoint to store the address of whatever client sends a message EndPoint _remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); // Binds the socket to the local end point in order to retrieve messages _soc.Bind(_localEndPoint); // Defines a buffer in which to store incoming data var _buff = new byte[131072]; // Raises the StatusUpdated event in order to notify the UI of a socket opening StatusUpdated?.Invoke("Opened " + _localEndPoint.ToString()); // Loops message recieve and send to echo back client messages while (_soc != null) { // Retrieves the number of new bytes in the buffer var _bytes = _soc.ReceiveFrom(_buff, 0, _buff.Length, SocketFlags.None, ref _remoteEndPoint); // Converts the buffer to a string message var _msg = Encoding.ASCII.GetString(_buff, 0, _bytes); // Vars to store the file parameters var _fileName = ""; var _fileExtension = ""; var _fileSize = 0; // Header before file "#FILE <FileName> <FileExtention>" if (_msg.Split('*')[0] == "#FILE") { // Grabs the file parameters from the header message _fileName = _msg.Split('*')[1]; _fileExtension = _msg.Split('*')[2]; // Notifies the UI that a file is incoming MessageReceived?.Invoke(_remoteEndPoint.ToString(), $"Incoming File: {_fileName}{_fileExtension}"); // Waits for the num bytes and file data from the client _fileSize = _soc.ReceiveFrom(_buff, 0, _buff.Length, SocketFlags.None, ref _remoteEndPoint); // Notifies the UI of a new file FileReceived?.Invoke(_remoteEndPoint.ToString(), _fileSize, _buff, _fileName, _fileExtension); _soc.SendTo(Encoding.ASCII.GetBytes($"Successfully Recieved: {_fileName}{_fileExtension}"), SocketFlags.None, _remoteEndPoint); // Skips the message recieved call continue; } // Notifies the UI of a new message MessageReceived.Invoke(_remoteEndPoint.ToString(), _msg); // Creates the echo message string var _echoMsg = "Echo: " + _msg; // Sends the echo message string to the client _soc.SendTo(Encoding.ASCII.GetBytes(_echoMsg), SocketFlags.None, _remoteEndPoint); } } }); } catch (Exception ex) { // For use debugging Console.WriteLine(ex); } }
private void OnClientDataReceived(object sender, DataReceivedEventArgs e) { if (!MessageConstructor.ValidateMessage(e.Data)) { if (StopAndWait) { byte[] msg = MessageConstructor.GetDataReceived(uint.MinValue, uint.MaxValue); Client.Send(msg, msg.Length); } return; } if (MessageConstructor.IsHandshake(e.Data)) { Connect(BitConverter.ToUInt32(e.Data, 1), BitConverter.ToUInt32(e.Data, 1 + sizeof(int)), e.EndPoint); return; } if (IsTransfering && MessageConstructor.IsFileData(e.Data)) { ReceivePacket(MessageConstructor.GetPacket(e.Data)); return; } if (MessageConstructor.IsFileMeta(e.Data)) { TotalPacketCount = BitConverter.ToUInt32(e.Data, 1 + sizeof(long)); string fn = Encoding.ASCII.GetString(e.Data, 1 + sizeof(long) + sizeof(uint), e.Data.Length - 1 - sizeof(long) - sizeof(uint) - sizeof(uint)); PrepareFile(fn); ReceivedPackets = new DataPacket[TotalPacketCount]; Console.WriteLine($"Receiving file '{fn}', total of {TotalPacketCount} packets."); WriteStatus(0, TotalPacketCount, false); Client.Send(e.Data, e.Data.Length); //Client.ErrorRate = 0.001; //Client.DropRate = 0.01; } if (IsTransfering && MessageConstructor.IsFileEnd(e.Data)) { WriteFile(); uint hash = BitConverter.ToUInt32(e.Data, 1); uint computed = MessageConstructor.GetFileHash(FileName); if (hash == computed) { FileReceived?.Invoke(this, new FileReceivedEventArgs() { FileName = FileName }); _is_transfering = false; } else { Console.WriteLine("Something is wrong, received different hash."); _is_transfering = false; } } }