Beispiel #1
0
 /// <summary>
 /// That function will execute the task of the command.
 /// </summary>
 /// <param name="args">arguments</param>
 /// <param name="result"> tells if the command succeded or not.</param>
 /// <returns>command return a string describes the operartion of the command.</returns>
 public string Execute(string[] args, out bool result)
 {
     result = true;
     try
     {
         string        wantedHandler  = args[0];
         string[]      sources        = (ConfigurationManager.AppSettings.Get("Handler").Split(';'));
         StringBuilder restOfHandlers = new StringBuilder();
         for (int i = 0; i < sources.Length; i++)
         {
             if (sources[i] != wantedHandler)
             {
                 restOfHandlers.Append(sources[i] + ";");
             }
         }
         string newHandlers = (restOfHandlers.ToString()).TrimEnd(';');
         ConfigurationManager.AppSettings.Set("Handler", newHandlers);
         this.server.CloseHandler(wantedHandler);
         string[] info = { wantedHandler };
         CommandRecievedEventArgs closeArgs = new CommandRecievedEventArgs((int)CommandEnum.CloseHandler, info, "");
         ImageServer.HandlerRemovalExecution(closeArgs);
         return(string.Empty);
     }
     catch (Exception e)
     {
         result = false;
         return(e.Message);
     }
 }
        public ProjectContext(string projectSettingsPath, IContainer parentContainer)
        {
            BuildSubContainerForThisProject(projectSettingsPath, parentContainer);

            ProjectWindow = _scope.Resolve <Shell>();

            string collectionDirectory = Path.GetDirectoryName(projectSettingsPath);

            //should we save a link to this in the list of collections?
            var collectionSettings = _scope.Resolve <CollectionSettings>();

            if (collectionSettings.IsSourceCollection)
            {
                AddShortCutInComputersBloomCollections(collectionDirectory);
            }

            if (Path.GetFileNameWithoutExtension(projectSettingsPath).ToLower().Contains("web"))
            {
                BookCollection editableCollection    = _scope.Resolve <BookCollection.Factory>()(collectionDirectory, BookCollection.CollectionType.TheOneEditableCollection);
                var            sourceCollectionsList = _scope.Resolve <SourceCollectionsList>();
                _bloomServer = new BloomServer(_scope.Resolve <CollectionSettings>(), editableCollection, sourceCollectionsList, _scope.Resolve <HtmlThumbNailer>());
                _bloomServer.Start();
            }
            else
            {
                if (Settings.Default.ImageHandler != "off")
                {
                    _imageServer = _scope.Resolve <ImageServer>();

                    _imageServer.StartWithSetupIfNeeded();
                }
            }
        }
Beispiel #3
0
        private void picchange(string file)
        {
            // file = @"D:\github\CarSystem\WebInfo\carImg\small\131\2017052406381964996.jpg";
            if (!file.Contains("small"))
            {
                return;
            }
            file = file.Replace("small", "load");

            if (!File.Exists(file))
            {
                return;
            }

            var fileName  = file.Replace("load", "px640");
            var fileName1 = file.Replace("load", "px270");

            var imgserver = new ImageServer();

            if (!File.Exists(fileName))
            {
                imgserver.MakeThumbnail(file, fileName, 640, 640, "W");
            }

            if (!File.Exists(fileName1))
            {
                imgserver.MakeThumbnail(file, fileName1, 270, 200, null);
            }
        }
Beispiel #4
0
        public ImageServer ProvideDefaultImageServer()
        {
            var imageServer = new ImageServer(this);

            imageServer.PopulateWithDefaults();
            return(imageServer);
        }
