Ejemplo n.º 1
0
        public static void StopAll()
        {
            var db = new PetaPoco.Database("LocalSQLite");

            // stop all running threads\monitors
            foreach (MonitorClass mc in _monitorRunPool)
            {
                // stop the Timer
                if (!mc.DisableTimer())
                {
                    log.WarnFormat("Unable to disable the timer for Monitor ID: {0}", mc.MonitorID);
                }
                // TODO: Does the thread need joining back??

                // change the monitor state
                try
                {
                    Model.Monitor monitor = db.Single <Model.Monitor>("Select * from Monitor WHERE MonitorID = @monitorID", new { monitorID = mc.MonitorID });
                    monitor.State = Model.MonitorState.Idle.ToString();
                    db.Update(monitor);
                }
                catch (Exception ex)
                {
                    log.WarnFormat("Unable to set the monitor state to Idle for monitor ID: {0}", mc.MonitorID);
                    log.ErrorFormat(ex.ToString());
                }
            }
        }
Ejemplo n.º 2
0
        private static Model.Monitor TranEntity(DataRow dr, string RoleCode)
        {
            Model.Monitor model = new Model.Monitor();

            if (dr["Field1"] != null)
            {
                model.Field1 = Convert.ToDecimal(dr["Field1"]).ToFixedDecimal().ToString();
            }
            if (dr["Field2"] != null)
            {
                model.Field2 = Convert.ToDecimal(dr["Field2"]).ToFixedDecimal().ToString();
            }
            if (dr["Field3"] != null)
            {
                model.Field3 = Convert.ToDecimal(dr["Field3"]).ToFixedDecimal().ToString();
            }
            if (dr["Field4"] != null)
            {
                model.Field4 = Convert.ToDecimal(dr["Field4"]).ToFixedDecimal().ToString();
            }
            if (dr["Field5"] != null)
            {
                model.Field5 = Convert.ToDecimal(dr["Field5"]).ToFixedDecimal().ToString();
            }
            if (dr["Field6"] != null)
            {
                model.Field6 = Convert.ToDecimal(dr["Field6"]).ToFixedDecimal().ToString();
            }
            if (dr["Field7"] != null)
            {
                model.Field7 = Convert.ToDecimal(dr["Field7"]).ToFixedDecimal().ToString();
            }
            if (dr["Field10"] != null)
            {
                model.Field10 = Convert.ToDecimal(dr["Field10"]).ToFixedDecimal().ToString();
            }
            if (dr["Field11"] != null)
            {
                model.Field11 = Convert.ToDecimal(dr["Field11"]).ToFixedDecimal().ToString();
            }
            if (dr["Field20"] != null)
            {
                model.Field20 = Convert.ToDecimal(dr["Field20"]).ToFixedDecimal().ToString();
            }

            model.Field8 = GetMemberTypeCount(RoleCode);

            if (Convert.ToDecimal(model.Field1) > 0)
            {
                model.Field9 = string.Format("{0:N2}%", ((Convert.ToDecimal(model.Field2)) / (Convert.ToDecimal(model.Field1))) * 100);
            }
            else
            {
                model.Field9 = "";
            }
            return(model);
        }
Ejemplo n.º 3
0
        public RunMonitor()
            : base("/run/monitor")
        {
            this.RequiresAuthentication();
            // TODO: need to change to have run claims
            this.RequiresAnyClaim(new[] { "editMonitor", "admin" });

            var db = new PetaPoco.Database("LocalSQLite");

            Get["/{id}"] = parameters =>
            {
                try
                {
                    int monitorID = (int)parameters.id;

                    Model.Monitor monitor = db.Single <Model.Monitor>("Select * from Monitor WHERE MonitorID = @monitorID", new { monitorID = monitorID });

                    // check the monitor should run
                    if (monitor.State == Model.MonitorState.Running.ToString() && monitor.RunMultiple == 0)
                    {
                        log.InfoFormat("Monitor [{0}] is in a running state - not running a multiple version (initiated from web request)", monitor.MonitorID);
                        return(Response.AsJson(new
                        {
                            success = false,
                            message = "Monitor is already running and is configured not to run multiple versions."
                        }));
                    }

                    // should check id is an int and the state of the monitor
                    //Thread thread = new Thread(App.Monitor.Run(monitor));
                    // maybe change to a task factory or thread pool
                    //http://stackoverflow.com/questions/8014037/c-sharp-call-a-method-in-a-new-thread
                    Thread thread = new Thread(() => App.Monitor.Run(monitor));
                    thread.Start();
                    return(Response.AsJson(new
                    {
                        success = true,
                        message = "Running the monitor"
                    }));;
                }
                catch (Exception ex)
                {
                    // Log error on the server - maybe should have ID in the URL so it can be part of the exception
                    log.WarnFormat("Error whilst trying to run monitor. Exception: {0}", ex.ToString());
                    // TODO: alert?
                    return(Response.AsJson(new
                    {
                        success = false,
                        message = ex.ToString()
                    }));
                }
            };
        }
