コード例 #1
0
 /// <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();
                     }
                 }
             }
 }
コード例 #2
0
        /// <summary>
        /// Executes the commands using the controller.
        /// </summary>
        /// <param name="sender"> Sender. </param>
        /// <param name="e"> Event. </param>
        public void OnCommandRecieved(object sender, CommandRecievedEventArgs e)
        {
            bool result;

            if (e.CommandID == (int)CommandEnum.NewFileCommand)
            {
                if (!e.RequestDirPath.Equals(m_path))
                {
                    return;
                }
                m_logging.Log("going into addFile", MessageTypeEnum.INFO);
                string r = m_controller.ExecuteCommand(e.CommandID, e.Args, out result);
                if (!result)
                {
                    m_logging.Log("Command failed.", MessageTypeEnum.FAIL);
                    return;
                }
                m_logging.Log("Command successful.", MessageTypeEnum.INFO);
            }
            else if (e.CommandID == (int)CommandEnum.CloseCommand)
            {
                m_logging.Log("Command close success", MessageTypeEnum.INFO);
                EndHandler();
                return;
            }
        }
コード例 #3
0
        /**
         * when the directory is changing, send the pictures to the correct path.
         */
        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            string[] args = new string[1];
            args[0] = e.FullPath;
            string          path = args[0];
            bool            result;
            DateTime        lastWriteTime = File.GetLastWriteTime(e.FullPath);
            MessageTypeEnum typeMsg       = new MessageTypeEnum();

            if (lastWriteTime != lastRead)
            {
                string resultMsg = "could'nt find picture...";
                //string fileEnding = Path.GetExtension(path);
                if (isCorrectEnding(path))
                {
                    resultMsg = controller.ExecuteCommand((int)CommandEnum.NewFileCommand, args, out result);
                    if (result)
                    {
                        typeMsg = MessageTypeEnum.INFO;
                    }
                    else
                    {
                        typeMsg = MessageTypeEnum.FAIL;
                    }
                }
                lastRead = lastWriteTime;
                logging.Log(resultMsg, typeMsg);
            }
        }
コード例 #4
0
        /// <summary>
        /// This function is being called whenever a new client is connected
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnNewClient(object sender, NewClientEventArgs e)
        {
            bool   result;
            string answer = _mController.ExecuteCommand((int)CommandEnum.GetConfigCommand, null, out result);

            if (answer != "")
            {
                serverChannel.SendSpecificlly(e.Client, answer);
            }
            lock (thisLock)
            {
                // get the list of logs
                List <MessageRecievedEventArgs> logMsgsReversed =
                    new List <MessageRecievedEventArgs>(LogService.Instance.LogMsgs);
                // reverse the list
                logMsgsReversed.Reverse();
                // go over the list of logs ans send them to the specific client
                foreach (MessageRecievedEventArgs msg in logMsgsReversed)
                {
                    string[]       info = { msg.Status.ToString(), msg.Message };
                    CommandMessage msgC = new CommandMessage((int)CommandEnum.LogCommand, info);
                    serverChannel.SendSpecificlly(e.Client, msgC.ToJson());
                    System.Threading.Thread.Sleep(100);
                }
            }
            _mLogging.Log("New client is connected", MessageTypeEnum.INFO);
            _mLogging.Log("Send config: " + answer, MessageTypeEnum.INFO);
        }
コード例 #5
0
        /// <summary>
        /// The event occur upon receiving a command.
        /// </summary>
        /// <param name="sender"></param> The command sender (invoker).
        /// <param name="e"></param> The argumetns.
        public void OnCommandRecieved(object sender, CommandReceivedEventArgs e)
        {
            string msg;
            bool   result = true;

            if (e.CommandID == CommandEnum.CloseCommand)
            {
                if (e.RequestDirPath != dirPath)
                {
                    return;
                }
                msg = "Directory " + dirPath + " is closing";
                dirWatcher.EnableRaisingEvents = false;
                DirectoryClose?.Invoke(this, new DirectoryCloseEventArgs(e.RequestDirPath, msg));
                //logger.Log(msg, MessageTypeEnum.INFO);
            }
            else
            {
                if (!IsSubFile(e.RequestDirPath))
                {
                    return;
                }
                msg = controller.ExecuteCommand(e.CommandID, e.Args, out result);
            }
            logger.Log(msg, GetMessageType(result));
        }