Beispiel #5
0
        public ImageInfo(Metadata metadata, ImageServer conf, int maxWidth, int maxHeight, int maxArea) : this()
        {
            Height = metadata.Height;
            Width  = metadata.Width;

            var tile = new Tile()
            {
                Width        = Math.Min(metadata.TileWidth, maxWidth),
                Height       = Math.Min(metadata.TileHeight, maxHeight),
                ScaleFactors = new List <int>()
            };

            for (int i = 0; i < metadata.ScalingLevels; i++)
            {
                tile.ScaleFactors.Add(Convert.ToInt32(Math.Pow(2, i)));
            }
            Tiles = new List <Tile> {
                tile
            };

            Profile.Add(new ServiceProfile(conf.AllowSizeAboveFull)
            {
                MaxWidth  = maxWidth == int.MaxValue ? default(int) : maxWidth,
                MaxHeight = maxHeight == int.MaxValue ? default(int) : maxHeight,
                MaxArea   = maxArea == int.MaxValue ? default(int) : maxArea,
                Formats   = conf.AdditionalOutputFormats.Count == 0 ? null : conf.AdditionalOutputFormats
            });
        }
Beispiel #6
0
 /// <summary>
 /// Constractor.
 /// </summary>
 /// <param name="handle">The handle log.</param>
 /// <param name="imageServer">The image server.</param>
 /// <param name="ll">the lloging sevice.</param>
 /// <param name="client">the tcp client.</param>
 public LogCommand(HandleLogs handle, ImageServer imageServer, ILoggingService ll, TcpClient client)
 {
     this.handle    = handle;
     im_s           = imageServer;
     loggingService = ll;
     tcp            = client;
 }
 /// <summary>
 /// Creates a new GUI client handler instance.
 /// </summary>
 /// <param name="imageController">An image controller.</param>
 /// <param name="loggingService">A logging service.</param>
 /// <param name="imageServer">An image server.</param>
 public HandleGuiClient(IImageController imageController, ILoggingService loggingService, ImageServer imageServer)
 {
     m_controller = imageController;
     m_logging    = loggingService;
     m_logging.MessageRecieved += NewLogCommand;
     m_imageServer              = imageServer;
 }
Beispiel #8
0
        private void CreateParts()
        {
            // now reading from configuration file:
            ConfigData conf =
                new ConfigData
                (
                    ConfigurationManager.AppSettings["Handler"].Split(';'),
                    ConfigurationManager.AppSettings["OutputDir"],
                    ConfigurationManager.AppSettings["SourceName"],
                    ConfigurationManager.AppSettings["LogName"],
                    int.Parse(ConfigurationManager.AppSettings["ThumbnailSize"])
                );

            this.config = conf;



            // model create:
            this.modal = new ImageServiceModal(conf.OutputDir, conf.ThumbnailSize);



            // Logger create and assign to event(in LoggingService)

            this.logging = new LoggingService();
            this.logging.MessageRecieved += eventLog1_EntryWritten;

            this.m_imageServer = new ImageServer(this.controller, this.logging, conf.OutputDir, conf.Paths);
            this.controller    = new ImageController(this.modal, this.logging, this.m_imageServer);
        }
        /// <summary>
        /// handeling the command of removing a handler
        /// </summary>
        /// <param name="server">the server of the service</param>
        /// <param name="commandAndArg">the command and the path of the handler that need to be remove </param>
        private void RemoveHandler(ImageServer server, string[] commandAndArg)
        {
            List <TcpClient> clients = server.GetClients();
            string           result  = server.RemoveHandler(commandAndArg[1]);

            if (result == "sucsses")
            {
                foreach (TcpClient c in clients)
                {
                    NetworkStream tempStream = c.GetStream();
                    BinaryWriter  tempWriter = new BinaryWriter(tempStream);
                    try
                    {
                        JObject configObj = new JObject
                        {
                            ["CommandEnum"]        = (int)CommandEnum.CloseCommand,
                            ["RemovedHandlerPath"] = commandAndArg[1]
                        };
                        tempWriter.Write(configObj.ToString());
                        //tempWriter.Write("RemovedHandler" + '#' + commandAndArg[1]);
                    }
                    catch (Exception)
                    {
                        this.RemoveClient(clients, c);
                    }
                }
            }
        }
