/// <summary> /// HandleClient function. /// handles the client-server communication. /// </summary> /// <param name="client">specified client</param> /// <param name="clients">list of all current clients</param> public void HandleClient(TcpClient client, List <TcpClient> clients) { try { new Task(() => { try { while (!m_isStopped) { NetworkStream stream = client.GetStream(); BinaryReader reader = new BinaryReader(stream); BinaryWriter writer = new BinaryWriter(stream); string commandLine = reader.ReadString(); Logging.Log("ClientHandler got command: " + commandLine, MessageTypeEnum.INFO); CommandRecievedEventArgs commandRecievedEventArgs = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(commandLine); if (commandRecievedEventArgs.CommandID == (int)CommandEnum.Disconnected) { clients.Remove(client); client.Close(); break; } bool r; string result = this.ImageController.ExecuteCommand((int)commandRecievedEventArgs.CommandID, commandRecievedEventArgs.Args, out r); // string result = handleCommand(commandRecievedEventArgs); Mutex.WaitOne(); writer.Write(result); Mutex.ReleaseMutex(); } } catch (Exception ex) { clients.Remove(client); Logging.Log(ex.ToString(), MessageTypeEnum.FAIL); client.Close(); } }).Start(); } catch (Exception ex) { Logging.Log(ex.ToString(), MessageTypeEnum.FAIL); } }
/// <summary> /// Updates the specified arrived message. /// </summary> /// <param name="arrivedMessage">The <see cref="CommandRecievedEventArgs"/> instance containing the event data.</param> private void Update(CommandRecievedEventArgs arrivedMessage) { try { foreach (Log log in JsonConvert.DeserializeObject <ObservableCollection <Log> >(arrivedMessage.Args[0])) { this.logs.Add(log); // setLogs(log); } } catch (Exception e) { Console.WriteLine("exception in update-logmodel" + e.Message); MessageBox.Show(e.ToString()); } }
//checks if extension exist in extensionsToListen. if yes-use CommandRecievedEventArgs to notice. private void OnChanged(object o, FileSystemEventArgs comArgs) { // debug.write("OnChanged"); string argsFullPath = comArgs.FullPath; Debug_program debug = new Debug_program(); debug.write(comArgs.FullPath); string[] args = { comArgs.FullPath }; string fileExtension = Path.GetExtension(argsFullPath); // debug.write(fileExtension); if (extensionsToListen.Contains("*" + fileExtension)) { CommandRecievedEventArgs commandArgs = new CommandRecievedEventArgs((int)CommandEnum.NewFileCommand, args, fileExtension); OnCommandRecieved(this, commandArgs); } }
public void send(object o, MessageRecievedEventArgs dirArgs) { try { if (isRunning) { MessageTypeEnum s = dirArgs.Status; string[] Args = { Convert.ToString((int)dirArgs.Status), dirArgs.Message }; CommandRecievedEventArgs cre = new CommandRecievedEventArgs((int)CommandEnum.AddLog, Args, null); string jsonCommand = JsonConvert.SerializeObject(cre); writer.Write(jsonCommand); } } catch (Exception e) { } }
/// <summary> /// a method that get an object and a CommandRecievedEventArgs and execute the command recieved /// </summary> /// <param name="sender">an object</param> /// <param name="e">a CommandRecievedEventArgs that represent the command who recieved</param> public void OnCommandRecieved(object sender, CommandRecievedEventArgs e) { bool result; string msg = m_controller.ExecuteCommand(e.CommandID, e.Args, out result); if (result) { m_logging.Log(msg, MessageTypeEnum.INFO); } else { m_logging.Log(msg, MessageTypeEnum.FAIL); } string s = m_controller.ExecuteCommand((int)CommandEnum.LastLogCommand, null, out result); m_tcpServer.NotifyAll(s); }
/// <summary> /// OnCommandRecieved of this handler actually tells the server that this handler is being closed /// and when the last handler is closed the server can finally stop. /// </summary> /// <param name="sender"> sender </param> /// <param name="e"> CommandRecievedEventArgs </param> public void OnCommandRecieved(object sender, CommandRecievedEventArgs e) { switch (e.CommandID) { case (int)CommandEnum.CloseHandlerCommand: this.m_logging.Log("closing Directory Handler of directory in path: " + this.m_path, MessageTypeEnum.INFO); DirectoryClose?.Invoke(this, new DirectoryCloseEventArgs(this.m_path, "closing")); for (int i = 0; i < 4; i++) { this.m_dirWatchers[i].Dispose(); } break; default: throw new ArgumentException(); } }
private void DataReceviedServer(object sender, DataReceivedEventArgs e) { MessageCommand mc = MessageCommand.FromJSON(e.Message); if (mc.CommandID == (int)CommandEnum.CloseCommand) { CommandRecievedEventArgs comArgs = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, mc.CommandMsg); CommandRecieved?.Invoke(this, comArgs); } else { string convert = m_controller.ExecuteCommand(mc.CommandID, null, out bool result); mc.CommandMsg = convert; ClientHandler ch = sender as ClientHandler; ch.Send(mc.ToJSON()); } }
/// <summary> /// Implements the ICommand interface /// When given closecommand, the method invokes the closeCommandEvent /// </summary> /// <param name="args"> /// The command enum and path /// </param> /// <param name="result"> /// </param> /// <returns></returns> public string Execute(string[] args, out bool result) { string path = args[1]; CommandRecievedEventArgs e = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, path); CloseCommandEvent?.Invoke(this, e); result = true; JObject closeObj = new JObject { ["CommandEnum"] = (int)CommandEnum.CloseCommand, ["Directory"] = path }; return(closeObj.ToString()); }
public string Execute(string[] args, out bool result) { try { SettingsObject settings = SettingsObject.GetInstance; string[] arguments = new string[1]; arguments[0] = settings.ToJson(); CommandRecievedEventArgs c = new CommandRecievedEventArgs((int)CommandEnum.GetConfigCommand, arguments, null); result = true; return(c.ToJson()); } catch (Exception e) { result = false; return(e.ToString()); } }
private void OnCommandRecieved(object sender, CommandRecievedEventArgs c_args) { string output = image_controller.ExecuteCommand(c_args.Command, c_args.Args, out MessageTypeEnum status, c_args.Client_Socket); // Update eventlogger and LogsModal with new log. if ((c_args.Command == (int)CommandEnum.NewFileCommand) || (c_args.Command == (int)CommandEnum.CloseCommand)) { logging_service.Log(output, status); string[] args = { output, ((int)status).ToString() }; image_controller.LogsModal.ServiceLogs.Add(args[0]); image_controller.LogsModal.ServiceLogs.Add(args[1]); // Send log to all clients. channel.SendCommandBroadCast(new CommandMessage((int)CommandEnum.LogCommand, args)); } }
/// <summary>The Event that will be activated upon new Command</summary> /// <param name="sender">The sender object</param> /// <param name="e">The arguments received by the command event</param> public void OnCommandRecieved(object sender, CommandRecievedEventArgs e) { bool currentResult; string message = this.m_controller.ExecuteCommand(e.CommandID, e.Args, out currentResult); // According to the current result - INFO if true, FAIL if not if (currentResult) { //Log INFO this.m_logging.Log(message, MessageTypeEnum.INFO); } else { //Log FAIL this.m_logging.Log(message, MessageTypeEnum.FAIL); } }
public event EventHandler <DirectoryCloseEventArgs> DirectoryClose; // The Event That Notifies that the Directory is being closed /// <summary> /// method handling commands being sent to the directory handler object /// </summary> /// <param name="sender">the sender of the command</param> /// <param name="e">arguments and info of the sent command</param> public void OnCommandRecieved(object sender, CommandRecievedEventArgs e) { m_logging.Log("In directory handler received command with id: " + e.CommandID, MessageTypeEnum.INFO); //right now with switch case because its a general command and not only close switch (e.CommandID) { //close command case CommandEnum.CloseCommand: this.CloseDirectory(); DirectoryClose?.Invoke(this, new DirectoryCloseEventArgs(this.m_path, "closing")); break; default: throw new ArgumentException(); } }
/// <summary> /// a method that get an object and a CommandRecievedEventArgs and close the service /// </summary> /// <param name="sender">an object yhat reoresent the ImageServer</param> /// <param name="e">a DirectoryCloseEventArgs</param> public void onCloseService(object sender, CommandRecievedEventArgs e) { ImageServer server = (ImageServer)sender; m_dirWatcher.EnableRaisingEvents = false; m_dirWatcher.Dispose(); string msg = "Handler closed " + m_path; m_logging.Log(msg, MessageTypeEnum.INFO); bool result; string s = m_controller.ExecuteCommand((int)CommandEnum.LastLogCommand, null, out result); if (result) { m_tcpServer.NotifyAll(s); } }
public string Execute(string[] args, out bool result) { try { string[] arr = new string[5]; arr[0] = ConfigurationManager.AppSettings.Get("OutputDir"); arr[1] = ConfigurationManager.AppSettings.Get("SourceName"); arr[2] = ConfigurationManager.AppSettings.Get("LogName"); arr[3] = ConfigurationManager.AppSettings.Get("ThumbnailSize"); arr[4] = ConfigurationManager.AppSettings.Get("Handler"); CommandRecievedEventArgs commandArgs = new CommandRecievedEventArgs((int)CommandEnum.GetConfigCommand, arr, ""); result = true; return(JsonConvert.SerializeObject(commandArgs)); } catch (Exception e) { result = false; return(e.ToString()); } }
private void LogRecieved(object sender, CommandRecievedEventArgs args) { //ignore if it isn't a log command if (args.CommandID != (int)CommandEnum.LogCommand) { return; } IList <LogItem> newItems = JsonConvert.DeserializeObject <IList <LogItem> >(args.Args[0]); //add new log entries to the list foreach (LogItem item in newItems) { this.LogsList.Add(item); } LogRecievedEvent?.Invoke(this, null); }
/// <summary> /// add the logs from the server /// </summary> /// <param name="args"></param> private void SetupPreviousLogs(CommandRecievedEventArgs args) { try { ObservableCollection <LogTuple> previousLogs = JsonConvert.DeserializeObject <ObservableCollection <LogTuple> >(args.Args[0]); for (int i = 1; i < previousLogs.Count(); i++) { this.logs.Add(new Log { Type = previousLogs[i].EnumType.ToString(), Message = previousLogs[i].Data }); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public void HandleClient(TcpClient client) { new Task(() => { using (NetworkStream stream = client.GetStream()) using (StreamReader reader = new StreamReader(stream)) { bool result; while (client.Connected) { string commandLine = reader.ReadToEnd(); CommandRecievedEventArgs cmd = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(commandLine); int command = cmd.CommandID; switch (command) { case (int)CommandEnum.GetConfigCommand: string data = this.m_controller.ExecuteCommand(command, null, out result); SendData(client, data); break; case (int)CommandEnum.LogCommand: data = this.m_controller.ExecuteCommand (command, null, out result); SendData(client, data); break; case (int)CommandEnum.CloseCommand: this.m_controller.ExecuteCommand(command, cmd.Args, out result); break; } } bool suc; string result = this.m_controller.ExecuteCommand(Int32.Parse(commandLine), null, out suc); writer.Write(result); } client.Close(); }).Start(); }
/// <summary> /// A generic send to server function. we send a command and an item. /// </summary> /// <param name="commandEnum">The type of command we send</param> /// <param name="item">The path of the handler. If we don't pick any specific handler this will be "Empty" string.</param> public void SendCommandToServer(CommandEnum commandEnum, string item) { string[] args = { }; // we remove a specific handler // if item is not an empty string we initialize args[0] as item, and send it as args. if (!item.Equals("")) { args = new string[1]; args[0] = item; CommandRecievedEventArgs e = new CommandRecievedEventArgs((int)commandEnum, args, item); SendInfo?.Invoke(this, e); } else // we receive info from the server { CommandRecievedEventArgs e = new CommandRecievedEventArgs((int)commandEnum, args, "Empty"); SendInfo?.Invoke(this, e); } }
/// <summary> /// Generate new LogCommand using the logging service /// </summary> /// <param name="args"> input args</param> /// <param name="result"> out result </param> /// <returns></returns> public string Execute(string[] args, out bool result) { try { ObservableCollection <LogTuple> logs = this._loggingService.Logs; string decriptedLogs = JsonConvert.SerializeObject(logs); string[] arr = new string[1]; arr[0] = decriptedLogs; CommandRecievedEventArgs commandSendArgs = new CommandRecievedEventArgs((int)CommandEnum.LogCommand, arr, ""); result = true; return(JsonConvert.SerializeObject(commandSendArgs)); } catch (Exception e) { result = false; return("Error in get previous logs command"); } }
/// <summary> /// Write to the server /// </summary> /// <param name="command">The command the write</param> public void Write(CommandRecievedEventArgs command) { try { //json the command string json = JsonConvert.SerializeObject(command); NetworkStream stream = client.GetStream(); BinaryWriter writer = new BinaryWriter(stream); //send json m_mutex.WaitOne(); writer.Write(json); m_mutex.ReleaseMutex(); } catch (Exception e) { Console.WriteLine(e.Message); } }
/// <summary> /// ask the currect logs from the server /// </summary> /// <returns></returns> private bool SendInitRequest() { try { if (!logModelClient.Running()) { return(false); } CommandRecievedEventArgs commandReq = new CommandRecievedEventArgs((int)CommandEnum.LogCommand, null, ""); this.logModelClient.WriteCommandToServer(commandReq); } catch (Exception e) { Console.WriteLine(e.ToString()); return(false); } return(true); }
private void UpdateConfigurations(CommandRecievedEventArgs e) { OutputDirectory = e.Args[0]; SourceName = e.Args[1]; LogName = e.Args[2]; int thumb; int.TryParse(e.Args[3], out thumb); ThumbnailSize = thumb; string[] handlers = e.Args[4].Split(';'); foreach (string handler in handlers) { if (!Handlers.Contains(handler)) { Handlers.Add(handler); } } }
//public event PropertyChangedEventHandler PropertyChanged; public void OnCommandRecieved(object sender, CommandRecievedEventArgs e) { // if it's get log command if (e.CommandID == (int)CommandEnum.LogCommand) { // translate the Args array of CommandRecievedEventArgs to logs and add them to logCollection for (int i = 0; i < e.Args.Length; i += 2) { MessageRecievedEventArgs log = new MessageRecievedEventArgs(); log.Status = this.FromString(e.Args[i]); log.Message = e.Args[i + 1]; App.Current.Dispatcher.Invoke((Action) delegate { this.LogsCollection.Add(log); }); } } }
/// <summary> /// Constructor /// </summary> public SettingsModel() { //get instance of communication this.Communication = CommunicationSingleton.Instance; //sign to InMessage this.Communication.Read(); this.Communication.InMessage += UpdateSettings; //create list of handelrs this.LbHandlers = new ObservableCollection <string>(); Object settingsLock = new Object(); BindingOperations.EnableCollectionSynchronization(LbHandlers, settingsLock); //write GetConfigCommand to server string[] arr = new string[5]; CommandRecievedEventArgs command = new CommandRecievedEventArgs((int)CommandEnum.GetConfigCommand, arr, ""); this.Communication.Write(command); }
/// <summary> /// constructor. /// </summary> public LogInfoModel() { LogMessages = new List <Log>(); try { // Set new command for creating log. CommandRecievedEventArgs command = new CommandRecievedEventArgs((int)CommandEnum.LogCommand, null, ""); // Send command and recevie back log history. TCPClientChannel.GetTCPClientChannel().DisconnectClientChannel(); string settingsMsg = TCPClientChannel.GetTCPClientChannel().SendAndReceive(command); // Add log history to log. UpdateByNotification(settingsMsg); //TCPClientChannel.GetTCPClientChannel().ListenToServer(); } catch (Exception) { } }
public void OnCommandRecieved(object sender, CommandRecievedEventArgs e) { if (this.directoryPath.Equals(e.RequestDirPath) || e.RequestDirPath.Equals("*")) { bool result; // execute recieved command string message = this.imageController.ExecuteCommand(e.CommandID, e.Args, out result); // check if command has executed succesfully and write result to the log if (result) { loggingModal.Log(message, MessageTypeEnum.INFO); } else { loggingModal.Log(message, MessageTypeEnum.FAIL); } } }
/// <summary> /// returns the logs list after convertion to json. /// </summary> /// <param name="args">args</param> /// <param name="result">succes flag</param> /// <returns></returns> public string Execute(string[] args, out bool result) { result = true; try { //serialize the new logs list in order to store in command args member of a string array type string[] str = new string[1]; str[0] = JsonConvert.SerializeObject(logCollectionSingleton.LogsCollection.ToList()); //create logs command with th new logs list CommandRecievedEventArgs argsToReturn = new CommandRecievedEventArgs((int)CommandEnum.LogCommand, str, ""); //serialize whole of it in order to return as string as the generic execute func declares return(JsonConvert.SerializeObject(argsToReturn)); } catch (Exception e) { result = false; return(e.ToString()); } }
/// <summary> /// Executes a log command. /// </summary> /// <param name="args">The command's arguments.</param> /// <param name="result">True if succeeded.</param> /// <returns></returns> public string Execute(string[] args, out bool result) { try { List <MessageRecievedEventArgs> logsList = m_logging.LogList; string jsonLogsList = JsonConvert.SerializeObject(logsList); string[] arr = new string[1]; arr[0] = jsonLogsList; CommandRecievedEventArgs commandSend = new CommandRecievedEventArgs((int)CommandEnum.LogCommand, arr, ""); result = true; return(JsonConvert.SerializeObject(commandSend)); } catch (Exception exc) { result = false; return(exc.ToString()); } }
/// <summary> /// UpdateConfigurations function. /// updates app config params. /// </summary> /// <param name="responseObj">the info came from srv</param> private void UpdateConfigurations(CommandRecievedEventArgs responseObj) { try { this.OutputDirectory = responseObj.Args[0]; this.SourceName = responseObj.Args[1]; this.LogName = responseObj.Args[2]; this.TumbnailSize = responseObj.Args[2]; string[] handlers = responseObj.Args[4].Split(';'); foreach (string handler in handlers) { this.Handlers.Add(handler); } } catch (Exception ex) { } }
/// <summary> /// OneCommandFromServer. /// function for handle only one event that command have been recieved . /// </summary> public void OneCommandFromServer() { string commandStr; try { NetworkStream stream = tcpClient.GetStream(); BinaryReader reader = new BinaryReader(stream); commandStr = reader.ReadString(); Console.WriteLine($"Recieve {commandStr} from Server"); CommandRecievedEventArgs responseObj = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(commandStr); CommandRecieved?.Invoke(this, responseObj); } catch (Exception e) { Console.WriteLine(e.Message); } }