Exemplo n.º 1
0
        private static void Addimgs(IImageController imageController)
        {
            imageController.NewImage("img1", "descr1", "url1", "birthday");
            imageController.ChangeImageName(1, "newName1");

            imageController.NewImage("img2", "descr2", "url2", "wedding");
            imageController.ChangeImageName(2, "newName2");
        }
Exemplo n.º 2
0
 /// <summary>
 /// constructor.
 /// </summary>
 /// <param name="controller">controller</param>
 /// <param name="logging"> logger</param>
 public AppServer(IImageController controller, ILoggingService logging)
 {
     try
     {
         this.m_controller = controller;
         this.m_logging    = logging;
         //establish a tcp connection
         IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8200);
         this.tcpListener = new TcpListener(ep);
         this.tcpListener.Start();
     }
     catch (Exception e) { this.m_logging.Log("Couldn't establish app server: " + e.ToString(), MessageTypeEnum.FAIL); }
     this.m_logging.Log("Tcp App - server established: ", MessageTypeEnum.INFO);
     this.clientsList = new List <TcpClient>();
     AcceptClients();
 }
        /************************************************************************
         * The Input: -.
         * The Output: -.
         * The Function operation: The function reads from the appConfig and initiallizes
         * and creates members.
         *************************************************************************/
        private void InitializeService()
        {
            //Reading appConfig.
            string[] handlerPaths  = ConfigurationManager.AppSettings["Handler"].Split(';');
            string   outputDir     = ConfigurationManager.AppSettings["OutputDir"];
            int      thumbnailSize = Int32.Parse(ConfigurationManager.AppSettings["ThumbnailSize"]);

            //Initializing and creating the members.
            this.model               = new ImageServiceModel(outputDir, thumbnailSize);
            this.logging             = new LoggingService();
            this.controller          = new ImageController(this.model);
            logging.MessageReceived += OnLog;
            this.m_imageServer       = new ImageServer(this.controller, this.logging, handlerPaths);
            //Updating the entry.
            eventLog1.WriteEntry("End Of Initialization");
        }
Exemplo n.º 4
0
        /// <summary>
        /// ServerConnection Constructor
        /// </summary>
        /// <param name="img_ctrl">The m controller.</param>
        /// <param name="log_service">The m logging.</param>
        /// <param name="port">The port.</param>
        public ServerConnection(IImageController img_ctrl, ILoggingService log_service, int port)
        {
            //sets image controller and log service
            this.img_controller      = img_ctrl;
            this.logging_service     = log_service;
            log_service.NewLogEntry += UpdateLog;
            this.server_port         = port;

            //Creates a new client handler
            this.client_handler         = new ClientHandler(log_service);
            this.client_handler.M_mutex = model_mutex;

            //sets the server as running
            this.server_stopped = false;
            this.clients_list   = new ObservableCollection <TcpClient>();
        }