コード例 #6
0
        //Called when a new file is added
        private void OnCreated(object source, FileSystemEventArgs e)
        {
            List <string> extensions = new List <string>()
            {
                ".jpg", ".png", ".gif", ".bmp", ".MOV"
            };

            string extension = Path.GetExtension(e.FullPath);

            if (!extensions.Contains(extension))
            {
                return;
            }

            Logging.Log(e.Name + " was added to " + DirPath, MessageTypeEnum.INFO);
            string[] args = { e.FullPath };
            string   info = Controller.ExecuteCommand(CommandEnum.NewFile, args, out bool result);

            if (result)
            {
                Logging.Log(e.Name + " moved to " + DirPath, MessageTypeEnum.INFO);
            }
            else
            {
                Logging.Log(e.Name + " failed to move to " + DirPath + ": " + info, MessageTypeEnum.FAIL);
            }
        }
コード例 #7
0
        // handles commands from server
        // no comands from server at this point of the ex
        public void OnCommandRecieved(object sender, CommandRecievedEventArgs e)
        {
            bool flag;

            // TODO:    execute command
            // figure out what to send to the execute comand
            m_controller.ExecuteCommand(e.CommandID, e.Args, out flag);
        }
コード例 #8
0
ファイル: ImageServer.cs プロジェクト: yifrach/ImageService
        /// <summary>
        /// the method incharge to close the hanlers and the all service.
        /// </summary>
        public void onCloseService()
        {
            CloseService?.Invoke(this, null);
            m_logging.Log("On stop", Logging.Modal.MessageTypeEnum.INFO);
            bool   res;
            string s = m_controller.ExecuteCommand((int)CommandEnum.LastLogCommand, null, out res);

            this.m_tcpServer.NotifyAll(s);
        }
コード例 #9
0
ファイル: ImageServer.cs プロジェクト: shaytzir/ImageSerivce
        /// <summary>
        /// Sends the settings and log.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="client">The client.</param>
        private void SendSettingsAndLog(object sender, IClientHandler client)
        {
            bool success;
            //genertate string (serialize to json of all settings from the appconfig)
            string setting = m_controller.ExecuteCommand((int)CommandEnum.GetConfigCommand, null, out success);

            client.SendCommand(setting);
            string log = m_controller.ExecuteCommand((int)CommandEnum.LogCommand, null, out success);

            client.SendCommand(log);
        }
コード例 #10
0
 /// <summary>
 ///See if command is meant for its directory
 ///Close command of execute command.
 ///Param: object, CommandRecuevedEventArgs.
 /// </summary>
 public void OnCommandRecieved(object sender, CommandRecievedEventArgs e) //how to check if command is meant for its directory?
 {
     if (e.CommandID == (int)CommandEnum.CloseCommand && (e.RequestDirPath.Equals(m_path) || e.RequestDirPath.Equals("")))
     {
         CloseHandler(sender, e);
     }
     else
     {
         m_controller.ExecuteCommand(e.CommandID, e.Args, out bool result);  // why object sender? its "*"
     }
 }