Beispiel #10
0
        /// <summary>
        /// Updates the entries.
        /// </summary>
        /// <param name="img_server">The server.</param>
        /// <param name="operation_result">if set to <c>true</c> [result].</param>
        /// <returns></returns>
        public string UpdateEntries(ImageServer img_server, out bool operation_result)
        {
            try
            {
                //sets the logging service
                ILoggingService logging_service = img_server.Logging;
                CommandMessage  msg             = new CommandMessage();
                msg.CommandID = (int)CommandEnum.LogCommand;
                JObject job_object = new JObject();

                //the logs
                ObservableCollection <MessageReceivedEventArgs> logs = logging_service.Logs;
                var json_var = JsonConvert.SerializeObject(logs);

                //sets log entries
                job_object["LogEntries"] = json_var;
                msg.CommandArgs          = job_object;
                operation_result         = true;
                return(msg.ToJSON());
            }
            catch (Exception e)
            {
                operation_result = false;
                return(e.Message);
            }
        }
Beispiel #11
0
        // Here You will Use the App Config!
        /// <summary>
        ///Start the server
        ///Param: string[] args - the command line arguments
        /// </summary>
        protected override void OnStart(string[] args)
        {
            eventLog1.WriteEntry(ServiceState.SERVICE_RUNNING.ToString());
            // Update the service state to Start Pending.
            ServiceStatus serviceStatus = new ServiceStatus();

            logging = new LoggingModal();
            logging.MessageRecieved += OnMsg;
            model         = new ImageServiceModel(ConfigurationManager.AppSettings["OutputDir"], Int32.Parse(ConfigurationManager.AppSettings["ThumbnailSize"]));
            controller    = new ImageController(model);
            m_imageServer = new ImageServer(controller, logging);

            CreateHandlers();

            serviceStatus.dwCurrentState = ServiceState.SERVICE_START_PENDING;
            serviceStatus.dwWaitHint     = 100000;

            // Update the service state to Running.
            serviceStatus.dwCurrentState = ServiceState.SERVICE_RUNNING;

            var server = new Thread(m_imageServer.StartServer);

            server.IsBackground = false;
            server.Start();
        }
Beispiel #12
0
        public (int, int, int) GetSizeConstraints(ImageServer conf)
        {
            var maxWidth  = Context.GetOwinEnvironment().Where(t => t.Key == "maxWidth").Select(t => t.Value as int?).SingleOrDefault();
            var maxHeight = Context.GetOwinEnvironment().Where(t => t.Key == "maxHeight").Select(t => t.Value as int?).SingleOrDefault();
            var maxArea   = Context.GetOwinEnvironment().Where(t => t.Key == "maxArea").Select(t => t.Value as int?).SingleOrDefault();

            return(maxWidth ?? conf.MaxWidth, maxHeight ?? conf.MaxHeight, maxArea ?? conf.MaxArea);
        }
 /// <summary>
 /// Reading the app.config.
 /// Initializing and creating members.
 /// </summary>
 private void InitializeService()
 {
     this.logging             = new LoggingService();
     logging.MessageRecieved += OnLog;
     this.m_imageServer       = new ImageServer(this.logging);
     // Lastly updating our entry
     eventLog1.WriteEntry("End of initialzation", EventLogEntryType.Information, eventId++);
 }
Beispiel #14
0
        private void ReciveImageAndProcess(Action <object> callbackDataForImageProcessing)
        {
            if (callbackDataForImageProcessing == null)
            {
                callbackDataForImageProcessing = d => { }
            }
            ;

            ImageServer.AcceptClients(callbackDataForImageProcessing);
        }
