Beispiel #1
0
        public RemResMessage AddWatchRule(RemResMessage message)
        {
            AddWatchRule convertedMessage;

            if (!(message is AddWatchRule))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            //convert message to goal type
            convertedMessage = message as AddWatchRule;

            //Validate the watchRule
            ValidateAddWatchRule(convertedMessage);

            //init the watch task
            CreateWatchTask(convertedMessage.WatchRule, true);

            return(new OperationStatus()
            {
                Command = convertedMessage.GetType().Name,
                Status = StatusType.OK,
                Message = String.Format("The watchrule {0} has been sucessfully created and is now running.", convertedMessage.WatchRule.Name)
            });
        }
Beispiel #2
0
        public RemResMessage GetSetting(RemResMessage message)
        {
            if (!(message is GetSetting))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            var key = ((GetSetting)message).Key;

            try
            {
                return(new GetSettingResult
                {
                    Settings = new RemResDataLib.BaseTypes.Settings()
                    {
                        settingsManagerObj.GetSettingValue(key)
                    }
                });
            }
            catch (Exception ex)
            {
                return(new OperationStatus()
                {
                    Command = message.GetType().Name,
                    Message = ex.Message,
                    Status = StatusType.ERROR
                });
            }
        }
Beispiel #3
0
        public RemResMessage GetKeepAliveResponse(RemResMessage message)
        {
            if (!(message is KeepAliveRequest))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            return(new KeepAliveResponse());
        }
Beispiel #4
0
        /// <summary>
        /// Processes the message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="clientID">The client identifier.</param>
        public void AddMessageForExecution(RemResMessage message, Guid clientID)
        {
            Guid messageId = Guid.NewGuid();

            messageQueue.Enqueue(new ExecutionMessage()
            {
                MessageID = messageId,
                Message   = message,
                ClientID  = clientID
            });
        }
 /// <summary>
 /// Sends the message.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="clientID">The client identifier.</param>
 /// <returns></returns>
 public void SendMessage(RemResMessage message, Guid clientID)
 {
     foreach (INetworkConnector connector in connectors)
     {
         if (connector.IsClientRegistered(clientID))
         {
             connector.SendMessage(message, clientID);
             return;
         }
     }
 }
Beispiel #6
0
        /// <summary>
        /// Sends the message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="clientID">The client identifier.</param>
        /// <returns></returns>
        public bool SendMessage(RemResMessage message, Guid clientID)
        {
            XmlSerializer xmlFormatter;
            NetworkStream networkStream;

            if (!currentClients.ContainsKey(clientID))
            {
                throw new InvalidOperationException("The given client is no longer available. Connection closed.");
            }

            xmlFormatter = new XmlSerializer(message.GetType());

            try
            {
                networkStream = new NetworkStream(currentClients[clientID]);
            }
            catch (Exception ex)
            {
                try
                {
                    log.Debug("Problem with data connection establishment to the client " + currentClients[clientID].RemoteEndPoint + ".", ex);
                }
                catch (Exception exi)
                {
                    log.Debug("Problem with data connection establishment to the client.", exi);
                }
                networkStream = null;
                return(false);
            }

            try
            {
                xmlFormatter.Serialize(networkStream, message);
            }
            catch (Exception ex)
            {
                log.Debug("Problem with sending the xml data message from the client.", ex);
            }
            finally
            {
                //Clean up
                networkStream.Close();
                networkStream.Dispose();

                //end connection to client - response was send - clean up in incomming data handler
                if (currentClients.ContainsKey(clientID))
                {
                    currentClients[clientID].Disconnect(false);
                }
            }

            return(true);
        }
Beispiel #7
0
 private void MainWindow_NotificationReceived(RemResMessage notificationMessage)
 {
     if (notificationMessage is Notification)
     {
         Notification msg = (notificationMessage as Notification);
         MessageBox.Show(String.Format(
                             "{0}\nValue:{1}\nWatch Field:{2}-{3}\nWatch Rule:{4}",
                             msg.Message, msg.LastValue, msg.WatchField.WatchObject,
                             msg.WatchField.WatchProperty, msg.WatchRuleName),
                         "Notification received");
     }
 }