コード例 #11
0
ファイル: ClientHandler.cs プロジェクト: AmitHadas/advanced2
        /// <summary>
        /// Handles the client.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="stream">The stream.</param>
        public void HandleClient(TcpClient client, NetworkStream stream)
        {
            m_logging.Log("start listening to new client...", Logging.Modal.MessageTypeEnum.INFO);
            new Task(() =>
            {
                StreamReader reader = new StreamReader(stream);
                StreamWriter writer = new StreamWriter(stream);
                while (true)
                {
                    try
                    {
                        bool res;
                        string commandLine = reader.ReadLine();
                        while (reader.Peek() > 0)
                        {
                            commandLine += reader.ReadLine();
                        }
                        if (commandLine != null)
                        {
                            CommandRecievedEventArgs command = JsonConvert.DeserializeObject <CommandRecievedEventArgs>(commandLine);

                            if (command.CommandID.Equals((int)CommandEnum.CloseGui))
                            {
                                string[] args = { JsonConvert.SerializeObject(client) };
                                CommandRecievedEventArgs closeCommand = new CommandRecievedEventArgs((int)CommandEnum.CloseGui, args, "");
                                m_controller.ExecuteCommand(closeCommand.CommandID, closeCommand.Args, out res);
                                m_logging.Log("Client disconnected", Logging.Modal.MessageTypeEnum.WARNING);
                                break;
                            }
                            string result = m_controller.ExecuteCommand(command.CommandID, command.Args, out res);
                            try
                            {
                                //  Thread.Sleep(1000);
                                mtx.WaitOne();
                                writer.WriteLine(result);
                                writer.Flush();
                                mtx.ReleaseMutex();
                            } catch (Exception e)
                            {
                                m_logging.Log("Client disconnected", Logging.Modal.MessageTypeEnum.WARNING);
                                RemoveClient?.Invoke(client);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        return;
                    }
                }
            }).Start();
        }
コード例 #12
0
        /// <summary>
        /// sends App.config content and all existing logs to the client
        /// </summary>
        /// <param name="writer">a writer that writes to a client</param>
        private void SendInitialInfo(BinaryWriter writer)
        {
            bool   res1, res2;
            string configs = m_controller.ExecuteCommand(
                (int)CommandEnum.GetConfigCommand, null, out res1);
            string logs = m_controller.ExecuteCommand(
                (int)CommandEnum.GetLogCommand, null, out res2);

            if (res1 && res2)
            {
                SendDataToClient(configs, writer);
                SendDataToClient(logs, writer);
            }
        }
コード例 #13
0
        private void FileCreatedEvent(object sender, System.IO.FileSystemEventArgs e)
        {
            m_Logger.Log($"File created name: {e.Name} @ {m_Path}", MessageTypeEnum.INFO);
            string[] extensions = { ".jpg", ".png", ".gif", ".bmp" };
            var      ext        = (Path.GetExtension(e.FullPath) ?? string.Empty).ToLower();

            if (extensions.Any(ext.Equals))
            {
                m_Logger.Log($"Image file extention detectet: {ext}, \nProcessing..", MessageTypeEnum.INFO);
                bool     commandResult = false;
                string[] args          = { e.FullPath, e.Name };
                string   resultInfo    = m_Controller.ExecuteCommand(1, args, out commandResult);
                if (false == commandResult)
                {
                    m_Logger.Log($"Command #1 failed with error: {resultInfo}", MessageTypeEnum.FAIL);
                }

                else
                {
                    m_Logger.Log($"Command 1 success - info: {resultInfo}", MessageTypeEnum.INFO);
                }
            }

            else
            {
                m_Logger.Log($"Not watching {ext} files.", MessageTypeEnum.INFO);
            }
        }
コード例 #14
0
        /// <summary>
        /// OnCommandRecieved function, once we recieved the command we will execute it.
        /// </summary>
        /// <param name="sender">Who sent the command</param>
        /// <param name="e">Arguments of command - id, args</param>
        public void OnCommandRecieved(object sender, CommandRecievedEventArgs e)
        {
            bool   resultSuccesful;
            string msg;

            //When running with parameter * it means we want for all so we will do this specific command for this specific handler
            if (e.Args[0].Equals("*"))
            {
                e.Args[0] = this.m_path;
            }
            //First we will excecute the command
            msg = m_controller.ExecuteCommand(e.CommandID, e.Args, out resultSuccesful);
            //Than we will write into the logger - we will use our boolean in order to know if succeeded or not
            if (resultSuccesful)
            {
                m_logging.Log(msg, MessageTypeEnum.INFO);
            }
            //Did not succeed
            else
            {
                m_logging.Log(msg, MessageTypeEnum.FAIL);
            }

            //Return the argument to * for the next handlers
            e.Args[0] = "*";
        }
コード例 #15
0
        /// <summary>
        /// Invoking this function every time a new file is added to the watched folder
        /// </summary>
        /// <param name="sender">
        /// The invoker
        /// </param>
        /// <param name="e">
        /// Event arguments
        /// </param>
        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            string[] path      = { e.FullPath };
            string[] filters   = { ".jpg", ".png", ".gif", ".bmp" };
            string   extension = Path.GetExtension(e.FullPath);

            // Checking if the new file is an image we should handle
            foreach (string f in filters)
            {
                // If so we'll execute the new fille command and logg approptiatly
                if (extension.Equals(f, StringComparison.InvariantCultureIgnoreCase) && File.Exists(path[0]))
                {
                    Thread.Sleep(100);
                    string msg = m_controller.ExecuteCommand((int)CommandEnum.NewFileCommand, path, out bool result);
                    if (result)
                    {
                        m_logging.Log("file in new path:" + msg, MessageTypeEnum.INFO);
                    }
                    else
                    {
                        m_logging.Log("could not move new file. reason: " + msg, MessageTypeEnum.FAIL);
                    }
                }
            }
        }
コード例 #16
0
ファイル: DirectoyHandler.cs プロジェクト: Gotesu/AP2-ex1
 /// <summary>
 /// The function executes a given command ussing the controller.
 /// </summary>
 /// <param name="CommandID">An command enum</param>
 /// <param name="args">Arguments for the command</param>
 private void ExecuteCommand(int CommandID, string[] args)
 {
     // the task
     Task t = Task.Run(() =>
     {
         // update runnig tasks value
         lock (tLock)
             m_tasks++;
         string commandName = Enum.GetName(typeof(CommandEnum), CommandID);
         // update logger of new command
         m_logging.Log("DirectoyHandler received a " + commandName,
                       MessageTypeEnum.INFO);
         bool check;
         // execute the command
         string message = m_controller.ExecuteCommand(CommandID, args, out check);
         // update logger with the result (success or failure)
         if (check)
         {
             m_logging.Log("DirectoyHandler done with " + commandName,
                           MessageTypeEnum.INFO);
         }
         else
         {
             m_logging.Log(message, MessageTypeEnum.FAIL);
         }
         // update runnig tasks value
         lock (tLock)
             m_tasks--;
     });
 }
コード例 #17
0
        public void OnCommandRecieved(object sender, CommandRecievedEventArgs e)
        {
            Task task = new Task(() =>
            {
                bool success;           // Indication if the Command Was Successful
                // If The Command is directed to the given Path
                if (e.RequestDirPath.Equals("*") || e.RequestDirPath.Equals(m_path))
                {
                    // If The User Wishes to close the file
                    if (e.CommandID == (int)CommandEnum.CloseCommand)
                    {
                        if (m_dirWatcher != null)
                        {
                            m_dirWatcher.EnableRaisingEvents = false;
                        }
                        DirectoryClose?.Invoke(this, new DirectoryCloseEventArgs(m_path,
                                                                                 String.Format(MessageInfrastructure.INFO_CloseCommand, m_path)));
                        // Invoking the Server Close
                    }
                    // Logging the Command Being Recieved
                    m_logging.Log(String.Format(MessageInfrastructure.INFO_RecievedCommand, e.CommandID,
                                                String.Join(",", e.Args)), Logging.Modal.MessageTypeEnum.INFO);

                    // Execute command
                    string result = m_controller.ExecuteCommand(e.CommandID, e.Args, out success);

                    MessageTypeEnum type = (success) ? MessageTypeEnum.INFO : MessageTypeEnum.FAIL;

                    m_logging.Log(String.Format(MessageInfrastructure.INFO_SuccessfulCommand, e.CommandID,
                                                String.Join(",", e.Args), result), type);
                }
            });

            task.Start();
        }
コード例 #18
0
        /// <summary>
        /// when file created
        /// </summary>
        /// <param name="source">event caller</param>
        /// <param name="e">the created file</param>
        public void OnChanged(object source, FileSystemEventArgs e)
        {
            // check if file is an image
            // if it is, backup
            logger.Log("New file detected in \"" + dirPath + "\"", MessageTypeEnum.L_INFO);
            if (!filters.Contains(Path.GetExtension(e.FullPath)))
            {
                logger.Log("File \"" + Path.GetFileName(e.FullPath) + "\" isnt an image",
                           MessageTypeEnum.L_INFO);
                return;
            }
            logger.Log("Backup \"" + Path.GetFileName(e.FullPath) + "\" is an image",
                       MessageTypeEnum.L_INFO);
            ExitCode status = controller.ExecuteCommand(Command.BackupFile, new string[] { e.FullPath });

            if (status != ExitCode.Success)
            {
                logger.Log("Failed to back up \"" + Path.GetFileName(e.FullPath) + "\" reson of failuer: " +
                           GetFailedReson(status), MessageTypeEnum.L_FAIL);
            }
            else
            {
                logger.Log("Successfully Backup \"" + Path.GetFileName(e.FullPath) + "\" and created thumbnail",
                           MessageTypeEnum.L_INFO);
            }
        }
コード例 #19
0
        /// <summary>
        /// When a command comes- checks what kind it is: if closing- its closes the service,
        /// otherwise its calls to ExecuteCommand and writes to the log sucsess\failure
        /// </summary>
        /// <param name="sender">the object called to the event</param>
        /// <param name="e">the event args required for this event</param>
        public void OnCommandRecieved(object sender, CommandRecievedEventArgs e)
        {
            bool   result;
            string message;

            if (e.CommandID == (int)CommandEnum.CloseCommand)
            {
                if (e.RequestDirPath.Equals("*") || e.RequestDirPath.Equals(m_path))
                {
                    m_dirWatcher.EnableRaisingEvents = false;
                    DirectoryCloseEventArgs dirCloseArgs = new DirectoryCloseEventArgs(m_path, "CLOSE");
                    DirectoryClose?.Invoke(this, dirCloseArgs);
                }
                return;
            }
            else
            {
                if (m_path == null || !e.RequestDirPath.Contains(m_path))
                {
                    return;
                }

                message = m_controller.ExecuteCommand(e.CommandID, e.Args, out result);
            }

            // write to the log
            if (result)
            {
                m_logging.Log(message, MessageTypeEnum.INFO);
            }
            else
            {
                m_logging.Log(message, MessageTypeEnum.FAIL);
            }
        }
コード例 #20
0
ファイル: ImageService.cs プロジェクト: giladmadmon/image_ex4
        /// <summary>
        /// Called when [server data recieved].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Communication.Model.Event.DataReceivedEventArgs"/> instance containing the event data.</param>
        private void OnServerDataRecieved(object sender, Communication.Model.Event.DataReceivedEventArgs <string> e)
        {
            CommandMessage cmdMsg = CommandMessage.FromJSON(e.Data);
            IClientCommunicationChannel <string> receiver = (IClientCommunicationChannel <string>)sender;
            string msg = null;

            if (cmdMsg.CmdId == CommandEnum.CloseClientCommand)
            {
                receiver.Close();
            }
            else if (cmdMsg.CmdId == CommandEnum.CloseCommand)
            {
                m_imageServer.sendCommand(CommandEnum.CloseCommand, new string[] { }, cmdMsg.Args[0]);
                ServerCommunication.Instance.Send(new CommandMessage(CommandEnum.CloseCommand, cmdMsg.Args).ToJSON());
            }
            else
            {
                bool result;
                msg = m_controller.ExecuteCommand((int)cmdMsg.CmdId, cmdMsg.Args, out result);
            }

            if (msg != null)
            {
                receiver.Send(msg);
            }
        }
コード例 #21
0
        /************************************************************************
         * The Input: a sender and an event.
         * The Output: -.
         * The Function operation: The function runs when a new file is being watched.
         *************************************************************************/
        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            string[] path = { e.FullPath };
            //Possible endings for images.
            string[] filters   = { ".jpg", ".png", ".gif", ".bmp" };
            string   extension = Path.GetExtension(e.FullPath);
            bool     result;

            //Checking whether the new file is an image we should handle.
            foreach (string f in filters)
            {
                // If it is we'll execute the new file command and logg accordingly.
                if (extension.Equals(f, StringComparison.InvariantCultureIgnoreCase))
                {
                    Thread.Sleep(100);
                    string msg = m_controller.ExecuteCommand((int)CommandEnum.NewFileCommand, path, out result);
                    if (result)
                    {
                        m_logging.Log("file in new path:" + msg, MessageTypeEnum.INFO);
                    }
                    else
                    {
                        m_logging.Log("Error in moving the new file. Reason: " + msg, MessageTypeEnum.FAIL);
                    }
                }
            }
        }