Ejemplo n.º 4
0
        public static void Run(object input)
        {
            var db = new PetaPoco.Database("LocalSQLite");

            // cast the input object
            //Model.Monitor monitor = input as Model.Monitor;

            int monitorID = (int)input;

            Model.Monitor monitor = db.Single <Model.Monitor>("Select * from Monitor WHERE MonitorID = @monitorID", new { monitorID = monitorID });

            Run(monitor);
        }
Ejemplo n.º 5
0
        public static bool IsActive(Model.Monitor m)
        {
            var mc = _monitorRunPool.Where(x => x.MonitorID == m.MonitorID);

            if (mc.Count() == 1)
            {
                return(true);
            }
            else if (mc.Count() > 1)
            {
                // log an error as something has gone very wrong (should, at most be 1 here).
                // TODO: should they be stopped and one started? will it every get here?
                throw new Exception("Multiple versions of monitor [id: {0}] are running");
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 6
0
        public static void setState(Model.Monitor m)
        {
            if (m.Active == 1)
            {
                // verify it's not already running
                if (IsActive(m))
                {
                    throw new Exception("monitor [ID: " + m.MonitorID + "] already running");
                }

                new Monitor(m);
            }
            else
            {
                // verify the monitor isn't running
                if (!IsActive(m))
                {
                    throw new Exception("monitor [ID: " + m.MonitorID + "] isn't running");
                }

                Disable(m.MonitorID);
            }
        }
Ejemplo n.º 7
0
        public WriteMonitor()
            : base("/write/monitor")
        {
            this.RequiresAuthentication();
            this.RequiresAnyClaim(new[] { "editMonitor", "admin" });

            // db reference
            var db = new PetaPoco.Database("LocalSQLite");

            // datatable functions

            Post["/dt/edit"] = pameters =>
            {
                // try\catch return  success\fail
                try
                {
                    Model.Monitor m = new Model.Monitor();
                    // get the previous verison of the monitor and then set up the monitor event handlers
                    // not doing it like this anymore
                    //m.PropertyChanged += new PropertyChangedEventHandler(App.Monitor.HandleActiveChangeEvent);
                    m = this.Bind();

                    log.InfoFormat("Updating monitor (ID: {0})", m.MonitorID.ToString());

                    // change the monitor state in the app layer/
                    if (Convert.ToBoolean(m.Active) != App.Monitor.IsActive(m))
                    {
                        App.Monitor.setState(m);
                    }

                    // TODO: get a previous version of the monitor and check if the interval has changed.
                    // Change the interval
                    if (m.Active == 1)
                    {
                        App.Monitor.ChangeInterval(m.MonitorID, m.RunInterval);
                    }

                    // persist the monitor, without the State column
                    db.Update(m, m.ColumnsToUpdateFromWeb);

                    return(Response.AsJson(new
                    {
                        success = true,
                        aaData = m
                    }));
                }
                catch (Exception ex)
                {
                    // Log error on the server - maybe should have ID in the URL so it can be part of the exception
                    log.WarnFormat("Error whilst editing monitor. Exception: {0}", ex.ToString());
                    // TODO: alert?
                    return(Response.AsJson(new
                    {
                        success = false,
                        message = ex.ToString()
                    }));
                }
            };

            Post["/dt/new"] = pameters =>
            {
                // try\catch return  success\fail
                Model.Monitor m = new Model.Monitor();

                log.InfoFormat("Adding new monitor (ID: {0})", m.MonitorID.ToString());

                try
                {
                    db.Insert(m);
                    // TODO: check if the monitor needs to start
                    return(Response.AsJson(new
                    {
                        success = true,
                        monitor = m
                    }));
                }
                catch (Exception ex)
                {
                    return(Response.AsJson(new
                    {
                        success = false,
                        message = ex.ToString()
                    }));
                }
            };

            Post["/dt/delete"] = parameter =>
            {
                try
                {
                    Model.Monitor m = new Model.Monitor();
                    m = this.Bind();

                    log.InfoFormat("Deleting monitor (ID: {0})", m.MonitorID.ToString());

                    db.Delete(m);

                    return(Response.AsJson(new
                    {
                        success = true
                    }));
                }
                catch (Exception ex)
                {
                    // Log error on the server - maybe should have ID in the URL so it can be part of the exception
                    log.WarnFormat("Error whilst deleting monitor. Exception: {0}", ex.ToString());
                    // TODO: alert?
                    return(Response.AsJson(new
                    {
                        success = false,
                        message = ex.ToString()
                    }));
                }
            };
        }
Ejemplo n.º 8
0
 protected override void SetPowerZone()
 {
     model = BLL.Monitor.GetMonitor();
 }
Ejemplo n.º 9
0
 public Monitor(Model.Monitor m)
 {
     _monitorRunPool.Add(new MonitorClass(m.MonitorID, m.RunInterval));
 }
Ejemplo n.º 10
0
        public static void Run(Model.Monitor monitor)
        {
            var db = new PetaPoco.Database("LocalSQLite");

            // check the monitor should run
            if (monitor.State == Model.MonitorState.Running.ToString() && monitor.RunMultiple == 0)
            {
                log.InfoFormat("Monitor [{0}] is in a running state - not running a multiple version", monitor.MonitorID);
                return;
            }

            monitor.State = Model.MonitorState.Running.ToString();
            db.Update(monitor);

            log.InfoFormat("Monitor (ID: {2}) running on Thread Id {0} with the sql {1}", Thread.CurrentThread.ManagedThreadId.ToString(), monitor.SQL, monitor.MonitorID);

            // Sleeping to test the web interface update
            //Thread.Sleep(10000);

            // start the job
            var job = new Model.Job();

            job.MonitorID = monitor.MonitorID;
            job.StartTime = DateTime.Now.ToString();
            db.Insert(job);

            // set the local directory
            string monitorFolder = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + monitor.MonitorID;

            try
            {
                if (File.Exists(monitorFolder))
                {
                    log.InfoFormat("Folder ({0}) exists, setting current location to that", monitorFolder);
                    Directory.SetCurrentDirectory(monitorFolder);
                }
                else
                {
                    log.InfoFormat("Folder ({0}) doesn't exist, creating the folder", monitorFolder);
                    DirectoryInfo di = Directory.CreateDirectory(monitorFolder);
                    log.InfoFormat("setting current location to that {0}", monitorFolder);
                    Directory.SetCurrentDirectory(monitorFolder);
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat(@"Unable to create and\or set directory {0}", monitorFolder);
                log.Error(ex.ToString());
            }


            int RowCount = 0;

            try
            {
                DataTable dt;
                // switch on the type of monitor
                switch (monitor.Type.ToUpper())
                {
                case "EVENTVWR":
                    //case Model.MonitorType.Eventvwr:
                    if (monitor.isBathStatement())
                    {
                        if (monitor.intoFileName() == null)
                        {
                            throw new Exception("filename (as parsed from the SQL) is null - shouldn't be");
                        }

                        string fileName    = @".\" + monitor.intoFileName();
                        string newFileName = @".\" + job.JobID + "." + monitor.intoFileName();
                        try
                        {
                            if (String.IsNullOrEmpty(monitor.Checkpoint))
                            {
                                LogParser.BatchEventLog(monitor.SQL);
                            }
                            else
                            {
                                LogParser.BatchEventLog(monitor.SQL, monitor.Checkpoint);
                            }
                            //rename the output to include the jobId

                            if (File.Exists(fileName))
                            {
                                File.Move(fileName, newFileName);
                                RowCount = -1;
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error running batch execute against Event Log", ex);
                        }
                        job.Batch      = 1;
                        job.Info       = newFileName;
                        job.FinalState = "Complete";
                    }
                    else
                    {
                        try
                        {
                            if (String.IsNullOrEmpty(monitor.Checkpoint))
                            {
                                dt = LogParser.ParseEventLog(monitor.SQL);
                            }
                            else
                            {
                                dt = LogParser.ParseEventLog(monitor.SQL, monitor.Checkpoint);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error parsing Event Log", ex);
                        }
                        RowCount = dt.Rows.Count;
                        // convert the DataTable into a list of Model.Eventvwr (with the JobId) and insert into the DB
                        try
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                db.Insert(new Model.Eventvwr(row, job.JobID));
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error saving Event Viewer data", ex);
                        }
                        job.Info       = "Job returned " + RowCount.ToString() + " rows";
                        job.FinalState = "Complete";
                    }
                    break;

                case "IIS":
                    if (monitor.isBathStatement())
                    {
                        if (monitor.intoFileName() == null)
                        {
                            throw new Exception("filename (as parsed from the SQL) is null - shouldn't be");
                        }

                        string fileName    = @".\" + monitor.intoFileName();
                        string newFileName = @".\" + job.JobID + "." + monitor.intoFileName();
                        try
                        {
                            if (String.IsNullOrEmpty(monitor.Checkpoint))
                            {
                                LogParser.BatchIISLog(monitor.SQL);
                            }
                            else
                            {
                                LogParser.BatchIISLog(monitor.SQL, monitor.Checkpoint);
                            }
                            //rename the output to include the jobId

                            if (File.Exists(fileName))
                            {
                                File.Move(fileName, newFileName);
                                RowCount = -1;
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error running batch execute against Event Log", ex);
                        }
                        job.Batch      = 1;
                        job.Info       = newFileName;
                        job.FinalState = "Complete";
                    }
                    else
                    {
                        try
                        {
                            if (String.IsNullOrEmpty(monitor.Checkpoint))
                            {
                                dt = LogParser.ParseIISLog(monitor.SQL);
                            }
                            else
                            {
                                dt = LogParser.ParseIISLog(monitor.SQL, monitor.Checkpoint);
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error parsing IIS Log", ex);
                        }
                        RowCount = dt.Rows.Count;
                        // convert the DataTable into a list of Model.Eventvwr (with the JobId) and insert into the DB
                        try
                        {
                            foreach (DataRow row in dt.Rows)
                            {
                                db.Insert(new Model.IIS(row, job.JobID));
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Error saving IIS Log data", ex);
                        }
                        job.Info       = "Job returned " + RowCount.ToString() + " rows";
                        job.FinalState = "Complete";
                    }
                    break;

                default:
                    job.Info       = "Monitor type [" + monitor.Type + "] not implemented";
                    job.FinalState = "Error";
                    db.Update(job);
                    throw new Exception(job.Info);
                }
            }
            catch (Exception ex)
            {
                job.Info       = ex.ToString();
                job.FinalState = "Error";
            }
            finally
            {
                if (monitor.Alert == 1)
                {
                    if (job.FinalState == "Error")
                    {
                        log.Error("Sending error email");
                        log.ErrorFormat("{0}", job.Info);
                        // send email saying job errored
                        Helpers.Email.Send("*****@*****.**", monitor.EmailAddresses, "Error on Monitor [" + monitor.Name + "] ", job.Info);
                        monitor.State = Model.MonitorState.Alert.ToString();
                    }
                    else if (RowCount > 0)
                    {
                        log.Info("Sending alert email");
                        monitor.State = Model.MonitorState.Alert.ToString();
                        // send email saying rowcount is greater than 0, include link to data
                        Helpers.Email.Send("*****@*****.**", monitor.EmailAddresses, "Alert on Monitor [" + monitor.Name + "] ", "The monitor returned " + RowCount.ToString() + " rows. </br> More information here: <a href='http://*****:*****@".\" + job.JobID + "." + monitor.intoFileName()
                        log.Info("Sending alert email");
                        monitor.State = Model.MonitorState.Alert.ToString();
                        // send email saying rowcount is greater than 0, include link to data
                        Helpers.Email.AttachAndSend("*****@*****.**", monitor.EmailAddresses, "Alert on Monitor [" + monitor.Name + "] ", "The monitor returned the attached file. </br> More information here: <a href='http://*****:*****@".\" + job.JobID + "." + monitor.intoFileName());
                    }
                }
                else
                {
                    monitor.State = Model.MonitorState.Idle.ToString();
                }
            }

            // catch monitor state still in running
            if (monitor.State == Model.MonitorState.Running.ToString())
            {
                monitor.State = Model.MonitorState.Idle.ToString();
            }

            job.EndTime = DateTime.Now.ToString();
            db.Update(job);
            db.Update(monitor);
        }