Exemplo n.º 5
0
        public ImageListenerManager(ILoggingService logger_, string outputDir, int thumbSize)
        {
            // create controller
            // and check that output dirctory successfully creates
            ExitCode status;
            ImageServiceFileHandler imageServiceFile = new ImageServiceFileHandler(outputDir, thumbSize, out status);

            logger     = logger_;
            controller = new ImageController(imageServiceFile);
            if (status == ExitCode.F_Create_Dir)
            {
                logger.Log("Cannot create output image folder.\nFatal error cannot recover, exiting",
                           Logger.Message.MessageTypeEnum.FAIL);
                Environment.Exit(1);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Sets the logger service.
 /// </summary>
 /// <param name="l">The logger service instance.</param>
 public void SetLoggerService(ILoggingService l)
 {
     this.logging    = l;
     this.controller = new ImageController(new ImageServiceModal(l));
     //set the client handler
     this.ch = new ImageServiceClientHandler(logging, controller);
     //this.ch.SetController(this.controller);
     this.CommandRecieved    += this.ch.OnCommandRecieved;
     this.LogMessageRecieved += this.ch.OnLogMessageRecieved;
     //start listening
     //System.Diagnostics.Debugger.Launch();
     this.Start();
     this.ConnectToImageSocketAndListen();
     this.logging.Log("after start command ctor", MessageTypeEnum.INFO);
     //  this.logging.Log("Hello frm server", ImageService.Logging.Modal.MessageTypeEnum.INFO);
 }
Exemplo n.º 7
0
 /// <summary>
 ///  constructor.
 /// </summary>
 /// <param name="controller">commands controller object.</param>
 /// <param name="logging">logger to pass messages to the log.</param>
 public ImageServer(IImageController controller, ILoggingService logging)
 {
     m_controller = controller;
     m_logging    = logging;
     ch           = new ClientHandler(m_controller, m_logging, this);
     ch.ClientClosedConnectionEvent += delegate(Object sender, ClientEventArgs e)
     {
         CloseAndRemoveClient(e.Client);
         m_logging.Log(Messages.ClientClosedConnection(), MessageTypeEnum.WARNING);
     };
     CreateDirectoryHandlers();
     allClients = new List <TcpClient>();
     serverIsOn = true;
     // TODO: interface
     imagesPort = new ImagesPort(m_logging);
 }
Exemplo n.º 8
0
 /// <summary>
 /// Sends to client.
 /// </summary>
 /// <param name="controller">The controller.</param>
 /// <param name="command">The <see cref="CommandReceivedEventArgs"/> instance containing the event data.</param>
 /// <param name="writer">The writer.</param>
 /// <returns></returns>
 public Boolean SendToClient(IImageController controller, CommandReceivedEventArgs command, BinaryWriter writer)
 {
     try
     {
         bool   result;
         string message = controller.ExecuteCommand(command.CommandID, command.Args, out result);
         M_mutex.WaitOne();
         writer.Write(message);
         M_mutex.ReleaseMutex();
         return(true);
     } catch (Exception e)
     {
         m_logger.Log("Failed to send to client due to: " + e.Message, MessageTypeEnum.FAIL);
         return(false);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// a constructor fore the server, setting a logger, imageservice model and an imange controller,
        /// also a dictionary of commans
        /// </summary>
        /// <param name="m_logging"></param>
        public ImageServer(ILogging m_logging, System.Diagnostics.EventLog eventLog)
        {
            this.logger = m_logging;
            ImageServiceModal iModal = new ImageServiceModal();

            this.imageController = new ImageController(iModal);
            Dictionary <int, ICommand> commandsList = new Dictionary <int, ICommand>()
            {
                { 1, new NewFileCommand(iModal) }
            };

            this.channel = TCPChannel.Instance(80, this.logger, eventLog);
            this.channel.Start();
            this.channel.startSendingLogs += subscribeToSendLogs;
            this.channel.GotCommand       += getCommand;
        }
Exemplo n.º 10
0
        ///<summary>
        ///start the service
        ///</summary>
        protected override void OnStart(string[] args)
        {
            ServiceStatusClass.isRunnig = true;
            m_logger.Log("In OnStart", MessageTypeEnum.INFO);
            // Update the service state to Start Pending.
            ServiceStatus serviceStatus = new ServiceStatus();

            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            serviceStatus.dwWaitHint     = 100000;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);

            // reads from the app config the parameters.
            string OutputFolder =
                ConfigurationManager.AppSettings.Get("OutputDir");
            int ThumbnailSize =
                Int32.Parse(ConfigurationManager.AppSettings.Get("ThumbnailSize"));

            // create the members.
            try
            {
                this.m_modal = new ImageServiceModal(OutputFolder, ThumbnailSize);
            } catch (Exception e)
            {
                m_logger.Log("exception in ImageService create model", MessageTypeEnum.FAIL);
            }


            this.m_controller = new ImageController(this.m_modal, this.m_logger);

            // create the server which will start listening.
            this.m_server = new ImageServer(this.m_controller, this.m_logger);

            //create server for the gui.

            GUIServer.Instance.OnMessageRecived += M_server_OnMessageRecived;
            //this.m_guiServer = new GUIServer(this.m_controller);


            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 60000; // 60 seconds
            timer.Elapsed += new
                             System.Timers.ElapsedEventHandler(this.OnTimer);
            timer.Start();
            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Handles the client.
 /// </summary>
 /// <param name="tcp_client">The client.</param>
 /// <param name="img_controller">The controller.</param>
 /// <param name="clients">The clients.</param>
 public void HandleClient(TcpClient tcp_client, IImageController img_controller, ObservableCollection <TcpClient> clients)
 {
     //creates a new task
     new Task(() =>
     {
         try
         {
             while (true)
             {
                 //creates a stream with reader and writer
                 NetworkStream client_stream = tcp_client.GetStream();
                 BinaryReader b_reader       = new BinaryReader(client_stream);
                 BinaryWriter b_writer       = new BinaryWriter(client_stream);
                 string string_input         = b_reader.ReadString();
                 if (string_input != null)
                 {
                     //Gets the command received
                     CommandReceivedEventArgs cmd = JsonConvert.DeserializeObject <CommandReceivedEventArgs>(string_input);
                     if (cmd.CommandID.Equals((int)CommandEnum.CloseGUI))
                     {
                         //removes the client
                         clients.Remove(tcp_client);
                         tcp_client.Close();
                         break;
                     }
                     else
                     {
                         //sends the arguments to the client
                         if (!this.SendToClient(img_controller, cmd, b_writer))
                         {
                             clients.Remove(tcp_client);
                             tcp_client.Close();
                             break;
                         }
                     }
                 }
             }
         }
         catch (Exception e)
         {
             //In case of an issue, cancels the token
             this.tSource.Cancel();
             model_logging_service.Log("Server Failure: " + e.Message, MessageTypeEnum.FAIL);
         }
     }, this.tSource.Token).Start();
 }
Exemplo n.º 12
0
 /// <summary>
 /// Executes command, uses mutex and sends to client
 /// </summary>
 /// <param name="img_controller">image controller</param>
 /// <param name="command">event data</param>
 /// <param name="binary_writer">binary writer</param>
 /// <returns></returns>
 public Boolean SendToClient(IImageController img_controller, CommandReceivedEventArgs command, BinaryWriter binary_writer)
 {
     try
     {
         bool   send_result;
         string msg = img_controller.ExecuteCommand(command.CommandID, command.Args, out send_result);
         M_mutex.WaitOne();
         binary_writer.Write(msg);
         M_mutex.ReleaseMutex();
         return(true);
     }
     catch (Exception e)
     {
         model_logging_service.Log("Client Sending Failure: " + e.Message, MessageTypeEnum.FAIL);
         return(false);
     }
 }
Exemplo n.º 13
0
        public event EventHandler <CommandRecievedEventArgs> CommandRecieved;          // The event that notifies about a new Command being recieved

        public ImageServer(IImageController m_controller, ILoggingService m_logging)
        {
            this.m_controller = m_controller;
            this.m_logging    = m_logging;
            string[] directories = (ConfigurationManager.AppSettings.Get("Handler").Split(';'));
            foreach (string dir in directories)
            {
                if (Directory.Exists(dir))
                {
                    createHandler(dir);
                }
                else
                {
                    m_logging.Log("Not such file or directory: " + dir, MessageTypeEnum.FAIL);
                }
            }
        }
Exemplo n.º 14
0
 /************************************************************************
  * The Input: ImageController a LoggingService and the way to a handler.
  * The Output: -
  * The Function operation: The function builds a server.
  *************************************************************************/
 public ImageServer(IImageController controller, ILoggingService logging, string[] handlersPath)
 {
     m_controller      = controller;
     m_logging         = logging;
     handlers          = new List <IDirectoryHandler>();
     this.handlersPath = handlersPath;
     //Creating handlers.
     for (int i = 0; i < handlersPath.Length; i++)
     {
         handlers.Add(new DirectoyHandler(this.m_controller, this.m_logging));
         handlers[i].StartHandleDirectory(handlersPath[i]);
         CommandRecieved            += handlers[i].OnCommandRecieved;
         handlers[i].DirectoryClose += OnHandlerClose;
         // Logging each handler into the entry.
         m_logging.Log("Directory Handler created at path:" + handlersPath[i], Logging.Model.MessageTypeEnum.INFO);
     }
 }
Exemplo n.º 15
0
        //Here You will use app config
        /// <summary>
        /// When implemented in a derived class,
        /// executes when a Start command is sent
        /// to the service by the Service Control Manager (SCM)
        /// or when the operating system starts
        /// (for a service that starts automatically).
        /// Specifies actions to take when the service starts.
        /// </summary>
        /// <param name="args">Data passed by the start command.</param>
        protected override void OnStart(string[] args)
        {
            try
            {
                Console.WriteLine("OnStart");

                // Update the service state to Start Pending.
                ServiceStatus serviceStatus = new ServiceStatus();
                serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
                serviceStatus.dwWaitHint     = 100000;
                SetServiceStatus(this.ServiceHandle, ref serviceStatus);
                eventLog1.WriteEntry("In OnStart");
                // Set up a timer to trigger every minute.
                System.Timers.Timer timer = new System.Timers.Timer();
                timer.Interval = 60000; // 60 seconds  //
                timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
                timer.Start();

                // Update the service state to Running.
                serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
                SetServiceStatus(this.ServiceHandle, ref serviceStatus);

                //read from app config
                AppConfig appConfig = new AppConfig();

                //create the LoggingService
                logging = new LoggingService();
                logging.MessageReceivedEvent += onMsg;
                logging.MessageReceivedEvent += LogCommand.onReceiveCommandLog;

                modal = new ImageServiceModal(appConfig.OutPutDir, appConfig.ThumbnailSize, logging);
                //controller = new ImageController(modal, appConfig);
                m_imageServer = new ImageServer(logging, appConfig.ArrHandlers);
                controller    = new ImageController(modal, appConfig, m_imageServer);
                m_imageServer.initImageServer(controller);

                ClientHandler clientHandler = new ClientHandler(controller, logging);
                server = new TCPServerChannel(8000, clientHandler);
                logging.MessageReceivedEvent += server.SendLog;
                server.Start();
            }
            catch (Exception ex)
            {
                eventLog1.WriteEntry(ex.Message);
            }
        }
Exemplo n.º 16
0
        public event EventHandler <CommandRecievedEventArgs> CommandRecieved;          // The event that notifies about a new Command being recieved
        #endregion

        public ImageServer(IImageController controller, ILoggingService logging)
        {
            this.m_controller = controller;
            this.m_logging    = logging;
            string[] directories = (ConfigurationManager.AppSettings.Get("Handler").Split(';'));
            foreach (string path in directories)
            {
                try
                {
                    this.CreateHandler(path);
                }
                catch (Exception ex)
                {
                    this.m_logging.Log("Error while creating handler for directory: " + path + " because:" + ex.ToString(), Logging.Modal.MessageTypeEnum.FAIL);
                }
            }
        }
Exemplo n.º 17
0
        protected override void OnStart(string[] args)
        {
            m_Logger.Log("Starting service.", MessageTypeEnum.INFO);
            // Update the service state to Start Pending.
            ServiceStatus serviceStatus = new ServiceStatus();

            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            serviceStatus.dwWaitHint     = 100000;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);

            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);

            // Creating service components.
            m_Logger.Log("Creating service components.", MessageTypeEnum.INFO);
            m_Model                      = new ImageServiceModel(m_Logger);
            m_Controller                 = new ImageController(m_Model, m_Logger);
            m_ImageServer                = new ImageServer(m_Controller, m_Logger);
            m_Server                     = new NetworkServer(PORT, m_Controller, m_Logger);
            m_Server.ClientConnected    += addClient;
            m_Server.clientDisconnected += removeClient;

            // Create output and thumbnails directories.
            bool   result     = false;
            string outputPath = ImageService.ReadSetting("OutputDir", out result);

            if (false == result)
            {
                m_Logger.Log($"OutputDir attribute cannot be found in appConfig.\nSetting default value.", MessageTypeEnum.INFO);
                outputPath = @"C:\Output";
            }

            this.CreateOutputFolder(outputPath);
            string thumbnailsPath = $@"{outputPath}\Thumbnails";

            this.CreateOutputFolder(thumbnailsPath);

            // Initiate server listenning (Run as task in order to guarentee OnStart method finish).
            Task serverStartTask = new Task(() =>
            {
                m_Server.Start();
            });

            serverStartTask.Start();
        }
Exemplo n.º 18
0
        /// <summary>
        /// ImageService constructor.
        /// </summary>
        /// <param name="args">command line args</param>
        public ImageService(string[] args)
        {
            InitializeComponent();
            info = ConfigInfomation.Instance;
            // for APP.config
            // string outputFolder = ConfigurationManager.AppSettings["OutputDir"];
            //int thumbnailSize = Int32.Parse(ConfigurationManager.AppSettings["ThumbnailSize"]);
            // string eventSourceName = ConfigurationManager.AppSettings["SourceName"];
            // string logName = ConfigurationManager.AppSettings["LogName"];
            string eventSourceName = info.eventSourceName;
            string logName         = info.logName;

            //Change to insert params (if exist)
            //if (args.Count() > 0)
            //{
            //   eventSourceName = args[0];
            //}
            //if (args.Count() > 1)
            //{
            //    logName = args[1];
            //}
            eventLog1 = new System.Diagnostics.EventLog();
            if (!System.Diagnostics.EventLog.SourceExists(eventSourceName))
            {
                System.Diagnostics.EventLog.CreateEventSource(eventSourceName, logName);
            }
            eventLog1.Source = eventSourceName;
            eventLog1.Log    = logName;
            eventLog1.Clear();
            int a = eventLog1.Entries.Count;

            //eventLog1.WriteEntry("Num of entries: " + a, EventLogEntryType.Information, eventId++);
            //eventLog1.WriteEntry("eventId: " + eventId, EventLogEntryType.Information, eventId++);

            // create LoggingService, CurrentRunLog, ImageServiceModal, ImageController
            m_currentLog             = new CurrentRunLog();
            logging                  = new LoggingService();
            logging.MessageRecieved += m_currentLog.AddToLog;  //Write log in CurrentRunLog
            logging.MessageRecieved += eventLog1_EntryWritten; //Write log in entry

            modal      = new ImageServiceModal(ConfigInfomation.Instance.outputDir, ConfigInfomation.Instance.thumbnailSize);
            controller = new ImageController(modal);
            //Adding new option of LogCommand
            controller.insertCommand((int)CommandEnum.LogCommand, new GetCurrentRunLogCommand(m_currentLog));
        }
Exemplo n.º 19
0
        public event EventHandler <CommandRecievedEventArgs> CommandRecieved;          // The event that notifies about a new Command being recieved
        #endregion

        /// <summary>
        /// constructor.
        /// </summary>
        /// <param name="controller">controller</param>
        /// <param name="logging">logger</param>
        public ImageServer(IImageController controller, ILoggingService logging, ICurrentRunLog currentLog)
        {
            m_controller = controller;
            m_logging    = logging;
            m_currentLog = currentLog;
            m_ch         = new ClientHandler(m_controller, m_logging);
            m_tcpserver  = new TCPServer(port, m_ch, m_logging);
            // read from App config and put handlers in array of string.
            // string[] directories = ConfigurationManager.AppSettings.Get("Handler").Split(';');
            foreach (string directoryPath in ConfigInfomation.Instance.handlerPaths)
            {
                // create handler for each path.
                CreateHandler(directoryPath);
            }
            m_controller.SpecialCommanndAppeared += SendCommand;
            // m_controller.SpecialCommanndAppeared += PassLog;
            // m_logging.MessageRecieved += m_ch.UpdateClientsNewLog;
        }
Exemplo n.º 20
0
        public ImageServer(IImageController i_Controller, ILoggingService i_Logger)
        {
            m_Logger              = i_Logger;
            m_Controller          = i_Controller;
            m_DirectoriesHandlers = new List <DirectoyHandler>();

            bool   result             = false;
            string watchedDirectories = ImageService.ReadSetting("Handler", out result);

            string[] directories = watchedDirectories.Split(';');
            foreach (string path in directories)
            {
                DirectoyHandler directoryHandler = new DirectoyHandler(path, m_Controller, this, m_Logger);
                m_DirectoriesHandlers.Add(directoryHandler);
                directoryHandler.StartHandleDirectory();
            }

            m_Logger.Log("Image Server Created.", MessageTypeEnum.INFO);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="IManagerOfHandlers"/> class.
        /// </summary>
        /// <param name="l">The logging service.</param>
        /// <param name="c">The controller.</param>
        public ImageServerManagerOfHandlers(ILoggingService l, IImageController c)
        {
            this.log        = l;
            this.controller = c;
            //initialize handlers list
            this.handler = new List <IDirectoryHandler>();
            //create the handler and sign the onClose method to the event
            string folderToListen = ConfigurationManager.AppSettings.Get("Handler");

            string[] folders = folderToListen.Split(';');
            //create handlers for each folder:
            foreach (string folder in folders)
            {
                if (Directory.Exists(folder))
                {
                    this.CreateHandlerForFolder(folder);
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Constractor.
        /// </summary>
        /// <param name="imageServer">The image server .</param>
        /// <param name="client"> The tcp client. </param>
        /// <param name="m_controller"> The image controller.</param>
        public HandleSettings(ImageServer imageServer, TcpClient client, IImageController m_controller)
        {
            imageServer.writeSocket(imageServer.AppConfigText(), client);
            NetworkStream ns = client.GetStream();

            //string r = imageServer.readSocket(ns);

            if (client.Connected)
            {
                while (true)
                {
                    string   command = imageServer.readSocket(ns);
                    string[] split   = command.Split('$');
                    int      id      = 0;
                    bool     t       = true;

                    if (split[0] == "Exit Server")
                    {
                        break;
                    }
                    if (split[0] == "CloseCommand")
                    {
                        id = (int)CommandEnum.CloseCommand;
                        imageServer.delete_handler(split[1]);
                        m_controller.ExecuteCommand(id, split, out t);
                    }
                    if (split[0] == "Exit Server")
                    {
                        break;
                    }

                    if (!client.Connected)
                    {
                        break;
                    }

                    if (!client.Connected)
                    {
                        break;
                    }
                }
            }
        }
Exemplo n.º 23
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="loggingService">Log</param>
 /// <param name="imageController">Controller</param>
 public ImageServer(ILoggingService loggingService, IImageController imageController)
 {
     this.m_controller           = imageController;
     this.m_logging              = loggingService;
     this.clientsReadyForNewLogs = new Dictionary <TcpClient, bool>();
     // this.m_logging.MessageRecieved += this.NewLogEntry;
     string[] arr = ConfigurationManager.AppSettings["Handler"].Split(';');
     dirPaths = new List <string>(arr);
     //Creates the direcory handlers for each directory path recieved.
     m_logging.Log("Image server was created, making handlers now", MessageTypeEnum.INFO);
     foreach (string path in dirPaths)
     {
         if (Directory.Exists(path))
         {
             m_logging.Log("Creating handler for :" + path, MessageTypeEnum.INFO);
             this.CreateHandler(path);
         }
     }
 }
Exemplo n.º 24
0
        /// <summary>ImageService Cntr.</summary>
        /// <param name="args">Arguments from command line</param>
        public ImageService(string[] args)
        {
            //Trying to inialize the ImageService members
            try
            {
                InitializeComponent();
                //Getting details from AppConfig
                string log        = ConfigurationManager.AppSettings.Get("LogName");
                string sourceName = ConfigurationManager.AppSettings.Get("SourceName");
                //Setting the current log
                eventLog1 = new System.Diagnostics.EventLog();

                //Checks if the source name exists actually
                if (!System.Diagnostics.EventLog.SourceExists(sourceName))
                {
                    //Creates an event sourcename
                    System.Diagnostics.EventLog.CreateEventSource(sourceName, log);
                }
                //Sets for the log the sourcename and log name
                eventLog1.Source = sourceName;
                eventLog1.Log    = log;
                //Creating new class members
                this.logging = new LoggingService();
                //Adding the writing message function
                this.logging.MessageRecieved += WriteMessage;
                this.modal = new ImageServiceModal()
                {
                    //Sets the new output directory
                    OutputFolder = ConfigurationManager.AppSettings.Get("OutputDir"),
                    //Gets the config for thumbnail size
                    ThumbnailSize = Int32.Parse(ConfigurationManager.AppSettings.Get("ThumbnailSize"))
                };
                //Sets the new controller and image server
                this.controller    = new ImageController(this.modal);
                this.m_imageServer = new ImageServer(this.controller, this.logging);
            }

            //Catches the exception if any exception was thrown in the process and prints it
            catch (Exception e)
            {
                this.eventLog1.WriteEntry(e.ToString(), EventLogEntryType.Error);
            }
        }
Exemplo n.º 25
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="controller">Image controller.</param>
 /// <param name="logging">Logging</param>
 /// <param name="handlersPathes">Handlera pathes.</param>
 public ImageServer(IImageController controller, ILoggingService logging, string[] handlersPathes)
 {
     Controller = controller;
     Logging    = logging;
     m_handlers = new List <IDirectoryHandler>();
     //For each path in handlers pathes.
     foreach (var path in handlersPathes)
     {
         //Write to log.
         m_logging.Log("Creating handler for: " + path, MessageTypeEnum.INFO);
         //Create handler.
         IDirectoryHandler handler = new DirectoyHandler(m_controller, m_logging, path);
         m_handlers.Add(handler);
         //Add events.
         CommandRecieved += handler.OnCommandRecieved;
         CloseServer     += handler.CloseHandler;
         //Start handle directory.
         handler.StartHandleDirectory(path);
     }
 }
Exemplo n.º 26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DirectoyHandler"/> class.
        /// </summary>
        /// <param name="p">The path to the directory it takes care.</param>
        /// <param name="m">imagecontroller object</param>
        /// <param name="l">a logging service</param>
        public DirectoyHandler(string p, IImageController m, ILoggingService l)
        {
            this.path       = p;
            this.controller = m;
            this.logging    = l;
            this.dirWatcher = new FileSystemWatcher();
            //this.logging.Log("Hello frm handler", ImageService.Logging.Modal.MessageTypeEnum.INFO);
            this.InitializeWatcher();
            this.DirectoryClose += this.controller.OnCloseOfService;
            this.handlers        = new List <String>();
            //create the handler and sign the onClose method to the event
            string folderToListen = ConfigurationManager.AppSettings.Get("Handler");

            string[] folders = folderToListen.Split(';');
            //create handlers for each folder:
            foreach (string folder in folders)
            {
                this.handlers.Add(folder);
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageServer"/> class.
        /// </summary>
        /// <param name="controller">The controller.</param>
        /// <param name="logging">The logging.</param>
        public ImageServer(IImageController controller, ILoggingService logging)
        {
            this.m_controller = controller;
            this.m_logging    = logging;
            this.handlersList = new LinkedList <IDirectoryHandler>();

            string sourceDir = ConfigurationManager.AppSettings.Get("Handler");

            string[] directories = sourceDir.Split(';');
            foreach (var dir in directories)
            {
                IDirectoryHandler handler = new DirectoryHandler(this.m_controller, this.m_logging);
                this.handlersList.AddLast(handler);
                // start listen to the directory
                handler.StartHandleDirectory(dir);
                this.m_logging.Log("handler for " + dir + " was created", Logging.Modal.MessageTypeEnum.INFO);
                CommandRecieved        += handler.OnCommandRecieved;
                handler.DirectoryClose += onClose;
            }
        }
Exemplo n.º 28
0
 /// <summary>
 /// Handles the client.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="controller">The controller.</param>
 /// <param name="clients">The clients.</param>
 public void HandleClient(TcpClient client, IImageController controller, ObservableCollection <TcpClient> clients)
 {
     new Task(() =>
     {
         try
         {
             while (true)
             {
                 NetworkStream stream = client.GetStream();
                 BinaryReader reader  = new BinaryReader(stream);
                 BinaryWriter writer  = new BinaryWriter(stream);
                 bool result;
                 string input = reader.ReadString();
                 if (input != null)
                 {
                     CommandReceivedEventArgs commandReceived = JsonConvert.DeserializeObject <CommandReceivedEventArgs>(input);
                     if (commandReceived.CommandID.Equals((int)CommandEnum.CloseGUI))
                     {
                         clients.Remove(client);
                         client.Close();
                         break;
                     }
                     else
                     {
                         if (!this.SendToClient(controller, commandReceived, writer))
                         {
                             clients.Remove(client);
                             client.Close();
                             break;
                         }
                     }
                 }
             }
         }
         catch (Exception e)
         {
             this.tokenSource.Cancel();
             m_logger.Log("Server failed due to: " + e.Message, MessageTypeEnum.FAIL);
         }
     }, this.tokenSource.Token).Start();
 }
Exemplo n.º 29
0
      /// <summary>
      /// executes when Start command is sent to the service by the SCM
      /// </summary>
      /// <param name="args">Data passed by the start command (null in our case).</param>
      protected override void OnStart(string[] args)
      {
          logging = new LoggingService();

          //Reads parameters from app.config
          string logSource = ConfigurationManager.AppSettings["SourceName"];
          string logName   = ConfigurationManager.AppSettings["LogName"];

          string[] handlers      = ConfigurationManager.AppSettings["Handler"].Split(';');
          string   outputDir     = ConfigurationManager.AppSettings["OutputDir"];
          string   thumbnailSize = ConfigurationManager.AppSettings["ThumbnailSize"];

          // Creating a new Settings object with the info above
          Settings settings = new Settings()
          {
              Handlers      = new System.Collections.ObjectModel.ObservableCollection <string>(handlers),
              LogName       = logName,
              LogSource     = logSource,
              OutputDir     = outputDir,
              ThumbnailSize = thumbnailSize
          };

          LogContainer.CreateLog(logSource, logName);

          //adds the eventLog OnMsg method to the logging service event.
          logging.MessageReceived += OnMsg;


          //creates modal, controller and ImageServer
          modal         = new ImageServiceModal(outputDir, int.Parse(thumbnailSize));
          controller    = new ImageController(modal);
          m_imageServer = new ImageServer(settings.Handlers, logging, controller);

          //creates desktop client handler and server for handling the tcp connection
          ImageService.ImageService.Server.IClientHandler ch     = new ImageService.ImageService.Server.AndroidAppHandler(settings, logging);
          ImageService.ImageService.Server.Server         server = new ImageService.ImageService.Server.Server(8000, ch);
          server.Start();

          logging.Log("ImageService started", MessageTypeEnum.INFO);
          logging.Log(outputDir, MessageTypeEnum.ERROR);
      }
        /// <summary>
        /// Funtion happens when service starts
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            // Update the service state to Start Pending.
            ServiceStatus serviceStatus = new ServiceStatus();

            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            serviceStatus.dwWaitHint     = 100000;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);


            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;
            SetServiceStatus(this.ServiceHandle, ref serviceStatus);

            // get OutputDir path and Thumbnail size from app config
            string outputFolder = ConfigurationManager.AppSettings["OutputDir"];
            int    size         = int.Parse(ConfigurationManager.AppSettings["ThumbnailSize"]);


            //create logging modal and add to event
            this.logging             = new LoggingService();
            logging.MessageRecieved += onMessage;

            //create server and client handler
            this.clientHandler = new ByteClinetHandler();
            this.server        = new Communication.Server(8000, clientHandler);
            // create image modal, controller and image server
            this.modal         = new ImageServiceModal(outputFolder, size, logging);
            this.controller    = new ImageController(modal, logging, clientHandler);
            this.m_imageServer = new ImageServer(this.logging, this.controller);

            //sign to events
            this.clientHandler.ClientHandlerCommandRecieved     += ClientHandlerCommandRecievedHandle;
            this.clientHandler.ClientHandlerCommandRecievedByte += ClientHandlerCommandRecievedHandleByte;
            server.newConnection += newConnectionHandler;

            logging.Log("In OnStart", MessageTypeEnum.INFO);
            this.logging.Log(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(), MessageTypeEnum.INFO);
            //start server
            server.Start();
        }
Exemplo n.º 31
0
        /// <summary>
        /// c'tor instelize all members from arguments of app config
        /// </summary>
        /// <param name="args"></param>
        public ImageService(string[] args)
        {
            InitializeComponent();
            //get info fro, app config to set the varibles.
            LogList logList = LogList.Instance;

            logList.LogRecords = new List <string>();
            //get info from appconfig file to singelton appConfigSettings
            AppCongigSettings appConfig = AppCongigSettings.Instance;

            appConfig.OutPutDir  = ConfigurationManager.AppSettings["OutputDir"];
            appConfig.ThumbNail  = Int32.Parse(ConfigurationManager.AppSettings["ThumbnailSize"]);
            appConfig.SourceName = ConfigurationManager.AppSettings["SourceName"];
            appConfig.LogName    = ConfigurationManager.AppSettings["Name"];


            //create logger server, modal. controller and server.
            this.modal         = new ImageServiceModal(appConfig.OutPutDir, appConfig.ThumbNail);
            this.logging       = new LoggingService();
            this.controller    = new ImageController(this.modal, this.logging);
            this.m_imageServer = new ImageServer(this.controller, this.logging);

            if (args.Count() > 0)
            {
                appConfig.SourceName = args[0];
            }
            if (args.Count() > 1)
            {
                appConfig.LogName = args[1];
            }
            eventLog1 = new System.Diagnostics.EventLog();
            if (!System.Diagnostics.EventLog.SourceExists(appConfig.SourceName))
            {
                System.Diagnostics.EventLog.CreateEventSource(appConfig.SourceName, appConfig.LogName);
            }
            //set log and sourse names.
            eventLog1.Source = appConfig.SourceName;
            eventLog1.Log    = appConfig.LogName;
            // listen to the server updates.
            logging.MessageRecieved += OnUpDateService;
        }