コード例 #22
0
        /// <summary>
        ///     Handles the client.
        /// </summary>
        public void HandleClient()
        {
            new Task(() =>
            {
                try
                {
                    while (true)
                    {
                        string commandLine  = _reader.ReadString();
                        string[] parameters = commandLine.Split('|');
                        string retval       = _imageController.ExecuteCommand(
                            (CommandEnum)Enum.Parse(typeof(CommandEnum), parameters[0]),
                            parameters.Skip(1).ToArray(), out EventLogEntryType _);

                        if (retval == null)
                        {
                            continue;
                        }

                        _writer.Write(parameters[0] + "|" + retval);
                        _writer.Flush();
                    }
                }
                catch (Exception)
                {
                    GuiClientClosed?.Invoke(this, null);
                    _loggingService.Log("Client Closed", EventLogEntryType.Error);
                }
            }).Start();
        }
コード例 #23
0
        /// <summary>
        /// this method responsible on command recieved.
        /// </summary>
        /// <param name="sender">the object that send the event</param>
        /// <param name="e">event args</param>
        public void OnCommandRecieved(object sender, CommandRecievedEventArgs e)
        {
            m_logging.Log("On Command Recieved", MessageTypeEnum.INFO);
            {
                bool isSuccess;
                if (e.CommandID == (int)CommandEnum.CloseCommand)
                {
                    m_logging.Log("Close command execute in handler", MessageTypeEnum.INFO);
                    closeHandler();
                    return;
                }

                if (e.RequestDirPath.Equals(this.m_path))
                {
                    string msg = m_controller.ExecuteCommand(e.CommandID, e.Args, out isSuccess);
                    if (isSuccess)
                    {
                        m_logging.Log(msg, MessageTypeEnum.INFO);
                    }
                    else
                    {
                        m_logging.Log("Error on execute command: " + msg, MessageTypeEnum.FAIL);
                    }
                }
            }
        }