Beispiel #15
0
        /// <summary>
        /// ImageService function.
        /// </summary>
        /// <param name="args">command line args</param>
        public ImageService3(string[] args)
        {
            try
            {
                statusRun = true;
                InitializeComponent();
                //read params from app config
                string eventSourceName = ConfigurationManager.AppSettings.Get("SourceName");
                string logName         = ConfigurationManager.AppSettings.Get("LogName");

                eventLog1 = new EventLog();
                if (!System.Diagnostics.EventLog.SourceExists(eventSourceName))
                {
                    System.Diagnostics.EventLog.CreateEventSource(eventSourceName, logName);
                }
                eventLog1.Source = eventSourceName;
                eventLog1.Log    = logName;

                //initialize members
                this.logging = new LoggingService(this.eventLog1);
                this.logging.MessageRecieved += WriteMessage;


                string outPutFolder = ConfigurationManager.AppSettings.Get("OutputDir");

                this.modal = new ImageServiceModal(outPutFolder, this.statusRun.ToString())
                {
                    OutputFolder  = ConfigurationManager.AppSettings.Get("OutputDir"),
                    ThumbnailSize = Int32.Parse(ConfigurationManager.AppSettings.Get("ThumbnailSize"))
                };

                this.controller             = new ImageController(this.modal, this.logging);
                this.m_imageServer          = new ImageServer(controller, logging);
                this.controller.ImageServer = m_imageServer;
                IClientHandler ch = new ClientHandler(controller, logging);

                int port = 8000;
                tcpServer = new TcpServer(port, logging, ch);
                ImageServer.NotifyAllHandlerRemoved += tcpServer.NotifyAllClientsAboutUpdate;
                this.logging.UpdateLogEntries       += tcpServer.NotifyAllClientsAboutUpdate;
                tcpServer.Start();

                //android
                int            port2            = 7999;
                IClientHandler tcpClientHandler = new TcpClientAndroid(controller, logging);
                ITcpServer     tcpServer2       = new TcpServer(port2, logging, tcpClientHandler);
                tcpServer2.Start();
            }
            catch (Exception e)
            {
                statusRun = false;
                this.eventLog1.WriteEntry(e.ToString(), EventLogEntryType.Error);
            }
        }
        public event EventHandler <DirectoryCloseEventArgs> DirectoryClose;              // The Event That Notifies that the Directory is being closed

        public DirectoyHandler(string i_Path, IImageController i_Controller, ImageServer i_Owner, ILoggingService i_Logger)
        {
            m_Logger = i_Logger;
            m_Owner  = i_Owner;
            m_Owner.CommandRecieved += this.OnCommandRecieved;
            m_Controller             = i_Controller;
            m_Path                = i_Path;
            m_DirWatcher          = new FileSystemWatcher(m_Path);
            m_DirWatcher.Created += new FileSystemEventHandler(this.FileCreatedEvent);
            m_Logger.Log($"Directory handler created for: {m_Path}", MessageTypeEnum.INFO);
        }
 public ImageController(IImageServiceModal modal, ILoggingService m_logging,
                        ImageServer imgServer, ConfigData config)
 {
     m_modal  = modal; // Storing the Modal Of The System
     commands = new Dictionary <int, ICommand>()
     {
         { (int)CommandEnum.NewFileCommand, new NewFileCommand(this.m_modal) },
         { (int)CommandEnum.CloseCommand, new CloseCommand() },
         { (int)CommandEnum.LogCommand, new LogCommand(m_logging) },
         { (int)CommandEnum.GetConfigCommand, new ConfigCommand(config) }
     };
 }
Beispiel #18
0
 public MyDataComunication CloseCommunication()
 {
     IsRecording = false;
     WaveIn.StopRecording();
     WaveOut.Stop();
     Capture.Stop();
     ImageClient.CloseConnection();
     ImageServer.CloseConnection();
     VoiceClient.CloseConnection();
     VoiceServer.CloseConnection();
     return(this);
 }
Beispiel #19
0
        public void OnAlert(ImageServer.Common.Alert alert)
        {
            AlertFilter filter = new AlertFilter(AlertCache.Instance);
            if (!filter.Filter(alert))
            {
                AlertCache.Instance.Add(alert);
                if (DatabaseEnabled)
                    WriteToDatabase(alert);
                else
                    WriteToLog(alert);
            }

        }