Beispiel #8
0
        public RemResMessage GetWatchData(RemResMessage message)
        {
            GetWatchData       convertedMessage;
            WatchDataSet       resultSet    = new WatchDataSet();
            IList <IWatchTask> tempTaskList = new List <IWatchTask>();

            if (!(message is GetWatchData))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            convertedMessage = (message as GetWatchData);

            if (string.IsNullOrEmpty(convertedMessage.Name) && convertedMessage.WatchField == null)
            {
                //return all data
                tempTaskList = lstAktivWatchTasks;
            }

            if (!string.IsNullOrEmpty(convertedMessage.Name))
            {
                //return data for watch rule name
                tempTaskList = lstAktivWatchTasks.Where(t => t.Rule.Name.Equals(convertedMessage.Name)).ToList();
            }

            if (convertedMessage.WatchField != null)
            {
                //return data for all rules with given field
                tempTaskList = lstAktivWatchTasks.Where(t => t.Rule.WatchField.WatchObject.Equals(convertedMessage.WatchField.WatchObject) &&
                                                        t.Rule.WatchField.WatchProperty.Equals(convertedMessage.WatchField.WatchProperty)).ToList();
            }

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var task in tempTaskList)
            {
                WatchField tempField = new WatchField
                {
                    Type             = task.Rule.WatchField.Type,
                    WatchObject      = task.Rule.WatchField.WatchObject,
                    WatchProperty    = task.Rule.WatchField.WatchProperty,
                    WhereClause      = task.Rule.WatchField.WhereClause,
                    WatchFieldValues = task.WatchData.ToList()
                };

                resultSet.Add(tempField);
            }

            return(new GetWatchDataResult()
            {
                WatchDataSet = resultSet
            });
        }
Beispiel #9
0
        public RemResMessage HandleNewNotificationEndPointReceived(RemResMessage message)
        {
            if (!(message is NotifyMe))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            OperationStatus errorStatus = new OperationStatus()
            {
                Command = message.GetType().Name,
                Status  = StatusType.OK,
                Message = "The enpoint is in the wrong format. Please use 'hostname:port'."
            };

            string endpoint = (message as NotifyMe).Endpoint;
            string hostname = null;
            int    port     = -1;

            if (string.IsNullOrEmpty(endpoint))
            {
                return(errorStatus);
            }

            string[] endpointParts = endpoint.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);

            if (endpointParts.Length == 2)
            {
                hostname = endpointParts[0];
                try
                {
                    port = Convert.ToInt32(endpointParts[1]);
                }
                catch
                {
                    return(errorStatus);
                }
            }
            else
            {
                return(errorStatus);
            }

            //raise event enpoint recieved
            NotificationEndpointReceivedHandler(hostname, port);

            return(new OperationStatus()
            {
                Command = message.GetType().Name,
                Status = StatusType.OK,
                Message = string.Format("The enpoint {0} was successfully added to the notification endpoints.", (message as NotifyMe).Endpoint)
            });
        }
Beispiel #10
0
        /// <summary>
        /// Send a notification message to the endpoint.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="endpoint">The endpoint.</param>
        /// <returns></returns>
        public bool SendNotification(RemResMessage message, string endpoint, int port)
        {
            XmlSerializer xmlFormatter;
            NetworkStream networkStream;
            TcpClient     client;

            xmlFormatter = new XmlSerializer(message.GetType());

            try
            {
                client        = new TcpClient(endpoint, port);
                networkStream = client.GetStream();
            }
            catch (Exception ex)
            {
                try
                {
                    log.Debug(String.Format("Problem with data connection establishment to the client {0}:{1}.", endpoint, port), ex);
                }
                catch (Exception exi)
                {
                    log.Debug("Problem with data connection establishment to the client.", exi);
                }

                networkStream = null;
                return(false);
            }

            try
            {
                xmlFormatter.Serialize(networkStream, message);
            }
            catch (Exception ex)
            {
                log.Debug("Problem with sending the xml data message from the client.", ex);
                return(false);
            }
            finally
            {
                //clean up

                if (networkStream != null)
                {
                    networkStream.Close();
                    networkStream.Dispose();
                }

                client.Close();
            }

            return(true);
        }