コード例 #24
0
        /// <summary>
        /// c'tor
        /// </summary>
        /// <param name="m_controller"></param> to execute commands from its dictionary
        /// <param name="m_logging"></param> to send logs
        public ImageServer(IImageController m_controller, ILoggingService m_logging)
        {
            this._mController = m_controller;
            this._mLogging    = m_logging;
            string[] directories = (ConfigurationManager.AppSettings.Get("Handler").Split(';'));
            foreach (string dir in directories)
            {
                if (Directory.Exists(dir))
                {
                    createHandler(dir);
                }
                else
                {   // if dir is not exists
                    bool     result;
                    string[] args = { dir };
                    m_controller.ExecuteCommand((int)CommandEnum.CloseCommand, args, out result);
                    m_logging.Log("Not such file or directory: " + dir, MessageTypeEnum.WARNING);
                }
            }

            // get comunication details to connect the server
            string ip   = ConfigurationManager.AppSettings.Get("Ip");
            int    port = Int32.Parse(ConfigurationManager.AppSettings.Get("Port"));

            serverChannel                 = new TcpServerChannel(port, ip);
            serverChannel.NewHandler     += OnNewClient;        // for new client
            ClientHandler.MessageRecived += GetMessageFromUser; // for msg from the user
            serverChannel.Start();
        }