Beispiel #20
0
        public unsafe Toolbar(GToolbarItem *items, int icon_size)
        {
            this.ButtonClick   = null;
            this.Rearranged    = null;
            this.NumItems      = 0;
            this.ActiveItem    = -2;
            this.SelectedItem  = -1;
            this.ActivePressed = false;
            base.SetStyle(ControlStyles.Selectable, false);
            this.InitializeComponent();
            this.Items    = items;
            this.IconSize = icon_size;
            this.NumItems = 0;
            if (*(int *)items != -3)
            {
                do
                {
                    this.NumItems++;
                }while (*(int *)(this.NumItems * 16 / sizeof(GToolbarItem) + this.Items) != -3);
            }
            this.ItemProps = new Toolbar.ToolbarItemProp[this.NumItems];
            ImageServer imageServer = ImageServer.GetImageServer("Images");
            int         num         = 0;

            if (0 < this.NumItems)
            {
                int num2 = 0;
                do
                {
                    this.ItemProps[num] = new Toolbar.ToolbarItemProp();
                    GToolbarItem *ptr  = num2 / sizeof(GToolbarItem) + this.Items;
                    int           num3 = *(int *)ptr;
                    if (num3 != -1 && num3 != -2)
                    {
                        this.ItemProps[num].itemImage         = imageServer.GetImage(new string(*(int *)(ptr + 8 / sizeof(GToolbarItem))));
                        this.ItemProps[num].itemDisabledImage = imageServer.GetImage(new string(*(int *)(num2 / sizeof(GToolbarItem) + this.Items + 8 / sizeof(GToolbarItem))) + "-disabled");
                        Toolbar.ToolbarItemProp toolbarItemProp = this.ItemProps[num];
                        if (toolbarItemProp.itemImage == null || toolbarItemProp.itemDisabledImage == null)
                        {
                            goto IL_170;
                        }
                    }
                    this.ItemProps[num].Enabled = true;
                    this.ItemProps[num].Pushed  = false;
                    num++;
                    num2 += 16;
                }while (num < this.NumItems);
                goto IL_199;
IL_170:
                < Module >.GLogger.MarkLine((sbyte *)(& < Module >.?? _C@_0CL@OAFELHOF@c?3?2jtfcode?2src?2workshop?2controls@), 98, (sbyte *)(& < Module >.?? _C@_0BM@GKMMDKEB@NControls?3?3Toolbar?3?3Toolbar?$AA@));
        public static string GetAvatar(long charId, ImageServer.ImageSize size)
        {
            string avatar;

            var tempAvatar = ImageServer.DownloadCharacterImage(charId, size);

            using (var stream = new MemoryStream())
            {
                tempAvatar.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                avatar = string.Format("data:image/png;base64,{0}", Convert.ToBase64String(stream.ToArray()));
            }
            tempAvatar.Dispose();
            return(avatar);
        }
 public void RunTwoServer_UseDifferentPorts()
 {
     using (var x = new ImageServer(null))
     {
         x.StartListening();
         var firstUrl = ServerBase.ServerUrl;
         using (var y = new ImageServer(null))
         {
             y.StartListening();
             var secondUrl = ServerBase.ServerUrl;
             Assert.AreNotEqual(firstUrl, secondUrl);
             Console.WriteLine(firstUrl + ", " + secondUrl);
         }
     }
 }
        public static string ExportImageServer(ImageServer imageServer)
        {
            IGeoImageDescription2 geoImageDesc = new GeoImageDescriptionClass();
            geoImageDesc.Width = 800;
            geoImageDesc.Height = 600;
            geoImageDesc.Extent = imageServer.ServiceInfo.Extent;
               // geoImageDesc.RenderingRule = rule;

            //Export an image using service's color map.
            IImageType imageType = new ImageTypeClass();
            imageType.Format = esriImageFormat.esriImageJPGPNG;
            imageType.ReturnType = esriImageReturnType.esriImageReturnURL;
            IMapImage mapImage = ((IImageServer2)imageServer).ExportMapImage(geoImageDesc, imageType);
            return mapImage.URL;
        }
        /// ------------------------------------------------------------------------------------
        public void Dispose()
        {
            _scope.Dispose();
            _scope = null;

            if (_bloomServer != null)
            {
                _bloomServer.Dispose();
            }
            _bloomServer = null;
            if (_imageServer != null)
            {
                _imageServer.Dispose();
            }
            _imageServer = null;
        }
        /**
         * when the service is closed, the handler closed too.
         */
        public void OnCloseService(object sender, CommandRecievedEventArgs e)
        {
            ImageServer imageServer = (ImageServer)sender;

            try
            {
                this.watcher.EnableRaisingEvents = false;
                this.watcher.Dispose();
                imageServer.CommandRecieved -= this.OnCommandRecieved;
                this.logging.Log("Handler for path: " + this.path + " was closed.", MessageTypeEnum.INFO);
            }
            catch
            {
                this.logging.Log(this.path + " failed to close the handler.", MessageTypeEnum.WARNING);
            }
        }
Beispiel #26
0
        public void GenerateAlert(ImageServer.Common.Alert alert)
        {
            IAlertServiceExtension[] extensions = GetExtensions();
            foreach(IAlertServiceExtension ext in extensions)
            {
                try
                {
                    ext.OnAlert(alert);    
                }
                catch(Exception e)
                {
                    Platform.Log(LogLevel.Error, e, "Error occurred when calling {0} OnAlert()", ext.GetType());
                }
            }

        }
Beispiel #27
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);
        }
