/// <summary> /// When the server is closing, the function send event to all handler to be close. /// </summary> public void CloseServer() { CommandRecievedEventArgs comArgs = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, "*"); CommandRecieved?.Invoke(this, comArgs); m_tcpServer.Close(); }
/// <summary> /// task that listenning to the server to get command . /// </summary> public void CommandFromServer() { string commandStr; new Task(() => { Console.WriteLine("listening to the server "); while (!stop) { 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); } } }).Start(); }
/// <summary> /// send command to all the handlers. /// </summary> /// <param name="commandId"> the command required to be performed </param> /// <param name="args"> the arguments for the command </param> /// <param name="path"> the path related to the command </param> public void sendCommand(CommandEnum commandId, string[] args, string path) { CommandRecievedEventArgs cmdEventArgs = new CommandRecievedEventArgs((int)commandId, args, path); CommandRecieved?.Invoke(this, cmdEventArgs); m_logging.Log(path + " - " + commandId, Logging.Modal.MessageTypeEnum.INFO); }
/// <summary> /// create handler to specific client - read from the client command, use the controller to /// execute it and write to the client the answer. /// </summary> /// <param name="client">specific tcpClient to handle</param> public void HandleClient(TcpClient client) { using (NetworkStream stream = client.GetStream()) using (BinaryReader reader = new BinaryReader(stream)) using (BinaryWriter writer = new BinaryWriter(stream)) { while (true) { string newcommand = reader.ReadString(); CommandRecievedEventArgs command = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(newcommand); if (command.CommandID == (int)CommandStateEnum.CLOSE_HANDLER) { CommandRecieved?.Invoke(this, command); imageController.ExecuteCommand((int)command.CommandID, command.Args, out bool result, out MessageTypeEnum type); } else { string msg = imageController.ExecuteCommand((int)command.CommandID, null, out bool result, out MessageTypeEnum type); m.WaitOne(); writer.Write(msg); m.ReleaseMutex(); } } } }
/// <summary> /// This function is being called when a client wrote a new msg /// It transfer the object into CommandMessage and execute the /// right command /// </summary> /// <param name="sender"></param> /// <param name="info"></param> private void GetMessageFromUser(object sender, DataCommandArgs info) { var msg = CommandMessage.FromJson(info.Data); if (msg == null) { _mLogging.Log("Can't convert " + info.Data + " to JSON", MessageTypeEnum.FAIL); return; } _mLogging.Log("Got msg from user, Command ID: " + msg.CommandId, MessageTypeEnum.INFO); bool result; // close command if (msg.CommandId == (int)CommandEnum.CloseCommand) { CommandRecieved?.Invoke(this, new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, msg.Args[0])); // send the msg to all the clients serverChannel.SendToAll(msg.ToJson()); } else if (msg.CommandId == (int)CommandEnum.DeleteCommand) { DeleteImages(msg.Args); } else { string answer = _mController.ExecuteCommand(msg.CommandId, null, out result); serverChannel.SendToAll(answer); } }
/// <summary> /// The function removes the handler responsible to the /// given path and updates all related sources /// </summary> /// <param name="path">The path of the handler we want to remove</param> public bool RemoveHandler(string path) { if (string.IsNullOrWhiteSpace(path)) { return(false); } string oldPaths = ConfigurationManager.AppSettings["Handler"]; if (oldPaths.Contains(path)) { string newPaths = oldPaths.Replace(path, ""); newPaths = newPaths.Replace(";;", ";"); if (newPaths.EndsWith(";")) { newPaths = newPaths.Substring(0, newPaths.Length - 1); } Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location); config.AppSettings.Settings["Handler"].Value = newPaths; config.Save(); ConfigurationManager.RefreshSection("appSettings"); } CommandRecieved?.Invoke(this, new CommandRecievedEventArgs((int)CommandEnum.RemoveHandler, new string[] { "Recieved remove handler request for " + path }, path)); return(true); }
/// <summary> /// OnClosedService. /// The Event that will be activated upon the service closed. Invoke command recived event of /// closing the directory handlers. /// </summary> public void OnClosedService() { CommandRecievedEventArgs commandRecievedEventArgs = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, "*"); CommandRecieved?.Invoke(this, commandRecievedEventArgs); m_logging.Log("Server notify to close directory handler", Logging.Modal.MessageTypeEnum.INFO); }
/// <summary> /// Gets a path for a handler, closes that handler /// </summary> /// <param name="path"></param> public void closeSpecificHandler(string path) { pathList.Remove(path); CommandRecievedEventArgs cmdRecieved = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, path); CommandRecieved?.Invoke(this, cmdRecieved); m_logger.Log(DateTime.Now.ToString() + " Closing handler at path " + path, MessageTypeEnum.INFO); }
/// <summary> /// Closes the server. /// </summary> public void CloseServer() { ClientCommandEventArgs Args = new ClientCommandEventArgs(null, new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, "*")); CommandRecieved?.Invoke(this, Args); com_server.ServerStop(); }
/// <summary> /// Close the server.invoke the command of it closing. /// </summary> public void CloseServer() { string[] args = { }; CommandRecievedEventArgs e = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, args, "*"); CommandRecieved?.Invoke(this, e); m_logging.Log("Server is Closing ", MessageTypeEnum.INFO); }
public void Stop() { m_Logger.Log("Shutting down server..", MessageTypeEnum.INFO); int commandID = 1; string[] args = { }; CommandRecieved.Invoke(this, new CommandRecievedEventArgs(commandID, args, "")); }
private async Task Callback(object source, ActionEventArgs e) { if (Host.ShuttingDown) { return; } switch (e.ActionType) { case PluginActionType.SignalTerminate: if (Terminated == null) { break; } await Terminated.Invoke(this, EventArgs.Empty); break; case PluginActionType.RegisterMethod: if (!(e.Result is IAsyncRegistrar <ServerMessagedEventArgs>)) { break; } Host.RegisterMethod((IAsyncRegistrar <ServerMessagedEventArgs>)e.Result); break; case PluginActionType.SendMessage: if (!(e.Result is CommandEventArgs) || CommandRecieved == null) { break; } await CommandRecieved.Invoke(this, (CommandEventArgs)e.Result); break; case PluginActionType.Log: if (!(e.Result is string)) { break; } if (Log == null) { return; } await Log.Invoke(this, new BasicEventArgs((string)e.Result)); break; default: throw new ArgumentOutOfRangeException(); } }
/// <summary> /// Invoking the subscribers once the command was Recieved. /// </summary> public void sendCommand() { //We dont want to remove the handlers from the app config so we just close them string[] args = { "*", "false" }; CommandRecievedEventArgs commandArgs = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, args, ""); //The invoke will run all the handlers on close server CommandRecieved?.Invoke(this, commandArgs); }
/// <summary> /// This is a method for stopping the server. /// </summary> public void StopServer() { // Log the stoppage: LoggingService.Log("Stopping & closing the server", MessageTypeEnum.INFO); // Invoke close command: var eventArgs = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, ""); CommandRecieved?.Invoke(this, eventArgs); }
/// <summary> /// method to close the server by commanding the handlers to close first /// </summary> public void CloseServer() { // invoke close all directories CommandRecieved Event CommandRecievedEventArgs args = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, "*"); CommandRecieved.Invoke(this, args); // wait for all handlers to close while ((CommandRecieved != null) && (CommandRecieved.GetInvocationList().Length > 0)) { System.Threading.Thread.Sleep(1000); } // update logger m_logging.Log("Server is Closed", MessageTypeEnum.INFO); }
public void CloseServer() { CommandRecievedEventArgs commandRecEventArgs = new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, null, null); CommandRecieved?.Invoke(this, commandRecEventArgs); try { listener.Stop(); } catch (Exception e) { m_logging.Log(e.Message, MessageTypeEnum.FAIL); } }
public void RemoveHandler(string path) { string oldPaths = ConfigurationManager.AppSettings["Handler"]; if (oldPaths.Contains(path)) { string newPaths = oldPaths.Replace(path, ""); newPaths = newPaths.Replace(";;", ";"); Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location); config.AppSettings.Settings["Handler"].Value = newPaths; config.Save(); } CommandRecieved?.Invoke(this, new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, new string[] { "Recieved remove handler request for " + path }, path)); }
private void AuroraCommandsServerIPC() { PipeSecurity pipeSa = new PipeSecurity(); pipeSa.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); while (isRunning) { try { using (IPCCommandpipeStream = new NamedPipeServerStream( "Aurora\\interface", PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.None, 5 * 1024, 5 * 1024, pipeSa, HandleInheritability.None )) { Global.logger.LogLine(String.Format("[AuroraCommandsServerIPC] Pipe created {0}", IPCCommandpipeStream?.GetHashCode())); IPCCommandpipeStream?.WaitForConnection(); Global.logger.LogLine("[AuroraCommandsServerIPC] Pipe connection established"); using (StreamReader sr = new StreamReader(IPCCommandpipeStream)) { string temp; while ((temp = sr.ReadLine()) != null) { Global.logger.LogLine("[AuroraCommandsServerIPC] Recieved command: " + temp); string[] split = temp.Contains(':') ? temp.Split(':') : new[] { temp }; CommandRecieved.Invoke(split[0], split.Length > 1 ? split[1] : ""); } } } Global.logger.LogLine("[AuroraCommandsServerIPC] Pipe connection lost"); } catch (Exception exc) { Global.logger.LogLine("[AuroraCommandsServerIPC] Named Pipe Exception, " + exc, Logging_Level.Error); } } }
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> /// Reads the command from the client. /// </summary> /// <param socker="s"></param> private void ReadCommand(Socket s) { while (IsConnected(s)) { try { byte[] b = new byte[1000]; string send = "empty"; int k = s.Receive(b); //m_logging.Log("Recieved...", Logging.Modal.MessageTypeEnum.INFO); int i = (int)Char.GetNumericValue(Convert.ToChar(b[0])); switch (i) { case 1: send = m_controller.ExecuteCommand(i, null, out bool result); break; case 2: send = m_controller.ExecuteCommand(i, null, out bool res); break; case 3: clients.Remove(s); return; case 5: string handel = ByteToString(b, k); IList <string> each = handel.Split(',').Reverse().ToList(); CommandRecieved?.Invoke("*", new CommandRecievedEventArgs(3, null, each[0])); send = "2" + each[0]; SendCloseHandler(each[0], s); break; } // m_logging.Log("sending " + send, Logging.Modal.MessageTypeEnum.INFO); if (IsConnected(s)) { Write(s, send); } } catch (Exception e) { break; } } }
public void CommandFromServer() { string commandStr; new Task(() => { while (!stop) { NetworkStream stream = tcpClient.GetStream(); BinaryReader reader = new BinaryReader(stream); //BinaryWriter writer = new BinaryWriter(stream); commandStr = reader.ReadString(); Console.WriteLine($"Recieve {commandStr} from Server"); //string jStr = JsonConvert.SerializeObject(e); //writer.Write(jStr); CommandRecievedEventArgs responseObj = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(commandStr); CommandRecieved?.Invoke(this, responseObj); } }).Start(); }
/// <summary> /// reading messages from client and sending them so service /// </summary> /// <param name="client"> sendind the message </param> public void HandleClient(TcpClient client) { new Task(() => { using (NetworkStream stream = client.GetStream()) using (BinaryReader reader = new BinaryReader(stream)) { while (true) { if (client.Connected) { string messageInString = reader.ReadString();//reading string message CommandMessage message = JsonConvert.DeserializeObject <CommandMessage>(messageInString); string[] args = { message.MessageResponse }; CommandRecieved?.Invoke(this, new CommandRecievedEventArgs(message.CommandID, args, message.MessageResponse));//sending message to server } } } }).Start(); }
/// <summary> /// initializes members and connects to server /// </summary> public bool Start() { if (this.isConnectionAttemptDone) { return(isOn); } this.isConnectionAttemptDone = true; try { //Auto choose client socket (no params) client = new TcpClient(); IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000); client.Connect(endPoint); stream = client.GetStream(); reader = new BinaryReader(stream); writer = new BinaryWriter(stream); } catch (Exception e) { return(false); } this.isOn = true; string rawData; CommandRecievedEventArgs commandArgs; new Task(() => { while (true) { try { rawData = reader.ReadString(); commandArgs = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(rawData); CommandRecieved?.Invoke(this, commandArgs); } catch (Exception e) {; } } }).Start(); return(true); }
/// <summary> /// sending the given command from the server to all the application's handlers. /// </summary> /// <param name="e"> The command that will be sent. </param> public void SendCommand() { string[] args = new string[1]; args[0] = ""; CommandRecieved?.Invoke(this, new CommandRecievedEventArgs((int)CommandEnum.CloseCommand, args, "")); }
// Invoke safely void InvokeOnCommandRecieved(string command, TcpClient requester) => CommandRecieved?.Invoke(command, requester);
/// <summary> /// Sends the command to the controller, that then executes the command. /// </summary> public void SendCommandToController() { string[] args = null; CommandRecieved?.Invoke("*", new CommandRecievedEventArgs(3, args, "")); myList.Stop(); }
/// <summary> /// invokes the CommandRecieved event to indicate a command was recieved /// </summary> public void NewCommand(object sender, CommandRecievedEventArgs e) { CommandRecieved?.Invoke(this, e); }
public void makeEvent(CommandRecievedEventArgs commandRecievedEventArgs) { CommandRecieved?.Invoke(this, commandRecievedEventArgs); }
/// <summary> /// Sends the command that was received. /// </summary> /// <param name="e"> Event. </param> public void SendCommand(CommandRecievedEventArgs e) { CommandRecieved?.Invoke(this, e); }
/// <summary> /// this method send command to all handlers by event. /// </summary> /// <param name="e">args for the event</param> public void SendCommand(object sender, CommandRecievedEventArgs e) { CommandRecieved?.Invoke(sender, e); }