コード例 #25
0
 /// <summary>
 /// This method is called when command is received.
 /// </summary>
 /// <param name="sender">The command sender.</param>
 /// <param name="e">The command's arguments.</param>
 public void OnCommandRecieved(object sender, CommandRecievedEventArgs e) // The Event that will be activated upon new Command
 {                                                                        //checking if our path is the one the server intended to handle the command
     if (e.RequestDirPath.Equals(m_path) || e.RequestDirPath.Equals("*")) // Equals compares content
     {
         // if CloseCommand
         if (e.CommandID == (int)CommandEnum.CloseCommand) // == better for numbers
         {
             m_dirWatcher.EnableRaisingEvents = false;     // stop watching.
             string exitMsg = "Stoped handling the directory in path: " + m_path;
             DirectoryCloseEventArgs directoryCloseEventArgs = new DirectoryCloseEventArgs(m_path, exitMsg);
             DirectoryClose?.Invoke(this, directoryCloseEventArgs);
         }
         else // if other command
         {
             bool   success;
             string msg = m_controller.ExecuteCommand(e.CommandID, e.Args, out success);
             if (success)
             {
                 m_logging.Log(msg, MessageTypeEnum.INFO);
             }
             else
             {
                 m_logging.Log(msg, MessageTypeEnum.FAIL);
             }
         }
     }
 }