Beispiel #28
0
        /// <summary>
        /// a method that get an object and a CommandRecievedEventArgs and close the service
        /// </summary>
        /// <param name="sender">an object yhat reoresent the ImageServer</param>
        /// <param name="e">a DirectoryCloseEventArgs</param>
        public void onCloseService(object sender, CommandRecievedEventArgs e)
        {
            ImageServer server = (ImageServer)sender;

            m_dirWatcher.EnableRaisingEvents = false;
            m_dirWatcher.Dispose();
            string msg = "Handler closed " + m_path;

            m_logging.Log(msg, MessageTypeEnum.INFO);
            bool   result;
            string s = m_controller.ExecuteCommand((int)CommandEnum.LastLogCommand, null, out result);

            if (result)
            {
                m_tcpServer.NotifyAll(s);
            }
        }
        /// <summary>
        /// executing a command and back an answer
        /// </summary>
        /// <param name="server">the server of the service</param>
        /// <param name="commandAndArg">the command and the args of this command</param>
        /// <param name="writer">the writer to the client</param>
        /// <param name="client">the client that need to remove if the connection is failed</param>
        private void ExecuteCommand(ImageServer server, string[] commandAndArg, BinaryWriter writer, TcpClient client)
        {
            List <TcpClient> clients = server.GetClients();
            bool             resultSuccesful;
            string           result;

            string[] args = new string[1];
            args[0] = " ";
            result  = server.GetController().ExecuteCommand(Convert.ToInt32((Enum.Parse(typeof(CommandEnum), commandAndArg[0]))), args, out resultSuccesful);
            try
            {
                writer.Write(result);
            }
            catch (Exception)
            {
                this.RemoveClient(clients, client);
            }
        }
        /// <summary>
        /// Executes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <param name="result">if set to <c>true</c> [result].</param>
        /// <returns>System.String.</returns>
        public string Execute(string[] args, out bool result)
        {
            result = true;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // Add an Application Setting.
            config.AppSettings.Settings.Remove("Handler");
            config.AppSettings.Settings.Add("Handler", args[0]);
            config.Save(ConfigurationSaveMode.Modified, true);
            ConfigurationManager.RefreshSection("appSettings");

            DirectoryCloseEventArgs e = new DirectoryCloseEventArgs(args[1], "Remove handler");

            this.m_imageServer.RemoveDirectoryHandler(args[1], e);

            CommandRecievedEventArgs command = new CommandRecievedEventArgs((int)CommandEnum.CloseHandler, args, "");

            ImageServer.RemoveHandlerEvent(command);
            return("");
        }