Beispiel #11
0
        public RemResMessage GetProcessList(RemResMessage message)
        {
            ProcessSet     resultList = new ProcessSet();
            GetProcessList convertedMessage;
            int            minRamBytes;

            List <System.Diagnostics.Process> lstProcess;

            if (!(message is GetProcessList))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            convertedMessage = message as GetProcessList;

            minRamBytes = convertedMessage.RAMOver;

            if (minRamBytes == 0)
            {
                lstProcess = System.Diagnostics.Process.GetProcesses().ToList();
            }
            else
            {
                lstProcess = System.Diagnostics.Process.GetProcesses().Where(p => p.WorkingSet64 >= minRamBytes).ToList();
            }

            foreach (var proc in lstProcess)
            {
                try
                {
                    resultList.Add(new Process
                    {
                        PID          = proc.Id,
                        ProcessName  = proc.ProcessName,
                        ProcessTitle = proc.MainWindowTitle,
                        Responding   = proc.Responding,
                        RAM          = (int)(proc.WorkingSet64)
                    });
                }
                catch (Exception ex)
                {
                    _log.Debug("Error during accesing the proccess list - " +
                               ex.Message);
                }
            }

            return(new GetProcessListResult()
            {
                ProcessSet = resultList
            });
        }
Beispiel #12
0
        public RemResMessage GetWatchRules(RemResMessage message)
        {
            if (!(message is GetWatchRules))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            //no possible in one line because of problem with convert from list<watchrule> to WatchRuleSet
            var ruleset = new WatchRuleSet();

            ruleset.AddRange(lstAktivWatchTasks.Select(t => t.Rule).ToList());

            return(new GetWatchRuleResult()
            {
                WatchRuleSet = ruleset
            });
        }
Beispiel #13
0
        public RemResMessage DeleteWatchRule(RemResMessage message)
        {
            DeleteWatchRule convertedMessage;

            if (!(message is DeleteWatchRule))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            //convert message to goal type
            convertedMessage = message as DeleteWatchRule;

            if (string.IsNullOrEmpty(convertedMessage.Name))
            {
                throw new ArgumentNullException("message.DeleteWatchRule.Name");
            }

            if (lstAktivWatchTasks.Any(t => t.Rule.Name.Equals(convertedMessage.Name)))
            {
                var item = lstAktivWatchTasks.FirstOrDefault(t => t.Rule.Name.Equals(convertedMessage.Name));

                if (item != null)
                {
                    item.EndWatchTask();

                    lstAktivWatchTasks.Remove(item);

                    SaveConfigRules();

                    return(new OperationStatus()
                    {
                        Status = StatusType.OK,
                        Command = "DeleteWatchRule",
                        Message = String.Format("The watchrule {0} has been successfully deleted.", convertedMessage.Name)
                    });
                }

                throw new InvalidOperationException(String.Format("There is no activ watchrule {0} running " +
                                                                  "on this service", convertedMessage.Name));
            }
            else
            {
                throw new InvalidOperationException(String.Format("There is no activ watchrule {0} running " +
                                                                  "on this service", convertedMessage.Name));
            }
        }
 /// <summary>
 /// Sends the notification.
 /// </summary>
 /// <param name="message">The message.</param>
 public void SendNotification(RemResMessage message)
 {
     //run through all endpoints and forward notification message
     lock (lockEndpoints)
     {
         foreach (var endpoint in lstNotificationEndpoints)
         {
             foreach (var connector in connectors)
             {
                 if (!connector.SendNotification(message, endpoint.Endpoint, endpoint.Port))
                 {
                     endpoint.FailedSendOperations++;
                 }
             }
         }
     }
 }
Beispiel #15
0
        public RemResMessage SetSetting(RemResMessage message)
        {
            if (!(message is SetSetting))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            var key   = ((SetSetting)message).Key;
            var value = ((SetSetting)message).Value;

            if (string.IsNullOrEmpty(key))
            {
                return(new OperationStatus()
                {
                    Command = "SetSetting",
                    Message = "The key value has to be specified.",
                    Status = StatusType.INVALIDINPUT
                });
            }

            var status = settingsManagerObj.SetSettingValue(key, value);

            if (status)
            {
                return(new OperationStatus()
                {
                    Command = "SetSetting",
                    Message = "The settings value was set.",
                    Status = StatusType.OK
                });
            }
            else
            {
                return(new OperationStatus()
                {
                    Command = "SetSetting",
                    Message = "The settings value can't be set.",
                    Status = StatusType.ERROR
                });
            }
        }