コード例 #26
0
        public void HandleClient(IClientWrapper client)
        {
            Task task = new Task(() => {
                try
                {
                    while (true)
                    {
                        string message = client.Read();
                        if (message == null)
                        {
                            client.Close();
                            break;
                        }
                        long length        = message.Length;
                        CommandMessage cmd = CommandMessage.FromJSONString(message);
                        bool result;
                        string newMessage = m_controller.ExecuteCommand((int)cmd.Type, cmd.Args, out result);
                        if (result)
                        {
                            client.Write(newMessage);
                        }
                    }
                } catch (IOException ex)
                {
                    client.Close();
                }
            });

            task.Start();
        }
コード例 #27
0
        public void HandleClient(TcpClient client)
        {
            //create a task witch will listen to  client command and execute them.
            new Task(() =>
            {
                try
                {
                    NetworkStream stream = client.GetStream();
                    BinaryReader reader  = new BinaryReader(stream);
                    BinaryWriter writer  = new BinaryWriter(stream);

                    string commandLine = "";
                    while (!commandLine.Equals("Close Client"))
                    {
                        //read first message from client.
                        commandLine = reader.ReadString();
                        if (commandLine.Equals("Close Client"))
                        {
                            break;
                        }
                        bool check;
                        string[] command = commandLine.Split(':');
                        //execute command
                        string result = m_controller.ExecuteCommand(Int32.Parse(command[0]), command, out check);
                        //send to client the result of the command
                        writer.Write(result);
                    }
                    //if client closed
                    client.Close();
                } catch (Exception)
                {
                    client.Close();
                }
            }).Start();
        }