Beispiel #31
0
 /// <summary>
 /// That function will execute the task of the command.
 /// </summary>
 /// <param name="args">arguments</param>
 /// <param name="result"> tells if the command succeded or not.</param>
 /// <returns>command return a string describes the operartion of the command.</returns>
 public string Execute(string[] args, out bool result)
 {
     try
     {
         result = true;
         if (args == null || args.Length == 0)
         {
             throw new Exception("Invalid args for deleting handler");
         }
         string        toBeDeletedHandler = args[0];
         string[]      directories        = (ConfigurationManager.AppSettings.Get("Handler").Split(';'));
         StringBuilder sbNewHandlers      = new StringBuilder();
         for (int i = 0; i < directories.Length; i++)
         {
             if (directories[i] != toBeDeletedHandler)
             {
                 sbNewHandlers.Append(directories[i] + ";");
             }
         }
         string        newHandlers = (sbNewHandlers.ToString()).TrimEnd(';');
         Configuration config      = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
         // Add an Application Setting.
         config.AppSettings.Settings.Remove("Handler");
         config.AppSettings.Settings.Add("Handler", newHandlers);
         // Save the configuration file.
         config.Save(ConfigurationSaveMode.Modified);
         // Force a reload of a changed section.
         ConfigurationManager.RefreshSection("appSettings");
         this.m_imageServer.CloseSpecipicHandler(toBeDeletedHandler);
         string[] array = new string[1];
         array[0] = toBeDeletedHandler;
         CommandRecievedEventArgs notifyParams = new CommandRecievedEventArgs((int)CommandEnum.CloseHandler, array, "");
         ImageServer.PerformSomeEvent(notifyParams);
         return(string.Empty);
     }
     catch (Exception ex)
     {
         result = false;
         return(ex.ToString());
     }
 }
        /// <summary>
        /// the function handeling the connections with the clients.
        /// </summary>
        /// <param name="client">the client that need to be handle</param>
        /// <param name="server">the server of the service</param>
        public void HandleClient(TcpClient client, ImageServer server)
        {
            List <TcpClient> clients = server.GetClients();
            bool             stop    = false;

            new Task(() =>
            {
                do
                {
                    NetworkStream stream = client.GetStream();
                    BinaryReader reader  = new BinaryReader(stream);
                    BinaryWriter writer  = new BinaryWriter(stream);

                    try
                    {
                        string command         = reader.ReadString();
                        string[] commandAndArg = command.Split(' ');

                        switch (commandAndArg[0])
                        {
                        case "RemoveHandler":
                            this.RemoveHandler(server, commandAndArg);
                            break;

                        case "Close":
                            this.RemoveClient(clients, client);
                            break;

                        default:
                            this.ExecuteCommand(server, commandAndArg, writer, client);
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        break;
                    }
                } while (!stop);
                client.Close();
            }).Start();
        }
 /// <summary>
 /// Updates the entries.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="result">if set to <c>true</c> [result].</param>
 /// <returns></returns>
 public string UpdateEntries(ImageServer server, out bool result)
 {
     try
     {
         ILoggingService logger = server.Logging;
         CommandMessage  msg    = new CommandMessage();
         msg.CommandID = (int)CommandEnum.LogCommand;
         JObject jObj = new JObject();
         ObservableCollection <MessageReceivedEventArgs> logs = logger.Logs;
         var json = JsonConvert.SerializeObject(logs);
         jObj["LogEntries"] = json;
         msg.CommandArgs    = jObj;
         result             = true;
         return(msg.ToJSON());
     }
     catch (Exception e)
     {
         result = false;
         return(e.Message);
     }
 }
Beispiel #34
0
        private static XmlDocument CreateXmlContent(ImageServer.Common.Alert alert)
        {
            XmlDocument doc = new XmlDocument();

            XmlNode docElement = doc.CreateElement("Contents");
            doc.AppendChild(docElement);

            XmlNode messageNode = doc.CreateElement("Message");
            messageNode.AppendChild(doc.CreateTextNode(alert.Message));

            docElement.AppendChild(messageNode);

            if (alert.ContextData != null)
            {
                XmlNode contextContainerNode = doc.CreateElement("Context");
                XmlNode contextNode = doc.ImportNode(XmlUtils.Serialize(alert.ContextData), true);

                contextContainerNode.AppendChild(contextNode);
                docElement.AppendChild(contextContainerNode);
            }

            return doc;
        }
 public void Init(IServerObjectHelper pSOH)
 {
     _serverObjectHelper = pSOH;
     pImageSever = _serverObjectHelper.ServerObject as ImageServer;
 }
Beispiel #36
0
        private static void WriteToDatabase(ImageServer.Common.Alert alert)
        {
            XmlDocument doc = CreateXmlContent(alert);

            AlertUpdateColumns columns = new AlertUpdateColumns();

            columns.AlertCategoryEnum = AlertCategoryEnum.GetEnum(alert.Category.ToString());
            columns.AlertLevelEnum = AlertLevelEnum.GetEnum(alert.Level.ToString());
            columns.Component = alert.Source.Name;
            columns.Content = doc;
            columns.InsertTime = Platform.Time;
            columns.Source = alert.Source.Host;
            columns.TypeCode = alert.Code;

            IPersistentStore store = PersistentStoreRegistry.GetDefaultStore();
            using (IUpdateContext ctx = store.OpenUpdateContext(UpdateContextSyncMode.Flush))
            {
                IAlertEntityBroker alertBroker = ctx.GetBroker<IAlertEntityBroker>();
                alertBroker.Insert(columns);
                ctx.Commit();
            }
        }
Beispiel #37
0
        static private string ResolveKey(ImageServer.Common.Alert alert)
        {
            Platform.CheckForNullReference(alert, "alert");
            Platform.CheckForNullReference(alert.Source, "alert.Source");
            string key = String.Format("{0}/{1}/{2}/{3}",
                                       alert.Source.Host, alert.Source.Name, alert.Code, alert.ContextData);

            return key;
        }
Beispiel #38
0
 /// <summary>
 /// Adds an alert into the cache.
 /// </summary>
 /// <param name="alert"></param>
 public void Add(ImageServer.Common.Alert alert)
 {
     lock (_syncLock)
     {
         _listAlerts.Add(alert);
     }
     _cache.Add(ResolveKey(alert), alert, null, alert.ExpirationTime, Cache.NoSlidingExpiration, CacheItemPriority.Normal,
             delegate(string key, Object value, CacheItemRemovedReason reason)
             {
                 // Discovered an exception here when debugging that may have caused the service to 
                 // crash. This delegate was called, however, the alert was not in the cache
                 lock (_syncLock)
                 {
                     if (_listAlerts.Contains((ImageServer.Common.Alert)value))
                         _listAlerts.Remove((ImageServer.Common.Alert)value);
                 }
             });
 }
Beispiel #39
0
 /// <summary>
 /// Gets a value indicating whether the specified alert or another alert that represents the same event is already in the cache.
 /// </summary>
 /// <param name="alert"></param>
 /// <returns></returns>
 public bool Contains(ImageServer.Common.Alert alert)
 {
     lock (_syncLock)
         return _listAlerts.Contains(alert);
 }
Beispiel #40
0
 public bool Filter(ImageServer.Common.Alert alert)
 {
     return _cache.Contains(alert);
 }
Beispiel #41
0
        private static void WriteToLog(ImageServer.Common.Alert alert)
        {
            XmlDocument doc = CreateXmlContent(alert);

            using (StringWriter sw = new StringWriter())
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineOnAttributes = false;
                settings.OmitXmlDeclaration = true;
                settings.Encoding = Encoding.UTF8;

                XmlWriter writer = XmlWriter.Create(sw, settings);
                doc.WriteTo(writer);
                writer.Flush();

                String log = String.Format("ALERT: {0} : {1}", alert.Source.Name, sw);
                switch (alert.Level)
                {
                    case AlertLevel.Critical:
                    case AlertLevel.Error:
                        Platform.Log(LogLevel.Error, log);
                        break;

                    case AlertLevel.Informational:
                        Platform.Log(LogLevel.Info, log);
                        break;
                    case AlertLevel.Warning:
                        Platform.Log(LogLevel.Warn, log);
                        break;
                    default:
                        Platform.Log(LogLevel.Info, log);
                        break;
                }
            }

        }