Beispiel #16
0
        public RemResMessage ClearWatchRules(RemResMessage message)
        {
            if (!(message is ClearWatchRules))
            {
                throw new InvalidOperationException("The message type for this messagehandler method is invalid.");
            }

            foreach (var item in lstAktivWatchTasks)
            {
                item.EndWatchTask();
            }

            lstAktivWatchTasks.Clear();

            SaveConfigRules();

            return(new OperationStatus()
            {
                Status = StatusType.OK,
                Command = "ClearWatchRules",
                Message = "The watchrule set has been successfully cleared."
            });
        }
Beispiel #17
0
        /// <summary>
        /// Handles the data connection.
        /// </summary>
        /// <param name="result">The result.</param>
        private void HandleDataConnection(IAsyncResult result)
        {
            Socket        client = null;
            NetworkStream networkStream;
            MemoryStream  memoryStream;
            StreamReader  reader;
            RemResMessage inputMessage = null;
            Guid          clientKey    = Guid.NewGuid();
            XmlSerializer xmlFormatter;

            byte[] buffer;

            OperationStatus osInvalidInput = new OperationStatus()
            {
                Command = "Unknown",
                Message = "Invalid Input Data - The input " +
                          "is not a valid RemRes Message or Command.",
                Status = StatusType.INVALIDINPUT
            };

            try
            {
                client = tcpListener.EndAcceptSocket(result);

                currentClients.Add(clientKey, client);
            }
            catch (Exception ex)
            {
                log.Debug("Error during connection establishment to the client.", ex);
            }

            if (client != null)
            {
                try
                {
                    networkStream = new NetworkStream(client);
                }
                catch (Exception ex)
                {
                    try
                    {
                        log.Debug("Problem with data connection establishment to the client " + client.RemoteEndPoint + ".", ex);
                    }
                    catch (Exception exi)
                    {
                        log.Debug("Problem with data connection establishment to the client.", exi);
                    }
                    networkStream = null;
                    memoryStream  = null;
                }

                while (client.Connected && networkStream != null)
                {
                    try
                    {
                        //direct deserializing from networkstream ends in endless loop
                        //because networkStream does not support seek/readtoend

                        //read data in buffer
                        buffer = new byte[client.Available];
                        networkStream.Read(buffer, 0, client.Available);
                        memoryStream = new MemoryStream(buffer);

                        reader = new StreamReader(memoryStream);
                        var message = reader.ReadToEnd();

                        //get the right formatter for the incomming message
                        xmlFormatter = GetXmlSerializer(message);

                        memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(message));

                        if (xmlFormatter != null)
                        {
                            inputMessage = (RemResMessage)xmlFormatter.Deserialize(memoryStream);
                        }
                        else
                        {
                            log.Debug("Problem with receiving the xml data message from the client. Unknown message format!");

                            //Send back an error operation status
                            SendMessage(osInvalidInput, clientKey);

                            //end connection
                            client.Disconnect(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Debug("Problem with receiving the xml data message from the client.", ex);

                        //Send back an error operation status
                        SendMessage(osInvalidInput, clientKey);

                        //end connection
                        client.Disconnect(false);
                    }

                    if (inputMessage != null)
                    {
                        if (messageReceivedHandler != null)
                        {
                            messageReceivedHandler(inputMessage, clientKey);
                        }
                    }

                    //while no data on network stream available and connection not closed
                    while (client.Available == 0 && client.Connected)
                    {
                        Thread.Sleep(new TimeSpan(0, 0, 0, 0, 100));
                    }
                }

                if (networkStream != null)
                {
                    networkStream.Close();
                    networkStream.Dispose();
                }

                client.Close();
                client.Dispose();
            }

            if (currentClients.ContainsKey(clientKey))
            {
                currentClients.Remove(clientKey);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Sends the message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        public RemResMessage SendMessage(RemResMessage message)
        {
            XmlSerializer xmlFormatter;
            NetworkStream networkStream;
            MemoryStream  memoryStream;
            StreamReader  reader;
            TcpClient     client;

            Byte[] buffer;

            xmlFormatter = new XmlSerializer(message.GetType());

            try
            {
                client        = new TcpClient(endpoint, port);
                networkStream = client.GetStream();
            }
            catch (Exception ex)
            {
                try
                {
                    log.Debug(String.Format("Problem with data connection establishment" +
                                            " to the service {0}:{1}.", endpoint, port), ex);
                }
                catch (Exception exi)
                {
                    log.Debug("Problem with data connection establishment" +
                              " to the service.", exi);
                }
                networkStream = null;
                return(null);
            }

            try
            {
                xmlFormatter.Serialize(networkStream, message);
            }
            catch (Exception ex)
            {
                log.Debug("Problem with sending the xml data message to the service.", ex);
            }

            try
            {
                buffer = new byte[client.Available];
                networkStream.Read(buffer, 0, client.Available);
                memoryStream = new MemoryStream(buffer);

                reader = new StreamReader(memoryStream);
                var messageStr = reader.ReadToEnd();
                xmlFormatter = GetXmlSerializer(messageStr);

                memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(messageStr));

                if (xmlFormatter != null)
                {
                    return((RemResMessage)xmlFormatter.Deserialize(memoryStream));
                }
                else
                {
                    log.Debug("Problem with receiving the xml data message from the client. Unknown message format!");
                }
            }
            catch (Exception ex)
            {
                log.Debug("Problem while receiving the the xml response data message from the service.", ex);
            }
            finally
            {
                networkStream.Close();
                networkStream.Dispose();
                client.Close();
            }

            return(null);
        }
 /// <summary>
 /// Sends the message.
 /// </summary>
 /// <param name="serviceID">The service identifier.</param>
 /// <param name="message">The message.</param>
 /// <returns></returns>
 public RemResMessage SendMessage(Guid serviceID, RemResMessage message)
 {
     return(lstConnectors[serviceID].SendMessage(message));
 }
        /// <summary>
        /// Handles the data connection.
        /// </summary>
        /// <param name="result">The result.</param>
        private void HandleDataConnection(IAsyncResult result)
        {
            Socket        client = null;
            NetworkStream networkStream;
            MemoryStream  memoryStream;
            RemResMessage inputMessage = null;
            XmlSerializer xmlFormatter = new XmlSerializer(typeof(RemResDataLib.Messages.Notification));

            byte[] buffer;

            try
            {
                client = tcpListener.EndAcceptSocket(result);
            }
            catch (Exception ex)
            {
                log.Debug("Error during connection establishment to the client.", ex);
            }

            if (client != null)
            {
                try
                {
                    networkStream = new NetworkStream(client);
                }
                catch (Exception ex)
                {
                    try
                    {
                        log.Debug("Problem with data connection establishment to the client " + client.RemoteEndPoint + ".", ex);
                    }
                    catch (Exception exi)
                    {
                        log.Debug("Problem with data connection establishment to the client.", exi);
                    }
                    networkStream = null;
                    memoryStream  = null;
                }

                if (client.Connected && networkStream != null)
                {
                    try
                    {
                        //direct deserializing from networkstream ends in endless loop
                        //because networkStream does not support seek/readtoend
                        buffer = new byte[client.Available];
                        networkStream.Read(buffer, 0, client.Available);
                        memoryStream = new MemoryStream(buffer);

                        inputMessage = (RemResMessage)xmlFormatter.Deserialize(memoryStream);
                    }
                    catch (Exception ex)
                    {
                        log.Debug("Problem with receiving the notification xml data message from the client.", ex);
                    }

                    if (inputMessage != null)
                    {
                        if (NotificationReceivedHandler != null)
                        {
                            NotificationReceivedHandler(inputMessage);
                        }
                    }
                }

                //clean up
                if (networkStream != null)
                {
                    networkStream.Close();
                    networkStream.Dispose();
                }

                client.Close();
                client.Dispose();
            }
        }
 /// <summary>
 /// Sends the message asynchronous.
 /// </summary>
 /// <param name="serviceID">The service identifier.</param>
 /// <param name="message">The message.</param>
 /// <returns></returns>
 public Task <RemResMessage> SendMessageAsync(Guid serviceID, RemResMessage message)
 {
     return(Task.Run <RemResMessage>(() => lstConnectors[serviceID].SendMessage(message)));
 }