コード例 #28
0
        /// <summary>
        /// Handles the <see cref="E:CommandRecieved" /> event.
        /// A command from the server, for now - just "close" command
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">An EventArgs that contains the event data.</param>
        public void OnCommandReceived(object sender, CommandReceivedEventArgs e)
        {
            bool result;

            //check if command is meant for its directory,
            //if yes – handle command (for now will just be to close handler)};
            if (e.RequestDirPath.Equals(m_path) || e.RequestDirPath.Equals("*"))
            {
                //check if the command is close
                if (e.CommandID == (int)CommandEnum.RemoveHandler)
                {
                    //close
                    closeHandler();
                }

                else
                {
                    // the string will return the new path if result = true,
                    //and will return the error message if the result = false
                    string resultOfCommand = m_controller.ExecuteCommand(
                        e.CommandID, e.Args, out result);

                    if (result == false)
                    {
                        m_logging.Log(resultOfCommand, MessageTypeEnum.FAIL);
                    }
                    else
                    {
                        m_logging.Log("copy image from " + m_path + " to "
                                      + resultOfCommand + " successes", MessageTypeEnum.INFO);
                    }
                }
            }
        }
コード例 #29
0
        /*********************************************************************/
        //check if command is meant for its directory, if yes – handle command(for now will just be to close handler)
        public void OnCommandRecieved(object sender, CommandRecievedEventArgs e)
        {
            FileSystemEventArgs e2 = null;

            if (watcher.Path.CompareTo(e.RequestDirPath) == 0)
            {
                if (e.CommandID == 1)
                {
                    closeHandler(e.RequestDirPath);
                    m_logging.Log("closeHandler command recieved " + e.RequestDirPath, MessageTypeEnum.INFO);
                }
                else
                {
                    bool     result;
                    FileInfo file = new FileInfo(e2.FullPath);
                    //send command to controller to add a file
                    string[] args = { e2.FullPath, file.Name };
                    m_controller.ExecuteCommand(CommandEnum.NewFileCommand, args, out result);
                    if (result == true)
                    {
                        //notify logger on success
                        m_logging.Log("added file " + file.Name + " succesfully", MessageTypeEnum.INFO);
                    }
                    else           //notify logger on failure
                    {
                        m_logging.Log("ERROR: faild to add  " + file.Name + "  file", MessageTypeEnum.INFO);
                    }
                    // Specify what is done when a file is changed, created, or deleted.
                }
            }
        }
コード例 #30
0
        /// <summary>
        /// Creating a thumbnail directory if missing and adding a thumbnail and its nessecery folders
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        public void CreateThumbnail(object source, FileSystemEventArgs e)
        {
            string strFileExt = Path.GetExtension(e.FullPath);

            m_logging.Log(strFileExt, MessageTypeEnum.INFO);
            // filter file types ignoring folders
            switch (strFileExt)
            {
            case @".jpg":
                break;

            case @".png":
                break;

            case @".bmp":
                break;

            case @".gif":
                break;

            default:
                return;
            }
            m_logging.Log("started creating thumbnail", MessageTypeEnum.INFO);
            bool result;

            string [] args = new string[3];
            args[0] = e.FullPath;
            //creting a filestream in order to copy the file
            FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read);

            try
            {
                //getting the time and date of the image
                DateTime dt = GetDateTakenFromImage(fs);
                m_logging.Log("date taken from image", MessageTypeEnum.INFO);

                args[1] = dt.Year.ToString();
                args[2] = dt.Month.ToString();
            } catch (Exception exce)
            {
                // in case the image has no date
                m_logging.Log("No Available Date", MessageTypeEnum.FAIL);
                args[1] = "Default";
                args[2] = "Default";
            }
            //closing the image
            fs.Close();
            fs.Dispose();
            try
            {
                //execute the command
                m_logging.Log(m_controller.ExecuteCommand(1, args, out result), MessageTypeEnum.INFO);
            } catch (Exception errors)
            {
                //incase there was an error int adding the file
                m_logging.Log(errors.ToString(), MessageTypeEnum.FAIL);
            }
        }